Compare strings in templates

callmekatootie picture callmekatootie · Jun 28, 2015 · Viewed 32.1k times · Source

I have the following template:

{{if . eq "login failed"}}
<span class="text-error">Incorrect username or password</span>
{{else if . eq "login success"}}
<span class="text-success">You have successfully logged in!</span>
{{end}}

I am passing a string when I execute the template.

However, I get the following error:

executing "login.html" at <.>: can't give argument to non-function .

How do I compare the strings within the template?

Answer

Tim Cooper picture Tim Cooper · Jun 28, 2015

eq is function, not an operator. It is called with the form: eq <x> <y> (not <x> eq <y>).

You can fix your template by moving the operands from the the sides of eq to after it:

{{if eq . "login failed"}}
<span class="text-error">Incorrect username or password</span>
{{else if eq . "login success"}}
<span class="text-success">You have successfully logged in!</span>
{{end}}