Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch or if/elseif/else inside golang HTML templates

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 ?

like image 347
Denys Séguret Avatar asked Jun 07 '13 13:06

Denys Séguret


1 Answers

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}} 
like image 78
Florian Margaine Avatar answered Sep 28 '22 03:09

Florian Margaine