Search code examples
global-variablestemplate-enginepartialsgo-templateshugo

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


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.


Solution

  • 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 }}