How to pass multiple parameters to a partial in Hugo
By Flavio Copes
How do you pass multiple parameters to a partial in Hugo? It's not as simple as it seems, you need to use a trick. Let's find out.
To pass multiple parameters to a partial in Hugo, you bundle them into a dictionary with the dict function, and pass that dictionary as the partial’s single argument.
I use Hugo to manage this site. It’s pretty cool.
One thing that got me stuck today was passing 2 parameters to a partial.
Here’s the underlying problem: a Hugo partial accepts exactly one context argument. Usually you pass ., the current page, and everything works. The moment you need a second value, there’s no second slot to put it in.
The dict trick
Since in a partial I could not access .Site.Pages to get the list of pages of the site (due to scope issues), I had to create a dictionary and fill it with 2 items:
{{ partial "my-partial.html" (dict "context" . "pages" $.Site.Pages) }}
The key here is passing (dict "context" . "pages" $.Site.Pages) as the parameter, instead of . as you usually do with partials.
dict takes alternating keys and values: the string "context" paired with the current page context, then the string "pages" paired with the site’s page list. The result is a single map, which fits in the partial’s one argument slot.
Inside the partial
Now inside the partial, instead of using . to access the current context variables you’d use .context.
And to access the value assigned to pages, I’d use .pages.
For example, the partial could list every page of the site like this:
<p>Links from {{ .context.Title }}:</p>
{{ range .pages }}
<a href="{{ .Permalink }}">{{ .Title }}</a>
{{ end }}
Inside the range, . becomes each individual page, so .Permalink and .Title work as usual.
You can of course pass multiple items, too. Just add more items to the dict.
Watch out for odd arguments
One thing to be careful with: dict wants an even number of arguments. Each key needs a value.
If you write something like (dict "context" . "pages") and forget the last value, Hugo fails the build with an error on that template. It looks cryptic the first time you see it, but the fix is checking that every key in the dict call has a matching value right after it.
Also remember the keys are strings, so they need quotes. Writing dict context . instead of dict "context" . is another easy way to break the build.