The user with no hat
The user with no hat

Reputation: 10846

How to use multiple arguments in a single statement with Go templates

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

Upvotes: 0

Views: 2689

Answers (1)

IamNaN
IamNaN

Reputation: 6864

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.

Upvotes: 1

Related Questions