如何在使用Golang的html/template模板中注入JavaScript代码?

huangapple go评论83阅读模式
英文:

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.JStemplate.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(&quot;&lt;script&gt;console.log(&#39;Hello World!&#39;);&lt;/script&gt;&quot;)})

Of course, you'll need to declare:

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

instead of string.

huangapple
  • 本文由 发表于 2022年9月21日 01:56:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/73790853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定