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>
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.JSortemplate.HTMLtypes to inject JS and HTML code.Of course, you'll need to declare:
instead of
string.