使用text/template包如何评估字段?go

huangapple go评论84阅读模式
英文:

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}}`

huangapple
  • 本文由 发表于 2015年3月9日 02:30:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/28930267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定