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

标签 html templates url go go-html-template

我在后端使用 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/

相关文章:

html - 尽管我在 CSS 中放置了 "list-style:none",但仍然列出元素符号

html - float DIV 无法正常流动

c++ - 如何编译非类型模板参数?

php - 如何在不使用 URL 中的 .php 的情况下访问 php 页面

url - (本地)文件路径是 URI 吗?

javascript - 更改页面时 Intel XDK jQuery Mobile 错误

c++ - 如何克服 GCC 限制 "could not convert template argument ' 0' to ' Foo *'"?

c++ - 为什么 typedef 模板是非法的?

Javascript:在文档中查找 URL

html - 仅使用 css 均衡 2 div 高度