How to use variables?

Hello Hugo community

I have the following code in a template:
image

The value from the i18n file should be something like the default value of the variable $action. In the case the parameter action exists, the default value should be overridden.

Unfortunately $action always contains the value from the i18n file. How can I change this?

{{ if isset .Params "action" }}
<a href='{{ .URL }}'><button>{{ .Params.action }}</button></a>
{{ else }}
<a href='{{ .URL }}'><button>{{ i18n "actionRead" }}</button></a>
{{ end }}

This one works, but I wonder why the other one doesnt.

Thank you :slight_smile:

You can’t get a variable outside of the scope of a conditional without using scratch: https://gohugo.io/functions/scratch

I learned that just recently when I was coming up with this table shortcode: Proposal to add a new shortcode "table" to Hugo

Thank you for your answers!

I don’t understand what this should have to do with scopes. Maybe normal variables are immutable?

Perhaps this example helps.

Let’s say you want to colorize the link of the page you’re watching. Therefore you need to range through all pages of your project and list all page titles. This you would do like so:

{{ range .Site.Pages }}
    {{ .Title }}
{{ end }}

Now if you want to highlight the link you’re on you need something to compare with. And here the scope comes into play.

In the above example the scope is the title of the iterated page inside the range.

Now check this:

<!-- This is the title of the page I'm currently viewing -->
{{ $title := .Title }}
<!-- In here the title is the title of the iterated page -->
{{ range .Site.Pages }}
   <li><a href="{{.URL}}" style="{{ if eq $title .Title }}background-color: green;{{ end }}">{{ .Title }}</a></li>
{{ end }}

The function range is now comparing the title the viewer is seeing with the title of the iterated page. If they are the same, the background will be highlighted.

So the scope of the variable $title is the title of the page the viewer is seeing. The scope of .Title is the page which is just iterated range.

I think this is very well documented in the Hugo Docs.

Hope this helps, Leo

1 Like

I just beat him!

{{ $var := "A" }}
{{ if $condition }}
  {{ $var := "B" }}
<p> var = {{ $var }}</p> // => B
{{ end }}
<p> var = {{ $var }}</p> // => A

:warning: Watch out for the : = and =

{{ $var := "A" }}
{{ if $condition }}
  {{ $var = "B" }}
<p> var = {{ $var }}</p> // => B
{{ end }}
<p> var = {{ $var }}</p> // => B
1 Like