Switch或if / elseif / else内部的golang HTML模板 [英] Switch or if/elseif/else inside golang HTML templates
问题描述
const(
paragraph_hypothesis = 1 paragraph_attachment = 1 paragraph_menu = 1
)
类型段落结构{
键入int // paragraph_hypothesis或paragraph_attachment或paragraph_menu
}
我想在中显示段落类型
$ b
我发现的唯一解决方案是基于专用函数,如 isAttachment
测试在Go中键入
并嵌套 {{if}}
:
{{range .Paragraphs}}
{{if .IsAttachment}}
- 附件演示文稿代码 -
{{else}} {{if .IsMenu}}
- 菜单 -
{{else}}
- 默认代码 -
{{end}} {{end}}
{{end}}
事实上,我有更多的类型,这使得它更怪,去代码使用 IsSomething
函数和模板与 {{end}}
。
干净的解决方案是什么?在go模板中是否存在 switch
或 if / elseif / else
解决方案?或者完全不同的方式来处理这些情况?
模板无逻辑。他们不应该有这种逻辑。你可以拥有的最大逻辑是一堆 if if
。
在这种情况下,您应该这样做:
{{if .IsAttachment}}
- 附件演示文稿代码 -
{{end}}
{{if .IsMenu}}
- 菜单 -
{{end}}
{{if .IsDefault}}
- 默认代码 -
{{end}}
I have this struct :
const (
paragraph_hypothesis = 1<<iota
paragraph_attachment = 1<<iota
paragraph_menu = 1<<iota
)
type Paragraph struct {
Type int // paragraph_hypothesis or paragraph_attachment or paragraph_menu
}
I want to display my paragraphs in a Type
dependent way.
The only solution I found was based on dedicated functions like isAttachment
testing the Type
in Go and nested {{if}}
:
{{range .Paragraphs}}
{{if .IsAttachment}}
-- attachement presentation code --
{{else}}{{if .IsMenu}}
-- menu --
{{else}}
-- default code --
{{end}}{{end}}
{{end}}
In fact I have more types, which makes it even weirder, cluttering both the Go code with IsSomething
functions and the template with those {{end}}
.
What's the clean solution ? Is there some switch
or if/elseif/else
solution in go templates ? Or a completely different way to handle these cases ?
Templates are logic-less. They're not supposed to have this kind of logic. The maximum logic you can have is a bunch of if
.
In such a case, you're supposed to do it like this:
{{if .IsAttachment}}
-- attachment presentation code --
{{end}}
{{if .IsMenu}}
-- menu --
{{end}}
{{if .IsDefault}}
-- default code --
{{end}}
这篇关于Switch或if / elseif / else内部的golang HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!