英文:
How to evaluate fields using text/template package? go
问题
我有一个模板,我想使用text/template包来评估各种字段。我很难弄清楚评估应该如何工作,因为下面的代码似乎失败了。模板包是否足够强大,可以处理这种类型的评估?
type something struct{
Brand string
}
tpl := `{{if .Brand == "Coke"}} It's a coke{{else}} It's something else{{end}}`
英文:
I have a template and I would like to evaluate various fields using the text/template package. I have a hard to time to figure it out how the evaluation should work because the code below seems to fail. Is the template package powerful enough to handle this kind of evaluations?
type something struct{
Brand string
}
tpl := `{{if .Brand == "Coke"}} It's a coke{{else}} It's something else{{end}}`
答案1
得分: 2
在模板包中有一个名为eq
的全局函数,你可以调用它。不确定为什么它的工作方式是这样的,但是下面是代码示例:
type something struct{
Brand string
}
tpl := `{{if eq .Brand "Coke"}} It's a coke{{else}} It's something else{{end}}`
这段代码使用了模板语法,如果.Brand
的值等于"Coke",则输出"It's a coke",否则输出"It's something else"。
英文:
There is a global function in the templates package named eq
that you can call. Not sure why it works like that but here is the code
type something struct{
Brand string
}
tpl := `{{if eq .Brand "Coke"}} It's a coke{{else}} It's something else{{end}}`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论