Switch or if/elseif/else inside golang HTML templates

Denys Séguret picture Denys Séguret · Jun 7, 2013 · Viewed 75.6k times · Source

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 ?

Answer

Florian Margaine picture Florian Margaine · Jun 7, 2013

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