Search code examples
goescaping

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>

Solution

  • 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}}