gpt4 book ai didi

templates - 如何使用 Go 模板在单个语句中使用多个参数

转载 作者:数据小太阳 更新时间:2023-10-29 03:16:53 24 4
gpt4 key购买 nike

我正在尝试在单个 if 语句(使用 text/template 包)中传递多个条件,该语句应转换为“If $total == 1 and has function returns false display works ”。我不明白这些管道究竟是如何工作的,也不明白为什么我会收到这个无意义的错误。据我所知,当使用链接( | )时,它将结果作为参数发送到最后一个命令(在本例中为 and )

{{if  eq $total 1 | ne has true | and}}
Works
{{end}}

err template: :29:26: executing "" at <ne>: wrong number of args for ne: want 2 got 2

最佳答案

我不确定为什么会出现有趣的错误消息,但您实际上将 3 个参数传递给 ne触发错误:

( from the text/template package )

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of the each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

所以你给出了 ne函数的结果 has , 值 true以及第一个表达式的结果。

为了得到你想做的事:

{{if eq $total 1 | and (not has)}}
Works
{{end}}

这将比较 eq $total 1 的结果(或 $total == 1 )作为第二个参数传递给 andhas 的否定结果因此只打印 Works什么时候$total == 1 AND has returns false .

查看工作示例 on the Playground .请注意,我用一个简单的结构替换了 $total(因为我不知道你从哪里得到它)。

关于templates - 如何使用 Go 模板在单个语句中使用多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com