如何在GO中使用间接模板函数链接多个条件?

我想判断.hello是否不包含"world",.world是否不包含"Hello",但我不能,因为我收到了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错误消息

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操场链接:https://go.dev/play/p/lWZwjbnSewy

推荐答案

not需要一个参数,所以你必须使用括号.

如果这样做,您想要否定的条件是contains "hello" or contains "world":

{{if not (or (contains .hello "hello") (contains .world "hello")) }}

这将输出(在Go Playground上try ):

    not passed

您还可以将此条件编写为not contains "hello" and not contains "world",如下所示:

{{if and (not (contains .hello "hello")) (not (contains .world "hello")) }}

Go相关问答推荐

将Go程序导出到WASM—构建约束排除所有Go文件

Golang文本/模板序列范围

如何在gofr发起的服务间调用请求中添加Authorization Header?

在nixos上找不到XInput2.h头文件的包

Prometheus 摘要分位数错误

在 go 中,将接收器 struct 从值更改为指针是否向后兼容?

如何在golang中使用viper获取对象的配置数组?

Golang校验器包:重命名字段错误处理

下载和合并时输出文件已损坏

我的神经网络(从头开始)训练,让它离目标更远

Golang 中具体类型的错误片段

访问传递给可变参数函数的通用 struct 的特定字段

如何使用 Go 获取 X11 中的窗口列表

使用 Golang SQL 驱动程序连接到snowflake

有没有办法判断值是否满足接口中定义的类型约束?

如何从 tinygo webassembly 目标返回对象

递归数据 struct 解组在 Go Lang Protobuf 中给出错误无法解析无效的线格式数据

Golang 有类似 C++ 的 decltype 的东西吗?

Scanner.Buffer - 最大值对自定义拆分没有影响?

在 go (1.18) 的泛型上实现多态的最佳方法是什么?