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
<img src="#ZgotmplZ">
If the data comes from a trusted source, use content types to exempt it
from filtering: URL(`javascript:...`).
如果您想替换 有效 url 文本,则不需要像 safeURL 函数这样的特殊功能。如果您的模板执行结果为 "#ZgotmplZ" 之类的值,则表示您要插入的 URL 无效。
看这个例子:
t := template.Must(template.New("").Parse(`<a href="{{.}}"></a>` + "\n"))
t.Execute(os.Stdout, "http://google.com")
t.Execute(os.Stdout, "badhttp://google.com")
输出:
<a href="http://google.com"></a>
<a href="#ZgotmplZ"></a>
如果您想按原样使用 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) },
}).Parse(`<a href="{{. | safeURL}}"></a>` + "\n"))
t2.Execute(os.Stdout, "http://google.com")
t2.Execute(os.Stdout, "badhttp://google.com")
输出:
<a href="http://google.com"></a>
<a href="badhttp://google.com"></a>
注意:如果您能够将template.URL 值直接传递给模板执行,则无需注册和使用safeURL() 自定义函数:
t3 := template.Must(template.New("").Parse(`<a href="{{.}}"></a>` + "\n"))
t3.Execute(os.Stdout, template.URL("http://google.com"))
t3.Execute(os.Stdout, template.URL("badhttp://google.com"))
输出:
<a href="http://google.com"></a>
<a href="badhttp://google.com"></a>
在Go Playground 上试试这些。