safeJS being ignored

I’m building my own disqus partial (I’ve got some weird requirements for my site so I can’t use the built in support) and am running into issues trying to build a URL string. This is what I have:

this.page.url = 'http://www.raymondcamden.com{{ .URL | safeJS }}';

I am using safeJS because I do not want the forward slashes in the value escaped. However, I’m still seeing this in source:

this.page.url = 'http://www.raymondcamden.com\/2015\/12\/28\/favorite-media-in-2015';

Any idea why?

Is it inside script tags? You could try safeURL

No go. Still modifies it.

And yes, it is inside script tags. Sorry I didn’t answer that question.

Strange as it sounds, try removing the quotes around the string. You should see in the rendered page the .URL value replaced with the URL, quoted. The Go template parser is context-aware, and so auto-quotes text inside JavaScript blocks. It took me a few attempts playing with the syntax to get what I wanted, but I wouldn’t have ever thought to remove the quotes had I not seen this comment.

I did, but it didn’t work. Here is how I tested:

var raymond = http://www.raymondcamden.com{{ .URL | safeURL }}; 

And the output:

var raymond = http:

I’ve found Go templates are very picky about context. You generally need to output the entire string, not part of it. Try something like this in a script context:

var raymond = {{ printf "http://www.raymondcamden.com%s" .URL | safeJS }}

Close - that output it perfectly, but without single quotes around it. So I got:

var raymond = http://www.raymondcamden.com/2016/03/07/how-i-added-search-to-my-static-blog;

(I added a ; to the end)

Oh, and if I add single quotes around it, it goes back to the broken, well, escaped, version.

Ok, so this worked:

var raymond = {{ printf "'http://www.raymondcamden.com%s'" .URL | safeJS }};

Holy smokes does that seem wrong. There really should be a way for me to say, “Don’t modify anything in this block - period”.

That’s probably my fault. Try removing safeJS, and it should quote the string for you.

1 Like