Hugo

[SOLVED] Assigning variables to conditions

Hey. There is a code

{{ if or (eq .RelPermalink "/page1/") (eq .RelPermalink "/ru/page2/") }}
{{ $orange_title := T "test1" | safeHTML }}
{{ else if or (eq .RelPermalink "/page3/") (eq .RelPermalink "/page4/") }}
{{ $orange_title := T "test2" | safeHTML }}
{{ else }}
{{ $orange_title := T "test3" | safeHTML }}
{{ end }}

But for some reason, an error is shown during site generation

ERROR 2019/12/03 13:04:27 Process: loading templates: "d:\hugo\src\themes\mytheme\layouts\partials\page.html:218:1": parse failed: template: partials/page.html:218: undefined variable "$orange_title"

Assign the variable first outside the if/else logic.

{{ $orange_title := "" }}
{{ if or (eq .RelPermalink "/page1/") (eq .RelPermalink "/ru/page2/") }}
{{ $orange_title = T "test1" | safeHTML }}
{{ else if or (eq .RelPermalink "/page3/") (eq .RelPermalink "/page4/") }}
{{ $orange_title = T "test2" | safeHTML }}
{{ else }}
{{ $orange_title = T "test3" | safeHTML }}
{{ end }}

Read more here: https://gohugo.io/templates/introduction/#variables

1 Like

Thank you

<!-- Orange Block -->
{{ $orange_title := "" }}
{{ $orange_btn := "" }}
{{ $orange_text := "" }}
{{ $orange_link := "" }}
{{ $orange_link_target := "" }}
{{ if or (eq .RelPermalink "/page/") (eq .RelPermalink "/de/page/") }}
{{ $orange_title := T "TEXT_EUROPE_Orange_title" | safeHTML }}
{{ else if or (eq .RelPermalink "/page2/") (eq .RelPermalink "/de/page2/") }}
{{ $orange_title := T "TEXT_RUSSIA_Orange_title" | safeHTML }}
{{ else }}
{{ $orange_title := T "TEXT_MAIN_PAGE_Orange_title" | safeHTML }}
{{ $orange_btn := T "TEXT_MAIN_PAGE_Orange_btn" | safeHTML }}
{{ $orange_text := T "TEXT_MAIN_PAGE_Orange_text" | safeHTML }}
{{ $orange_link := "/page3/dedicated/" | relLangURL }}
{{ $orange_link_target := 1 }}
{{ end }}
{{ .Scratch.Set "orange_title" $orange_title }}
{{ if or (eq .RelPermalink "/page3/") (eq .RelPermalink "/de/page3/") }}
{{ .Scratch.Set "orange_btn" $orange_btn }}
{{ .Scratch.Set "orange_text" $orange_text }}
{{ .Scratch.Set "orange_link" $orange_link }}
{{ .Scratch.Set "orange_link_target" $orange_link_target }}
{{ end }}
{{ partial "modules/orange_banner" . }}
<!-- END Orange Block -->

http://localhost:1313/page3/
I see an empty variable. Why?

The first time you declare the variable you should use :=, when overriding use only =. Example:

{{ $orange_title := "" }}
{{ if true }}
{{ $orange_title = "foo" }}
{{ end }}