使用 README 中的示例 golang gin 代码:func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "foo": "bar", }) }}// in template index.tmpl<script>{{.foo}}</script>// result in html<script>"bar"</script>但是如果没有引号我怎样才能得到它,我只需要barvs "bar"?
1 回答
![?](http://img1.sycdn.imooc.com/5923e28b0001bb7201000100-100-100.jpg)
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
模板包实现了 HTML 上下文感知引擎来提供注入安全的 html。
换句话说,它知道它在 script 标签内执行,因此它不会输出原始字符串,而是与 js 兼容的 json 编码字符串。
要修复此问题,与评论建议的不同,请将字符串设置为template.JS
值,并且安全措施不会尝试保护字符串。
参考 - https://golang.org/pkg/html/template/
包模板 (html/template) 实现数据驱动模板,用于生成安全的 HTML 输出,防止代码注入。
使用此类型会带来安全风险:封装的内容应来自受信任的来源,因为它将逐字包含在模板输出中。
package main
import (
"html/template"
"os"
)
func main() {
c := `<script>
{{.foo}}
{{.oof}}
</script>`
d := map[string]interface{}{"foo": "bar", "oof": template.JS("rab")}
template.Must(template.New("").Parse(c)).Execute(os.Stdout, d)
}
https://play.golang.org/p/6qLnc9ALCeC
- 1 回答
- 0 关注
- 181 浏览
添加回答
举报
0/150
提交
取消