WORMrus
WORMrus

Reputation: 169

How to stop html template from escaping

I have an html template where i want to insert some JavaScript code from outside of template itself. In my template data struct i have created a string field JS string and call it with {{.JS}}. The problem is that everything in browser is escaped:

newlines are \n

< and > are \u003c and \u003e

" is \"

Same symbols inside of a template are fine. If I Print my JS field into console it is also fine. I have seen some similar problems solved by using template.HTML type instead of string. In my case it does not work at all.

EDIT 1

The actual context is

<script language="JavaScript">
    var options = {
        {{.JS}}
    };
</script>

Upvotes: 7

Views: 6189

Answers (2)

mkopriva
mkopriva

Reputation: 38203

Either change the field's type to template.JS like so:

type Tmpl struct {
    // ...
    JS template.JS
}

Or declare a simple function that converts a string to the template.JS type like so:

func toJS(s string) template.JS {
    return template.JS(s)
}

And then register the function with the Funcs method and use it in your template like so:

{{toJS .JS}}

Upvotes: 14

syscll
syscll

Reputation: 1031

Try setting the type of JS to template.JS:

import "html/template"

type x struct {
        JS template.JS
}

Documentation can be found here.

Upvotes: 5

Related Questions