golang template range 循环中引用外部变量

发布时间: 2022-05-16 14:06:24 作者: 大象笔记

LocalizeUrl 是我自定义的一个函数,接受两个参数,第一个参数是 url,第二个是语言。 但是在 gin template 中使用时报错。

报错的模板代码

{{ range $index, $product := .products }}
<a href={{ LocalizeUrl (printf "/product/%d" $product.ID) .lang }}>
{{ end }}

晦涩的报错信息

template: index.html:88:69: executing "index.html" at .lang: can't evaluate field lang in type models.Product

evaluate:中文翻译为:评估,鉴定。

range 循环中使用外部变量的正确姿势

就是在外部变量前,加上美元符号:

{{ range $index, $product := .products }}
<a href={{ LocalizeUrl (printf "/product/%d" $product.ID) $.lang }}>
{{ end }}

参考文档

可以优先看 text/template 的文档,因为其与 html/template 的接口是类似的,只不过 html/template 增加了对变量的转义。

我是一名山东烟台的开发者,联系作者