在golang HTML模板中切换或if / elseif / else
发布时间:2020-12-16 19:20:50 所属栏目:大数据 来源:网络整理
导读:我有这个结构: const ( paragraph_hypothesis = 1iota paragraph_attachment = 1iota paragraph_menu = 1iota)type Paragraph struct { Type int // paragraph_hypothesis or paragraph_attachment or paragraph_menu} 我想以类型依赖的方式显示我的段落.
我有这个结构:
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 } 我想以类型依赖的方式显示我的段落. 我发现唯一的解决方案是基于专门的功能,如isAttachment测试类型Go和嵌套{{if}}: {{range .Paragraphs}} {{if .IsAttachment}} -- attachement presentation code -- {{else}}{{if .IsMenu}} -- menu -- {{else}} -- default code -- {{end}}{{end}} {{end}} 实际上,我有更多的类型,这使得它甚至更凶猛,使用IsSomething函数和Go {{end}}的模板混淆了Go代码. 什么是干净的解决方案? go模板中是否有某些开关或if / elseif / else解决方案?还是完全不同的方式来处理这些情况?
模板是无逻辑的.他们不应该有这样的逻辑.你可以拥有的最大逻辑是一堆if.
在这种情况下,您应该这样做: {{if .IsAttachment}} -- attachment presentation code -- {{end}} {{if .IsMenu}} -- menu -- {{end}} {{if .IsDefault}} -- default code -- {{end}} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |