Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hugo data files from dynamic parameter

I'm developing a big hugo template. I try to simplfy the problem, so I have two datafile:

  • PROMO_00_1.yaml
  • PROMO_00_2.yaml

that are phisically stored in this directory:

themes/data/hp/

So, in the site config the user will decide which of this data file will be used simply indicate it in a param (HpElement).

In the template I call the partial in this way:

 {{ partial "multiplepages/homepage/promos/00_promo_singleslide_text_video" (dict "context" . "data" $.Site.Params.HpElement) }}

In a partial I write:

{{ $data_partial := (printf "$.Site.Data.homepage.%s" .data)}}
{{ $data_partial}}

and the Hugo output is on the website:

$.Site.Data.homepage.PROMO_00_1

What I need is to access the single variable inside the .yaml file but the user MUST can decide which YAML file have to use. How can I achieve that?

Thanks

like image 429
pinguinone Avatar asked Nov 23 '25 06:11

pinguinone


1 Answers

I just finished up a similar use case where I needed to select a YAML based on a date stamp. The index function is key to this operation.

https://gohugo.io/functions/index-function/

Here is a simplified version of my situation:

{{ $date := now.Format "s20060102"}}
{{ $data := (index .Site.Data.schedule $date) }}

{{ with $data }}
  <h1>.longdate</h1>
  {{ range .times }}
    <h2>{{ .name }} - {{ .location }}
  {{ end}
{{ end}

The example in the Hugo documentation uses an example where the data file is selected based on an attribute in the front matter.

like image 72
Corey S. Avatar answered Nov 24 '25 21:11

Corey S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!