英文:
How to inject Javascript in html template (html/template) with Golang?
问题
有没有办法在Golang的HTML模板(html/template)中将JavaScript作为变量注入?我希望脚本能够被注入到模板中,但实际上脚本被作为字符串注入到了"中。
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>"})
...
渲染后的HTML输出:
...
<head>
    "<script>console.log('Hello World!');</script>"
</head>
...
期望的输出:
<head>
    <script>console.log('Hello World!');</script>
   // 并且应该在控制台中记录Hello World!
</head>
英文:
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
得分: 1
假设您正在使用html/template包,这是预期的行为。普通字符串不应该能够注入HTML/JS代码。
如果您信任内容,可以使用template.JS或template.HTML类型来注入JS和HTML代码。
return tmpl.Execute(writer, myObject{
  Script: template.HTML("<script>console.log('Hello World!');</script>")})
当然,您需要声明:
type myObject struct {
   Script template.HTML
   ...
}
而不是string。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论