Golang text/template多个条件,带!not运算符

ccgok5k5  于 2023-11-14  发布在  Go
关注(0)|答案(2)|浏览(160)

如何在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 playground链接:https://go.dev/play/p/lWZwjbnSewy

irlmq6kh

irlmq6kh1#

not需要一个参数,因此必须使用括号。
如果是这样,则要求反的条件为contains "hello" or contains "world"

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

字符串
这将输出(在Go Playground上尝试):

not passed


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

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

wlzqhblo

wlzqhblo2#

另一种方法是将模板函数修改为notContains,其中not操作在函数本身中执行,然后从模板字符串中删除not
例如:

func notContains(str string, sub string) bool {
    return !strings.Contains(str, sub)
}

var (
    templateFuncMap = template.FuncMap{
        "notContains": notContains,
    }
)

字符串
模板中的用法:

{{if and (notContains .hello "world") (notContains .world "hello") }}
        passed
{{else}}
        not passed
{{end}}`


Playground:https://go.dev/play/p/t5Xg3t4xWgr

相关问题