templates - 在 golang gin 简单模板示例中,如何呈现不带引号的字符串?

标签 templates go go-gin

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


  • https://golang.org/pkg/html/template/#JS

  • 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/

    相关文章:

    C++ 运算符= return *this 后的结果发生变化

    c++ - 具有成员运算符*的模板化运算符*的友元声明

    go - 安装 go 模块失败并显示 `invalid: module contains a go.mod file, so major version must be compatible`

    go - 将参数解析为 bool 或仅在 switch 语句中使用字符串

    c++ - 从 vector 中的父基转换的模板化子 T 生成的虚假字符

    c++ - 用类参数化的类和与辅助函数的混淆

    go - 我可以在共享网络服务器上使用 go 来生成 HTML 吗?

    go - 在 Golang 中使用 Gin 获取反向代理与 TLS(到代理服务器)一起工作时遇到问题

    go - 服务器发送事件意外行为

    go - 如何记录或打印使用 Gin 收到的请求?