2

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>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.