Why {{ if eq ... }} does not work

I’m looping through a JSON array and want to emit html based on the value of a numeric field. Here’s my code.

{{ if eq .complete.audio 0 }}
<i class="microphone slash icon"></i>
{{ if eq .complete.audio 1 }}
<i class="volume up icon"></i>
{{ if eq .complete.audio 2 }}
<i class="clock outline icon"></i>
{{ else }}
<i class="question icon"></i> {{.complete.audio}}
{{ end }}

None of the equality tests evaluate true and the {{ else }} condition is the only path taken. I tried quoting the numeric values (0,1,2) in case .complete.audio was unexpectedly a string type but that didn’t work either.

Thanks in advance for your help.

I’m curious what this will so you:

{{ printf "%#v" .complete }}

It looks okay to me…

map[string]interface {}{"audio":1, "index":1, "fb":0, "format":1}

Thanks for your input

Addition with .complete.audio works fine but checking the result fails the equality test. Here’s how I modified the original code.

  {{ if eq (add .complete.audio 1) 1 }}
    <i class="microphone slash icon"></i>
  {{ else if eq (add .complete.audio 1) 2 }}
    <i class="volume up icon"></i>
  {{ else if eq (add .complete.audio 1) 3 }}
    <i class="clock outline icon"></i>
  {{ else }}
  <i class="question icon"></i> {{.complete.audio}}+1: {{add .complete.audio 1}}
  {{ end }}

The {{else}} path is always taken and I get output like:

  • 1+1: 2
  • 2+1: 3

So - adding doesn’t help.

Does this change anything?

{{ if eq (int .complete.audio) 0 }}
1 Like

YESSSS!!!

Thanks for you help!!

Glad you are able to move forward now, but the int cast shouldn’t be necessary.

Did some digging in the hugo code. The issue is that the value from JSON is a float (I believe all numeric values are floats in JSON). You should be able to simplify your code by comparing to a float:

{{ if eq .complete.audio 0.0 }}

I’ll create an issue in GH to improve the eq function so that’s not as strict.

1 Like

The simplified template works great. Thanks again for your help.