Search code examples
templatesgogo-gin

In golang gin simple template example, how do you render a string without quotes?


Using example golang gin code from README:

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>

But how can I get it without the quotes, I need just bar vs "bar"?


Solution

  • the template package implements an HTML context aware engine to provide injection safe html.

    In other words it knows it executes inside a script tag, thus it does not output raw string but json encoded strings compatible with js.

    To fix it, unlike the comment suggests, make the string a template.JS value and the security measures will not attempt to protect the strings.

    ref - 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