gpt4 book ai didi

html - 如何从 Golang 中的 html/template 中删除 ZgotmplZ?

转载 作者:IT王子 更新时间:2023-10-29 01:09:03 29 4
gpt4 key购买 nike

我在后端使用 Golang。当我使用 html/templates 呈现 html 时,我得到了 URL 的 ZgotmplZ

{{if .UserData.GitURL}}
<li>
<a href="{{.UserData.GitURL}}">
<i class="icon fa fa-github"></i>
</a>
</li>
{{end}}

我在服务器端为 GitURL 使用字符串。此 URL 为 https。当我寻找解决方案时,一些博客建议使用 safeURL。所以我尝试了,

{{if .UserData.GitURL}}
<li>
<a href="{{.UserData.GitURL | safeURL}}">
<i class="icon fa fa-github"></i>
</a>
</li>
{{end}}

但是代码没有编译。

有人可以帮我解决这个问题吗?任何建议都会非常有帮助。

最佳答案

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>

您可以使用 template.URL 类型的值如果您想按原样使用 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 上试试这些.

关于html - 如何从 Golang 中的 html/template 中删除 ZgotmplZ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382624/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com