Home > OS >  Go Template if value is set and is false
Go Template if value is set and is false

Time:01-06

I am using Listmonk which utilizes Go Templates. I have a situation where a variable for user status (.Subscriber.Attribs.Pro) may exist (and if it does, it is true or false. I want to display a block of text only if the value exists.

The code I have works if the Pro attribute is set. However if it is not set, it will be processed as not '' which leads to a value of true.

{{ if not .Subscriber.Attribs.Pro }}
  You are not a Pro user!
{{ end }}

How do I have this code run only if the Pro attribute is explicitly set to false

CodePudding user response:

So basically you only want to display the text if .Subscriber.Attribs.Pro is supplied and is false. So do a comparison:

{{ if eq false .Subscriber.Attribs.Pro }}
    You are not a Pro user!
{{ end }}

We can test it like:

t := template.Must(template.New("").Parse("{{ if eq false .Pro }}You are not a Pro user!\n{{ end }}"))

fmt.Println("Doesn't exist:")
if err := t.Execute(os.Stdout, nil); err != nil {
    panic(err)
}

fmt.Println("Pro is false:")
m := map[string]interface{}{
    "Pro": false,
}
if err := t.Execute(os.Stdout, m); err != nil {
    panic(err)
}

fmt.Println("Pro is true:")
m["Pro"] = true
if err := t.Execute(os.Stdout, m); err != nil {
    panic(err)
}

Output will be (try it on the Go Playground):

Doesn't exist:
Pro is false:
You are not a Pro user!
Pro is true:

As you can see, the {{if}} block is only executed when Pro is explicitly set to false.

CodePudding user response:

Use the included Sprig hasKey function:

{{if hasKey .Subscriber.Attribs "Pro"}}
    {{ if not .Subscriber.Attribs.Pro }}
        You are not a Pro user!
     {{ end }}
{{ end }}
  •  Tags:  
  • Related