Access root context($) from within a partial

I was testing something. What I’ve been trying to do is to access the root context($) from within a partial called as such:

{{ partial "test.html" (dict "someVar" someVal "context" . )}}

When I do this, I am unable to access global variables such as $.Site.(something). I also tried passing a new variable, "root" \$ but it fails. Please help me with this.

Had to place a \ beside because this site won't render alone.

The code you use to call your partial is fine.

You just need to access the context a bit differently. For example, to get the baseURL within your partial:

{{ .context.Site.BaseURL }}

Thanks for the quick reply. I tested it and it failed while I was trying to use:

{{ $paginator := .context.Paginate (where .Data.Pages "Type" .context.Site.Params.contentType) $itemsPerPage }}

Apparently, $.Site.Params.contentType used to work but .context.Site.Params.contentType returns nil.

Hmm, I didn’t initially test this with params, but I am seeing the same thing now.

As a workaround, you can pass the param you need as part of the dictionary, e.g.

{{ partial "test.html" (dict "someVar" someVal "context" . "contentType" .Site.Params.contentType) }}

I am aware of that but there are a lot of variables used. So, I want to avoid this approach for tidyness.

I see. In that case, just pass .Site.Params, then use as needed

{{ partial "test" (dict "params" .Site.Params) }}

In the meantime, I’ve also got stuck in another problem.
I can’t access .IsHome in the partial using .context.IsHome. Hugo print the following in the console: parse failed: template: partials/nav.html:5: function "context" not defined

That works for me. Maybe you are not passing the context?

Here’s my partial call:

{{ partial "test" (dict "context" . "params" .Site.Params) }}

And here’s my test partial:

{{ range $key, $value := .params }}
  {{ $key }} = {{ $value }}
{{ end }}

IsHome = {{ .context.IsHome }}
1 Like

I’ve done exactly the same thing:

{{ partial "nav.html" (dict "context" . "rssButton" true "type" "") }}

This is inside the partial:

{{ if not .context.IsHome }}
	<div class="item">
              <a href="/">
		    <i class="inverted big link home icon" title="{{ i18n `home` }}"></i>
{{ end }}

But somehow, it still fails, giving the above stated message while building.
This is the exact message:

executing "partials/nav.html" at <.context.IsHome>: can't evaluate field context in type *hugolib.PageOutput

Fixed it, I didn’t take in account the other partial calls, which were causing this build fail.