Cant get variable set in a conditional

Im trying to create a button partial where i can set link, title and color by using the following that works:

{{ partial “button.html” (dict “src” “#” “title” “button title text” “bgcolor” “green”) }}

But inside the partial (button.html) im trying to convert the bgcolor to a hex. The variable $color echos when inside the conditional but when i try to use it outside the conditional it does not get recognised. I get the error
undefined variable “$color”.

If any one can help with a solution be super grateful!

{{  if (eq .bgcolor "green" ) }}
    {{$color := "#00ac69"}} //setting a green hex color
    {{$color}} //works when inside if statement
{{ else }}
    <!-- orange hex -->
    {{$color := "#f86230"}}
    {{$color}} // again works
{{ end }}

<a href="{{.src }}" style="background-color:{{$color}};">{{.title}}</a> //$color doesnt work.
1 Like

I might be totally off here but try defining color var before the if statement, I have a hunch it might be a scoping issue.

I think this is a scope issue. If you’re using the most recent Hugo with the most recent version of Golang, you can redefined variables with just =. Nevertheless, try this instead…

<a href="{{.src }}" style="background-color:{{  if eq .bgcolor "green"  }}#00ac69{{else}}#f86230{{end}}">{{.title}}</a>

Thanks redwatters

I think I read somewhere that you cannot access variables inside conditionals when using partials. I’ve tried to replicate with .scratch too but struggled there aswell.

Your solution works so ill use that!

1 Like

Kinda sorta. Have you tried this as well per the above link I provided from the docs? (Read that entire section of the page.)

{{ $color := "#f86230" }}
{{ if eq .bgcolor "green" }}
    {{ $color = "#00ac69" }}
{{ end }}

<a href="{{.src }}" style="background-color:{{$color}};">{{.title}}</a>

If the previous solution works, this is probably gilding the lily. Just wanted to make sure you know that you can reassign variables in Hugo versions .48 and .49 :smile:

3 Likes

Hi rdwatters

Thanks! Apologies for not reading the link properly, was too tired after struggling, and when i saw your solution that worked, I just jumped on it. Updated hugo and now variables work how you would expect them to!

1 Like