Home >Backend Development >Golang >Golang text/template multiple conditions with !not operator
php editor Xigua introduces you to an interesting feature in Golang - multiple conditions of text/template with !not operator. This feature is very practical in Golang's template engine and can help us handle conditional judgments more flexibly. By using the !not operator, we can judge multiple conditions at the same time in the template, simplify the code logic, and improve development efficiency. This article will introduce in detail how to use this feature and give some usage examples to help everyone better understand and apply it. Let’s explore this interesting Golang feature together!
How to use indirect template functions to link multiple conditions in Go?
I want to check if .hello
does not contain "world" and if .world
does not contain "hello" but I can't because I get 2009/11/ 10 23:00:00 Executing template: template : content:2:5: Executing "content" in 238ee6817c12cd3b0f999d2fed793ff9: not has the wrong number of parameters: want 1 Received 2
Error message
package main import ( "log" "os" "strings" "text/template" ) var ( templateFuncMap = template.FuncMap{ "contains": strings.Contains, } ) func main() { // Define a template. const temp = ` {{if not (contains .hello "hello") (contains .world "hello") }} passed {{else}} not passed {{end}}` s := map[string]string{ "hello": "world", "world": "hello", } t := template.Must(template.New("content").Funcs(templateFuncMap).Parse(temp)) err := t.Execute(os.Stdout, s) if err != nil { log.Println("executing template:", err) } }
Go to the playground link: https://go.dev/play/p/lWZwjbnSewy
not
requires a parameter, so brackets must be used .
If you do this, the condition you want to negate is contains "hello" or contains "world"
:
{{if not (or (contains .hello "hello") (contains .world "hello")) }}
This will output (try it on Go Playground):
not passed
You can also write this condition as not contains "hello" and not contains "world"
, as shown below:
{{if and (not (contains .hello "hello")) (not (contains .world "hello")) }}
The above is the detailed content of Golang text/template multiple conditions with !not operator. For more information, please follow other related articles on the PHP Chinese website!