Golang text/template多条件结合not操作符的实现与报错解决
Go模板中链式多个条件的正确写法
你遇到的错误是因为not模板函数仅接受1个参数,但你直接传入了两个contains调用表达式,违反了函数参数规则。
要实现「.hello不包含"world" 且 .world不包含"hello"」的逻辑,需要用and函数结合not来组合两个否定条件,正确的代码如下:
package main import ( "log" "os" "strings" "text/template" ) var ( templateFuncMap = template.FuncMap{ "contains": strings.Contains, } ) func main() { // 修正后的模板 const temp = ` {{if and (not (contains .hello "world")) (not (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) } }
关键修改说明
- 使用
and函数连接两个独立的布尔条件,and支持接收多个参数,只有所有参数为真时才返回真 - 每个条件单独用
not包裹contains调用,确保not只接收一个布尔值参数,符合函数调用规则
内容的提问来源于stack exchange,提问作者Manticore
相关产品推荐
相关产品推荐

