【问题标题】:How to get rid of ZgotmplZ from html/template in Golang?如何从 Golang 中的 html/template 中删除 ZgotmplZ?
【发布时间】:2021-12-21 23:13:08
【问题描述】:

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

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

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

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

但是代码没有编译。

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

【问题讨论】:

标签: html templates url go go-html-template


【解决方案1】:

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 上试试这些。

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多