Using Hugo, how can I access a variable from a partial file that is defined in base file?
Asked Answered
T

3

5

I'm new to using Hugo and Go Templates. How can I access a variable from a partial file that is defined in base file using Hugo?

For eg: I have an index.html file which contains code that reads the data stored in the events.json file in the data directory and stores it in a variable. How can I access that variable from another file?

index.html

{{ $events := .Site.Data.events }}

{{ partial "people" . }}

people.html

// access the events variable from the index.html
{{ $events }}

I really hope this makes sense. I can try and clarify more if needed.

Thilde answered 8/2, 2017 at 22:20 Comment(0)
N
11

0.15 introduced a map that can be used for this.

index.html

{{ $events := .Site.Data.events }}
{{ partial "people" (dict "events" $events) }}

people.html

// access the events variable from the index.html
{{ .events }}
Navarrete answered 20/2, 2017 at 6:21 Comment(0)
S
5

You could use the dict func:

{{ partial "people" (dict "page" . "events" $events) }}

You will then address them like {{ .page.someVar }} and {{ .events.someVar }} in the partial.

An alternative in your case could maybe, in the partial (as the previous poster said), address the .Site.Data.events directly from the partial.

Soup answered 19/2, 2017 at 21:28 Comment(2)
good stuff, I was not aware of dict πŸ‘ . By the way, please fix the rounded bracket after $events, it should be curly brace. I can't suggest edit since it's less than 6 chars long. – Quod
Thanks for the correction (the rounded bracket is correct, btw). – Soup
Q
-2

According to Hugo documentation:

... partial calls receive two parameters.

  1. The first is the name of the partial and determines the file location to be read.
  2. The second is the variables to be passed down to the partial.

This means that the partial will only be able to access those variables. It is isolated and has no access to the outer scope.

This means, the events variable is outside of the scope of people.html. Your people.html cannot "see" it. One solution would be pass it down, like:

{{ partial "people" . $events }}

If it does not work, try different notation ($ vs. .).

If that does not work, you can always call your data file again, without variable, just like in the examples, that is, use {{ .Site.Data.events }} in your people.html partial.

Let me know in the comments how it goes, I'll try to improve my answer if necessary. I know it's a pain to get out of Hugo boundaries into Go territory :)

Quod answered 17/2, 2017 at 14:1 Comment(2)
{ partial "people" . $events }} and using $ or . notation also does not work – Thilde
The first parameter in your sample is "people", the second one ".". $events is a third parameter that defines for what section the partial works. This does not solve the issue. – Rudolfrudolfo

© 2022 - 2024 β€” McMap. All rights reserved.