xpt
xpt

Reputation: 22994

Go template is adding extra quotes to output

I want to use the value of my variable in Go template as-is but Go is adding extra quotes around it. E.g., for a Go template like

{{.Site}}:{{.Port}}/{{.Path}}

I want to get the output as

Mysite:3000/from/here

but the template is giving me the following instead:

"Mysite":"3000"/"from/here"

So,

Upvotes: 1

Views: 5233

Answers (1)

xpt
xpt

Reputation: 22994

As per Go HTML template doc:

HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.

The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below.

It means JavaScript escaping is enabled whenever the go HTML template engine detects that it is within a <script> tag, (i.e., it has nothing to do with whether using regular " or not as the first commenter thinks). So

to get the output as

Mysite:3000/from/here

instead of:

"Mysite":"3000"/"from/here"

Do not wrap it with <script> & </script> tag. Do the concatenation after template Execute().

Again, with <script> & </script> tag wrapped around, I'm getting:

var url = `"Mysite":"3000"/"from/here"/${othervars}?"orgId=1\u0026refresh=30s"`

vs. without <script> & </script> tag wrapped around it, I'm getting:

var url = `Mysite:3000/from/here/${othervars}?orgId=1&amp;refresh=30s`

Just what I need.

However, my actual case is that I'm using go HTML template engine to process my .html template files, so I cannot really do the concatenation afterwards, as everything is defined in the .html template file. So, just as Martin Gallagher has shown in his code, for such case, using template function seems to be the only option.

But even that might not be a viable option, as this is what I'm getting out of Martin's code:

var url = "Mysite:3000\/from\/here?orgId=1\u0026refresh=30s"

It is still not exactly what I wanted:

var url = `Mysite:3000/from/here/${othervars}?orgId=1&amp;refresh=30s`

So maybe with such case, it indeed has no ideal solution.

Upvotes: 1

Related Questions