Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings in templates

Tags:

go-templates

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?

like image 470
callmekatootie Avatar asked Jun 28 '15 15:06

callmekatootie


2 Answers

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}}
like image 80
Tim Cooper Avatar answered Oct 23 '22 06:10

Tim Cooper


To compare if two strings equal :

{{ if eq .Status "Approved" }}
       ...Do something
{{ else }} 
       ...Do something else
{{ end }}

To compare if two strings not equal :

  {{ if ne .Status "" }}  // If status is not empty 
           ...Do something
  {{ else }} 
           ...Do something else
  {{ end }}

There are more golang HTML template directives here at : https://pkg.go.dev/text/template#hdr-Actions

like image 30
Balaji Boggaram Ramanarayan Avatar answered Oct 23 '22 07:10

Balaji Boggaram Ramanarayan