英文:
Go Template if value is set and is false
问题
我正在使用 Listmonk,它使用 Go Templates。我遇到了这样一种情况:用户状态的变量(.Subscriber.Attribs.Pro)可能存在(如果存在,则为 true 或 false)。我只想在该值存在时显示一段文本。
我已经有了一段代码,如果 Pro 属性被设置了,它可以正常工作。然而,如果没有设置,它会被处理为 not '',导致值为 true。
{{ if not .Subscriber.Attribs.Pro }}
You are not a Pro user!
{{ end }}
请问如何让这段代码仅在 Pro 属性明确设置为 false 时运行?
英文:
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
答案1
得分: 2
所以基本上,你只想在提供了.Subscriber.Attribs.Pro并且其值为false时显示文本。可以进行如下比较:
{{ if eq false .Subscriber.Attribs.Pro }}
You are not a Pro user!
{{ end }}
我们可以进行如下测试:
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)
}
输出结果将会是(可以在Go Playground上尝试):
Doesn't exist:
Pro is false:
You are not a Pro user!
Pro is true:
正如你所见,只有当Pro被明确设置为false时,{{if}}块的内容才会被执行。
英文:
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 body of the {{if}} block is only executed when Pro is explicitly set to false.
答案2
得分: 1
使用包含的Sprig的hasKey函数:
{{if hasKey .Subscriber.Attribs "Pro"}}
{{ if not .Subscriber.Attribs.Pro }}
你不是专业用户!
{{ end }}
{{ end }}
英文:
Use the included Sprig hasKey function:
{{if hasKey .Subscriber.Attribs "Pro"}}
{{ if not .Subscriber.Attribs.Pro }}
You are not a Pro user!
{{ end }}
{{ end }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论