Losing scope in partial when using dict()

I’m getting some strange behavior when using dict() in my partial call.

  1. This works as expected, notice the period in the partial call to pass in the current scope
    {{ range first 1 (where .Data.Pages “Params.featured” “eq” true) }}
    {{ partial “blog/hero” . }}
    {{ end }}

  2. This also works fine:
    {{ partial “blog/hero” . (dict “abc” “list”) }}

  3. This loses scope: (period after dict)
    {{ partial “blog/hero” (dict “abc” “list”) . }}

However in my partial with #2 I get an error can’t evaluate field abc

In my partial with #3 field abc is available but because of loss of scope my partial outputs no content.

Can someone please explain this to me?

Hi,

The partial call takes two arguments: the partial name, and the context. In #2 and #3 you are passing three args: the partial name, the dot, and the dict.

Pass the dot as part of the dict instead:

{{ partial "foo" ( dict "abc" "list" "dot" . ) }}

The outer “dot” will then be accessible from inside your partial as .dot

docs:

Hey @pointyfar, thanks for the response.

So that makes sense, basically passing in scope via a variable.

I didn’t find any mention in the docs that partial calls only accept two parameters. Did I miss that somewhere?

However this solution hasn’t fixed my main issue which is to have the partial output some content, as it’s still lost the scope or is there some way I can set this inside the partial with the new variable?

Is this a case for using Scratch? I’m new to Hugo and haven’t used that yet.

The docs may not explicitly say the max number of args. But in the examples, no more than two args are ever used.

As @pointyfar showed in his example, the “scope” you speak of is now available by using the dot variable

Hey @zwbetz .

So my partial is wrapped like this:

  {{ range first 1 (where .Data.Pages “Params.featured” “eq” true) }}
{{ partial “blog/hero” . }}{{ end }}

How would the partial then know to use .dot instead of .?

In the partial definition you would use dot instead of .

If that doesn’t make sense, share your partial definition and we’ll help with the conversion

Ahh, sorry being very slow.

So instead of {{ .Type } it would be {{ .dotType }

Am on my phone so can’t test this, but try:

{{ .dot.Type }}

Also this is an interesting read, relevant to your original question: Accessing `.` from partial that also has a `dict`

Yep, that worked.

e.g. {{ .dot.Type }}

Thanks guys.

1 Like