Can't pass variable from partial?

Hi everyone,
I am trying to pass a variable from my partial but it just renders as empty content, when I add the “.” then it renders fine so don’t understand why??

My partial

{{ partial "navigation/menu" (dict "class" "header") }}

My menu

{{ if .Site.Params.Foo.baz }}
<a href="https://www.example.com/{{ .Site.Params.Foo.baz}}" class="{{ .class }}" title="Example">Example</a>
{{ end }}

I would like to pass {{ .class }} to my partial as I want to use the menu on a few different pages and want to be able to set the class variable from the partial dict.

Any ideas?
Thanks in advance.

You can rewrite to:

{{ if site.Params.Foo.baz }}
<a href="https://www.example.com/{{ site.Params.Foo.baz}}" class="{{ .class }}" title="Example">Example</a>
{{ end }}

If you need the Page, you also need to pass that in the dict.

2 Likes

wow the legend himself, thank you so much for the quick reply! I will try this. I just didn’t understand why the dict wasn’t passing, is it because its within an if statement?

bep beat me to the short answer, so I’ll give a longer one:

In the call to your partial:

{{ partial "navigation/menu" (dict "page" .Page "class" "header") }}

In you menu partial:

{{ $ctx := . }}
{{ $class = .class }}
{{ $page := .page }}
{{ with $page }}
    {{ if .Site.Params.Foo.baz }}
    <a href="https://www.example.com/{{ .Site.Params.Foo.baz}}" class="{{ $class }}" title="Example">Example</a>
    {{ end }}
{{ end }}

That’s one way at any rate. But, if you only need site.Params.Foo.baz bep’s way is better.

4 Likes

Thank you so much! I see now I have to pass the contextual dot over if I want to use .Site.Params I see now, thanks for the I will give it a go! I have two solutions to one problem. Thank you for your time!

1 Like

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