Accessing `.` from partial that also has a `dict`

I find myself often wanting to pass a dict as well as the current page context into a partial into different places, like this:

  {{ partial "some-partial.html" (dict "foo" "123" "content" . ) }}
  {{ partial "some-partial.html" (dict "foo" "4567" "content" . ) }}
  {{ partial "some-partial.html" (dict "foo" "89" "content" . ) }}

Then I can access . through .content in the partial, and the other dict keys by referencing them via .<key>, e.g. .foo.

This seems slightly backwards to me. Instead, I’m wondering if there’s a way to always pass . to the partial, and if a dict is present, it gets attached to a specific location inside the partial’s context, e.g. .ContextualParams. So, later, if I wanted to access the foo key in the dict, I’d do .ContextualParams.foo (or whatever), but . is always .

Is this a use case that others have encountered? Am I just using dicts and partials incorrectly?

2 Likes

No. We can only pass on 1 data object to the Go templates (it can be a list/slice, but that would not help), so theres is currently no magic way. And partial is just a plain old Go func, so it needs to know about the context (i.e. it has no method receiver).

Thanks @bep; is (dict "k1" "v1" [...] "kN" "vN" "content" .) the best-practices way to also include . when it’s needed?

I haven’t thought about it. It would, of course, be good for interoperability to have some common naming here, but I’m probably the last person to ask about that (or, maybe not the last …)

1 Like