How can I chain multiple conditions using indirect template functions in Go?
I want to check if .hello
doesn't contain "world" and .world
doesn't contain "hello", but I cannot because I got 2009/11/10 23:00:00 executing template: template: content:2:5: executing "content" at <not>: wrong number of args for not: want 1 got 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 playground link: https://go.dev/play/p/lWZwjbnSewy
not
expects one argument, so yo have to use parenthesis.
If you do, 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 the Go Playground):
not passed
You can also write this condition as not contains "hello" and not contains "world"
, which would look like this:
{{if and (not (contains .hello "hello")) (not (contains .world "hello")) }}