
php小编西瓜向大家介绍Golang中一个有趣的特性——文本/模板带有!not运算符的多个条件。这个特性在Golang的模板引擎中非常实用,能够帮助我们更灵活地处理条件判断。通过使用!not运算符,我们可以在模板中同时判断多个条件,简化代码逻辑,提高开发效率。本文将详细介绍如何使用这个特性,并给出一些使用示例,帮助大家更好地理解和应用。让我们一起来探索这个有趣的Golang特性吧!
问题内容
如何在 Go 中使用间接模板函数链接多个条件?
我想检查 .hello 是否不包含“world”并且 .world 是否不包含“hello”,但我不能,因为我得到 2009/11/10 23:00:00 执行 template: template : content:2:5: 在 错误消息
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)
}
}
去游乐场链接:https://go.dev/play/p/lWZwjbnSewy
立即学习“go语言免费学习笔记(深入)”;
发卡宝是一个专业的软件卡密等虚拟商品在线交易平台,拥有多种兑换方式,费率低,结算快,正规企业平台一直稳定运营,24小时不间断提供自动发卡服务。【模板说明】试用版自带一套模板(响应式)【环境支持】PHP环境 / 200M或以上空间大小 / 开启父路径 / 设置index.php为默认首页 / 目录写入权限需要开启【数据库】MySQL【安装步骤】将文件上传至空间目录,运行“http://域名/inst
解决方法
not 需要一个参数,因此必须使用括号。
如果这样做,您要否定的条件是 contains "hello" 或 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")) }}









