使用自述文件中的示例 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>
但是没有引号我怎么能得到它,我只需要
bar
对比 "bar"
?
最佳答案
模板包实现了一个 HTML 上下文感知引擎来提供注入(inject)安全的 html。
换句话说,它知道它在脚本标签内执行,因此它不输出原始字符串,而是输出与 js 兼容的 json 编码字符串。
要修复它,与评论建议的不同,将字符串设为 template.JS
value 和安全措施不会试图保护字符串。
引用
- https://golang.org/pkg/html/template/
Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
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
关于templates - 在 golang gin 简单模板示例中,如何呈现不带引号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261897/