比较模板中的字符串

时间:2015-06-28 15:52:02

标签: templates go

我有以下模板:

{{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}}

我在执行模板时传递一个字符串。

但是,我收到以下错误:

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

如何比较模板中的字符串?

2 个答案:

答案 0 :(得分:31)

eq is function,而不是运营商;它应该像eq <x> <y>一样使用,而不是<x> eq <y>。要解决此问题,您应该将模板更改为以下内容:

{{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}}

答案 1 :(得分:1)

比较两个字符串是否相等:

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

比较两个字符串是否不相等:

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

这里有更多 golang HTML 模板指令:https://pkg.go.dev/text/template#hdr-Actions