You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:34:58