为什么我在 Go HTML 模板输出中看到 ZgotmplZ? [英] Why am I seeing ZgotmplZ in my Go HTML template output?
本文介绍了为什么我在 Go HTML 模板输出中看到 ZgotmplZ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我调用 Go 模板函数输出 HTML 时,它显示 ZgotmplZ
.
When I'm calling a Go template function to output HTML, it displays ZgotmplZ
.
示例代码:
http://play.golang.org/p/tfuJa_pFkm
package main
import (
"html/template"
"os"
)
func main() {
funcMap := template.FuncMap{
"printSelected": func(s string) string {
if s == "test" {
return `selected="selected"`
}
return ""
},
"safe": func(s string) template.HTML {
return template.HTML(s)
},
}
template.Must(template.New("Template").Funcs(funcMap).Parse(`
<option {{ printSelected "test" }} {{ printSelected "test" | safe }} >test</option>
`)).Execute(os.Stdout, nil)
}
输出:
<option ZgotmplZ ZgotmplZ >test</option>
推荐答案
"ZgotmplZ" 是一个特殊值,表示不安全的内容达到了运行时的 CSS 或 URL 上下文.该示例的输出将是:
"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:
<img src="#ZgotmplZ">
你可以在模板funcMap中添加一个safe和attr函数:
You can add a safe and attr function to the template funcMap:
包主
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(`
<option {{ .attr |attr }} >test</option>
{{.html|safe}}
`)).Execute(os.Stdout, map[string]string{"attr":`selected="selected"`,"html":`<option selected="selected">option</option>`})
}
输出将如下所示:
<option selected="selected" >test</option>
<option selected="selected">option</option>
你可能想定义一些其他的函数,可以将字符串转换为 template.CSS、template.JS、template.JSStr、template.URL 等.
You may want to define some other functions which can convert string to template.CSS, template.JS, template.JSStr, template.URL etc.
这篇关于为什么我在 Go HTML 模板输出中看到 ZgotmplZ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文