Accessing dict variables in a partial

Using Hugo v0.62.2

We have a page documentation.md (note, this is a Markdown file) that contains some front matter, content, and refers to a partial code-example.html.

Inside code-example.html we have:

<div class="status-{{ .status }}"> ... </div>

We would like to be able to do something like

{{< partial "code-example" (dict "status" "silver") >}}

and have the resulting output be <div class="status-silver"> ... </div>, or

{{< partial "code-example" (dict "status" "gold") >}}

and get <div class="status-gold"> ... </div>


The error we get is:

unrecognized character in shortcode action: U+0028 '('. Note: Parameters with non-alphanumeric args must be quoted

Seems it doesn’t like the (dict "status" "silver") part.


First attempt to fix

We created a partial named code-example-silver.html that references code-example.html like so.

{{ partial "code-example" (dict "status" "silver") }}

and because of the change of scope, we changed code-example.html to:

<div class="status-{{ . }}"> ... </div>

And now the output is

<div class="status-map[status:silver]"> ... </div>

if we use

<div class="status-{{ .status }}"> ... </div>

then the error is

<.status>: can't evaluate field status in type *hugolib.ShortcodeWithPage

How do we make this work?

1 Like

Welcome to the forum Barnaclebill :wave:

Hmm. Tough problem you have here. It seems like you did a lot of things right. But perhaps this is worth trying:

What happens if you use

<div class="status-{{ .status }}"> ... </div>

to try and access that map value?

Ah yes, forgot to add that to the original post (which I’ve just updated). In that case the error is

<.status>: can't evaluate field status in type *hugolib.ShortcodeWithPage

Hmm. Honestly the only thing I can think of is to prefix .status with .Page. So it becomes .Page.status then.

The docs say:

You can also use the variable .Page to access all the normal page variables.

So if a shortcode needs to get the title of its page, we use .Page.Title rather than .Title. Perhaps this applies to dict as well.

.Page.status generates this error:

<.Page.status>: can't evaluate field status in type page.Page

.status is not in the list of Page variables

I suggest that you share a slimmed down repo with your setup so that people in this forum can look into it.

After a lot of tinkering we found that using .Get works. We were even able to pass multiple variables into the partial and access them by index like so.

{{ partial "code-example" "silver" "gold" }}

then using

{{ .Get 1 }} // for the first variable
{{ .Get 2 }} // for the second variable, and so on...

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