ZgotmplZ是一个特殊值,表示您的输入无效。从html/template的文档引用:
"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
If the data comes from a trusted source, use content types to exempt it
from filtering: URL(`javascript:...`).
如果你想替换一个有效 URL文本,没有什么特别喜欢像需要safeURL功能。如果您的模板执行结果的值为"#ZgotmplZ",则表示您要插入的网址无效。
见这个例子:
t := template.Must(template.New("").Parse(`` + "\n"))
t.Execute(os.Stdout, "http://google.com")
t.Execute(os.Stdout, "badhttp://google.com")
输出:
,如果你想使用URL作为,是不逃避您可以使用template.URL类型的值。请注意,在这种情况下,即使它不是有效的URL,所提供的值也会按原样使用。
safeURL不是某种可用于模板的魔术或预定义函数。但是,你可以注册一个返回string URL参数作为template.URL类型的值,你自己的自定义功能:
t2 := template.Must(template.New("").Funcs(template.FuncMap{
"safeURL": func(u string) template.URL { return template.URL(u) },
t2.Execute(os.Stdout, "http://google.com")
t2.Execute(os.Stdout, "badhttp://google.com")
输出:
注:如果你能在template.URL传递值不需要注册并使用safeURL()定制功能:
t3 := template.Must(template.New("").Parse(`` + "\n"))
t3.Execute(os.Stdout, template.URL("http://google.com"))
t3.Execute(os.Stdout, template.URL("badhttp://google.com"))
输出: