Can I use a variable initialized in an `if` statement outside of it?

I know that the variable scope and context within with and range statements only apply within them. A variable can be created within them but can only then be used within them, not outside. If you want to use it outside, you have to create the variable outside the statement first and then only reassign the value.

But I always thought it was different for if statements. That you could create a variable inside the statement and use it outside, however I’m generating a error which indicates that my understanding is wrong. A variable the very certainly exists within, no longer is defined outside the if statement.

It is an easy fix, but am I missing something or was my understanding wrong all along?

The code is below. The issue is $logo_new which is created in the if statement and I want to use it again outside. (also, please don’t judge the code otherwise as it is in refactor process from the mess that it was)

{{ with $logo := resources.Get site.Params.logo_src }}
  {{ $logoWidth:= site.Params.logo_width | default $logo.Width }}
  {{ if eq .MediaType.SubType "gif" }}
    {{ $logo_new := ($logo.Resize (add (string $logoWidth) "x")).RelPermalink }}
  {{ else if eq .MediaType.SubType "svg+xml" }}
    {{ $logo_new := $logo.RelPermalink }}
  {{ else }}
    {{ $options := add (string $logoWidth) "x webp icon" }}
    {{ $logo_new := ($logo.Resize $options).RelPermalink }}
    {{ $logo_fallback := ($logo.Resize (add (string $logoWidth) "x")).RelPermalink }}
    {{ warnf "%#v" $logo_new }}
  {{ end }}
  {{ warnf "%#v" $logo_new }}
    width="{{ $logoWidth }}"
    src="{{ $logo }}"
    alt="{{ site.Params.logo_alt | default site.Params.logo_text }}"
    {{- if and (ne .MediaType.SubType "gif") (ne .MediaType.SubType "svg+xml") -}}
      onerror="this.onerror=null;this.src='{{ $logo }}'"
    {{- end -}} />
{{ else }}
  {{ with site.Params.logo_text }}
    {{ . | markdownify }}
  {{ else }}
    {{ site.Title | markdownify }}
  {{ end }}
{{ end }}

Hate to rain on your parade, but the if-statement variable scoping is not different in the way you’re saying.

You’ll have to declare your variable outside the if-statement then reassign it in each relevant block.

1 Like

Nuts. So then the only difference between the if, with, range is that changing of upper-level variable scope, but the limitation of a variable’s scope created within those statements is the same.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.