Join two variables together

How do I join multiple custom variables into one? I want both to generate a $pages variable to use in RSS feed template. (Where "load regular pages in section blog, and include pages which have a layout of multipage.

{{ $p1 := where site.RegularPages "Section" "blog" }}
{{ $p2 := where site.Pages "Params.layout" "=" "multipage" }}
{{ $pages := <!-- join both --> }}

See union.

I tried this

{{ $pages := where .Site.RegularPages "Section" "blog" }}
{{ $pages := $pages | union (where .Site.Pages "Params.layout" "=" "multipage") }}

But received this error

Edit: trimming newlines ({{- -}}) solved it.

It should be = instead of := in this second line.

The union page you linked to says otherwise?

That’s a typo in the doc. It should be fixed. fix: Use `=` instead of `:=` for variable reassignments by kaushalmodi · Pull Request #1771 · gohugoio/hugoDocs · GitHub

Only the first assignment uses :=. Think of it as a variable declaration. Re-assignments use =.

You can do it either way:

{{ $x := 1 }}
{{ $x := add $x 1 }}
{{ $x }} --> 2

{{ $x := 1 }}
{{ $x = add $x 1 }}
{{ $x }} --> 2

I like the first way because of the alignment.

I did mine this way to be consistent with how I have learnt to use Hugo variables

{{- $p1 := where site.RegularPages "Section" "blog" }}
{{- $p2 := where site.Pages "Params.layout" "multipage" }}
{{- $pages := $p1 | union ($p2) }}

I didn’t know that!

So the = is useless? I wonder why it was introduced then? Or did := get allowed for reassignments some time later?

I really like the consistency in definition:

  • := for declarations or first assignments
  • = for reassignments

Update: OK, I get it. Using := for both initial and later assignments works in the case of $pages in this thread because the redefinition is happening in the same scope as the initial assignment.

1 Like

@jmooring About variable redefinition: Introduction to Hugo Templating | Hugo

In the documentation, I think that that convention should be followed (use = for redefinition) for clarity. If the user does := instead of = in that variable redefinition example in the above linked doc, they might be surprised by the outcome.

2 Likes

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