how to check empty value of a string in golang template

Tinkaal Gogoi picture Tinkaal Gogoi · Feb 24, 2017 · Viewed 24.8k times · Source

I have this below golang template code snippet where I take values from a map of type map[string]interface{} and check if that string is empty or not but my string empty check is failing as: template: apps.html:62:29: executing "apps.html" at <eq $src "">: error calling eq: invalid type for comparison . I tried to print the empty value also and it is rendered as <nil> but my {{if eq $src "<nil>"}} check is also failing and even if I put nil then also it fails. Is there any better way to achieve this.

    {{$src := (index . "source")}}
    {{$tar := (index . "target")}}
    {{if eq $src ""}}
          <div></div>
    {{else}}
          <div style="display:none;">
              <input id="username" name="source" value="{{ $src }}"/>
              <input id="username" name="target" value="{{ $tar }}"/>
          </div>
    {{end}}

Answer

Kenny Grant picture Kenny Grant · Feb 24, 2017

Here is what you're doing (always better to give an example play.golang.org link if possible):

https://play.golang.org/p/uisbAr_3Qy

A few problems with what you're doing: If you're using a map for context, you don't need to use index at all, so your variables are not required. If you want to check if a key exists, just check for a nil entry with if. If your map contains elements of type interface, you can't compare with a string, only use eq when you're sure you have an element but are not sure what it might be, and wrap it in an if test if unsure whether the key exists.

I think you want to do something like this:

{{if .source }}
  <div style="display:none;">
    <input id="username" name="source" value="{{ .source }}"/>
    <input id="username" name="target" value="{{ .target }}"/>
  </div>
{{else}}
  <div>empty</div>
{{end}}

https://play.golang.org/p/D2DCjAklFE

See the docs for text/template as they have a lot more detail:

https://golang.org/pkg/text/template/#hdr-Actions