登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-28 18:24:34 435浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《如何从 Golang 中的 html/template 中删除 ZgotmplZ?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我在后端使用 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 的文档:

如果您想替换有效网址文本,则无需像 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 上尝试这些。

理论要掌握,实操不能落!以上关于《如何从 Golang 中的 html/template 中删除 ZgotmplZ?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>