Home > Back-end >  How to inject Javascript in html template (html/template) with Golang?
How to inject Javascript in html template (html/template) with Golang?

Time:09-21

Is there any way to inject Javascript as a variable in Golang html template (html/template). I was expecting the script to be injected in the template however script is injected as string inside ".

template.html

...
<head>
    {{ .myScript }}
</head>
...

parser.go

    ...
    fp := path.Join("dir", "shop_template.html")
    tmpl, err := template.ParseFiles(fp)
    if err != nil {
        return err
    }
    
    return tmpl.Execute(writer, myObject{Script: "<script>console.log('Hello World!');</script>"})
    ...

rendered html output:

...
<head>
    "<script>console.log('Hello World!');</script>"
</head>
...

Expected output

<head>
    <script>console.log('Hello World!');</script>
   // And should log Hello World! in the console.
</head>

CodePudding user response:

Assuming you are using the html/template package, this is the expected behavior. Regular strings should not be able to inject HTML/JS code.

If you trust the content, you can use template.JS or template.HTML types to inject JS and HTML code.

return tmpl.Execute(writer, myObject{
  Script: template.HTML("<script>console.log('Hello World!');</script>")})

Of course, you'll need to declare:

type myObject struct {
   Script template.HTML
   ...
}

instead of string.

  • Related