英文:
is there a way to list used variables?
问题
让我们假设我有一个基本的Go文本模板:
{{.var}} is another {{.var2}}
我想要获取模板中使用的变量名称的数组,以便在执行时如果这些变量在我传递给执行的数据中不存在,就可以跳过执行。有没有办法做到这一点?
由于我的数据不是结构体而是一个映射(map),使用 .var 会始终返回某个值:如果它不存在,那么在执行模板时它将返回一个空字符串,而我希望在执行模板时能够得到一个错误。
所以对于上面的示例,我希望得到的结果是:
[var var2]
英文:
Let's say I have a basic go text/template:
{{.var}} is another {{.var2}}
I want to get an array of the variables names used in the template, to be able to skip the execution if they are not available in the data I pass to execute, is it possible to do that somehow?
As my data is not a struct but a map, doing .var will always return something: if it doesn't exist, it will return an empty string when I would have hoped to get an error when executing the template.
So for the example from above, I would have liked to get:
[var var2]
答案1
得分: 5
使用一个模板函数,如果值未设置,则返回一个错误。类似这样:
template.FuncMap(map[string]interface{}{
"require": func(val interface{}) (interface{}, error) {
if val == nil {
return nil, errors.New("Required value not set.")
}
return val, nil
},
}))
然后在你的模板中使用:
{{require .Value}}
你可以在这里查看示例代码:http://play.golang.org/p/qZMBID7Y8L
英文:
Use a template func that returns an error if a value isn't set. Something like this:
template.FuncMap(map[string]interface{}{
"require": func(val interface{}) (interface{}, error) {
if val == nil {
return nil, errors.New("Required value not set.")
}
return val, nil
},
}))
Then in your template:
{{require .Value}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论