英文:
How to use multiple arguments in a single statement with Go templates
问题
我正在尝试在单个if语句中使用多个条件(使用text/template包),应该翻译为“如果$total
等于1且has
函数返回false
,则显示works
”。我不明白管道是如何工作的,也不明白为什么会出现这个错误。据我了解,当使用管道(|
)进行链接时,它会将结果作为参数发送给最后一个命令(在这种情况下是and
)。
{{if eq $total 1 | ne has true | and}}
Works
{{end}}
错误信息:模板错误::29:26:执行“ne”时参数数量错误:需要2个,实际得到2个。
英文:
I'm trying to pipe multiple conditions in a single if statement(using text/template package) which should translate into "If $total
== 1 and has
function returns false
display works
". I don't understand how exactly the pipelines work or why I'm getting this non-sense error. As far as I understand when chaining is used (|
) it sends the result as argument to the last command (and
in this case)
{{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
答案1
得分: 1
我不确定为什么会出现这个有趣的错误消息,但实际上你传递给 ne
的是 3 个参数,这触发了错误:
(来自 text/template 包的文档)
通过使用管道字符 '|' 将一系列命令连接起来,可以形成一个“链式”管道。在链式管道中,每个命令的结果都作为下一个命令的最后一个参数传递。管道中最后一个命令的输出就是整个管道的值。
所以你给 ne
的参数是函数 has
的结果、值 true
和第一个表达式的结果。
要实现你想要的效果,请使用以下代码:
{{if eq $total 1 | and (not has)}}
Works
{{end}}
这将比较 eq $total 1
(或 $total == 1
)的结果,将其作为第二个参数传递给 and
,并且将 has
的结果取反,只有当 $total == 1
且 has
返回 false 时才会打印出 "Works"。
在 Playground 上可以看到一个可运行的示例。请注意,我用一个简单的结构体替换了 $total
(因为我无法确定你从哪里获取它)。
英文:
I'm not sure about why the funny error message, but you are actually passing 3 arguments to ne
which triggers the error :
(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.
So you are giving ne
the result of function has
, the value true
and the result of the first expression.
To get what you want do:
{{if eq $total 1 | and (not has)}}
Works
{{end}}
This will compare the result of eq $total 1
(or $total == 1
) which is passed as the second argument to the and
and the negated result of has
and thus only print Works
when $total == 1 AND has returns false
.
See a working example on the Playground. Note that I replaced $total (since I can't tell where you get it from) with a simple struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论