Load data using dynamic path

Hello,

I am trying to load json data using a dynamic path, using variables that are specified in Front Matter of my dot md files.

My data structure is as follows
data/guide/<name>/<date>.json

I have tried using printf to build up the path and the various solutions offered by these posts like below

I also tried this solution with setting a dataFile in the front matter

{{ $dataFile := index .Site.Data.guide .Params.datafile }}

But get the following error

guide is not a method but has arguments Rebuild failed:

executing β€œmain” at <index .Site.Data.guide .Params.datafile>: error calling index: value is nil; should be of type string

I have also tried to simplify the directory path to

data/guide/<name>-<date>.json

but this does not help either.

All suggestions welcomed.

Thanks in advance
gearoid

Structure

data
└── guide/
    β”œβ”€β”€ a/
    β”‚   └── 2021-06-07.json
    └── b/
        └── 2021-06-01.json

Example of TOML front matter:

+++
title = "Test"
date = 2021-06-05T07:12:16-07:00
draft = false
[guide]
  name = "a"
  date = 2021-06-07
+++

Example of YAML front matter:

title: Test
date: 2021-06-05T07:12:16-07:00
draft: false
guide:
  name: b
  date: 2021-06-01

layouts/_default/single.html

{{ with .Params.guide }}
  {{ $data := index site.Data.guide .name (dateFormat "2006-01-02" .date) }}
{{ end }}

1 Like

You are a gentleman @jmooring thanks very much for the prompt reply and the clear solution.

1 Like

Although this works, I am going to revise my answer. Here’s why:

  1. You cannot access the data files directly. For example, this:

    {{ site.Data.guide.a.2021-06-04 }}
    

    generates this error:

    bad number syntax: ".2021-06"
    
  2. And if you try to convince Hugo that the filename is a string by placing a non-numeric character at the beginning:

    {{ site.Data.guide.a._2021-06-04 }}
    

    it doesn’t like the hyphens:

    bad character U+002D '-'
    
  3. And if you try to use numbers only…

    {{ site.Data.guide.a.20210604 }}
    

    it doesn’t like numbers:

    unexpected ".20210604" in operand
    

So, use this instead…

Structure

data
└── guide/
    β”œβ”€β”€ a/
    β”‚   └── _20210607.json
    └── b/
        └── _20210601.json

layouts/_default/single.html

{{ with .Params.guide }}
  {{ $data := index site.Data.guide .name (dateFormat "_20060102" .date) }}
{{ end }}

The front matter format remains unchanged.

2 Likes

@jmooring yes discovered this too

with the front matter like this now. I removed the date format file as this would have resulted in too many files being generated that dont need to be kept around so I just over write each day file now

guide:
  name: "a"
  page: "0"
data
└── guide/
    β”œβ”€β”€ a/
    β”‚   └── 0.json
    └── b/
        └── 0.json
1 Like

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