在 golang gin 简单模板示例中,如何呈现不带引号的字符串?
In golang gin simple template example, how do you render a string without quotes?
使用自述文件中的示例 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
vs "bar"
?
模板包实现了一个 HTML 上下文感知引擎以提供安全注入 html。
换句话说,它知道它在脚本标签内执行,因此它不会输出原始字符串,而是 json 与 js 兼容的编码字符串。
要修复它,与评论建议的不同,将字符串设置为 template.JS
值,安全措施将不会尝试保护字符串。
参考
- 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)
}
使用自述文件中的示例 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
vs "bar"
?
模板包实现了一个 HTML 上下文感知引擎以提供安全注入 html。
换句话说,它知道它在脚本标签内执行,因此它不会输出原始字符串,而是 json 与 js 兼容的编码字符串。
要修复它,与评论建议的不同,将字符串设置为 template.JS
值,安全措施将不会尝试保护字符串。
参考 - 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)
}