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 ?
Yes, you can use
{{else if .IsMenu}}
You can achieve
switch
functionality by adding custom functions to the template.FuncMap.In the example below I've defined a function,
printPara (paratype int) string
which takes one of your defined paragraph types and changes it's output accordingly.Please note that, in the actual template, the
.Paratype
is piped into theprintpara
function. This is how to pass parameters in templates. Please note that there are restrictions on the number and form of the output parameters for functions added toFuncMap
s. This page has some good info, as well as the first link.Produces:
Playground link
Hope that helps, I'm pretty sure the code could be cleaned up a bit, but I've tried to stay close to the example code you provided.
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: