【问题标题】:In golang gin simple template example, how do you render a string without quotes?在 golang gin 简单模板示例中,如何渲染不带引号的字符串?
【发布时间】:2019-10-07 15:21:32
【问题描述】:

使用自述文件中的示例 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"

【问题讨论】:

  • "foo": template.HTML(""),如果您渲染整个脚本标签并从模板中删除脚本标签,似乎可以工作。

标签: templates go go-gin


【解决方案1】:

模板包实现了一个 HTML 上下文感知引擎来提供注入安全的 html。

换句话说,它知道它在脚本标签内执行,因此它不输出原始字符串,而是输出与 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    相关资源
    最近更新 更多