Why am I seeing ZgotmplZ in my Go HTML template output?

后端 未结 6 975
执念已碎
执念已碎 2020-12-10 23:31

When I\'m calling a Go template function to output HTML, it displays ZgotmplZ.

Sample code:

http://play.golang.org/p/tfuJa_pFkm

         


        
6条回答
  •  心在旅途
    2020-12-11 00:35

    "ZgotmplZ" is a special value that indicates that unsafe content reached a CSS or URL context at runtime. The output of the example will be:

     
    

    You can add a safe and attr function to the template funcMap:

    package main

    import (
        "html/template"
        "os"
    )
    
    func main() {
        funcMap := template.FuncMap{
            "attr":func(s string) template.HTMLAttr{
                return template.HTMLAttr(s)
            },
            "safe": func(s string) template.HTML {
                return template.HTML(s)
             },
        }
    
        template.Must(template.New("Template").Funcs(funcMap).Parse(`
        
            {{.html|safe}}
         `)).Execute(os.Stdout,   map[string]string{"attr":`selected="selected"`,"html":``})
    }
    

    The output will look like:

    
    
    

    You may want to define some other functions which can convert string to template.CSS, template.JS, template.JSStr, template.URL etc.

提交回复
热议问题