在golang gin简单模板示例中,如何渲染不带引号的字符串?

使用 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"?


慕妹3146593
浏览 182回答 1
1回答

qq_遁去的一_1

模板包实现了 HTML 上下文感知引擎来提供注入安全的 html。换句话说,它知道它在 script 标签内执行,因此它不会输出原始字符串,而是与 js 兼容的 json 编码字符串。要修复此问题,与评论建议的不同,请将字符串设置为template.JS值,并且安全措施不会尝试保护字符串。参考 -&nbsp;https://golang.org/pkg/html/template/包模板 (html/template) 实现数据驱动模板,用于生成安全的 HTML 输出,防止代码注入。https://golang.org/pkg/html/template/#JS使用此类型会带来安全风险:封装的内容应来自受信任的来源,因为它将逐字包含在模板输出中。package mainimport (&nbsp; &nbsp; "html/template"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; c := `<script>{{.foo}}{{.oof}}</script>`&nbsp; &nbsp; d := map[string]interface{}{"foo": "bar", "oof": template.JS("rab")}&nbsp; &nbsp; template.Must(template.New("").Parse(c)).Execute(os.Stdout, d)}https://play.golang.org/p/6qLnc9ALCeC
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go