HUGO

Access Data in Markdown Render Hooks

Hi,
I was wondering if there’s a way to load and parse a json or toml in a type specific render hook.

Following this example, I’m wondering if a Json placed in data folder can be accessed here.

{{ $en_anchor := .Site.Data.headings.heading1 }}

<h{{ .Level }} id="{{ $en_anchor }}">{{ .Text | safeHTML }} <a href="#{{ $en_anchor }}">¶</a></h{{ .Level }}>

I’m getting a context error:

executing "_default/_markup/render-heading.html" at <.Site.Data.headings.heading1>: can't evaluate field Site in type goldmark.headingContext

headings.json looks like:

{
    "heading1": "foo",
    "heading2": "bar"
}

You have a context (dot) problem. This might be helpful:
https://www.regisphilibert.com/blog/2018/02/hugo-the-scope-the-context-and-the-dot/

The simplest solution is to use the site function.

{{ $d := site.Data.foo }}

I’m actually doing that but still getting a context error. (sorry, the code block was cutting the first line off)

{{ $en_anchor := .Site.Data.headings.heading1 }}
<h{{ .Level }} id="{{ $en_anchor }}">{{ .Text | safeHTML }} <a href="#{{ $en_anchor }}">¶</a></h{{ .Level }}>

No, you are doing this:

{{ $en_anchor := .Site.Data.headings.heading1 }}

I asked you to do this instead:

{{ $en_anchor := site.Data.headings.heading1 }}
1 Like

Thanks @jmooring . That did the trick!
Follow up question, is there any way to access nested values in a json using [ ]?

{{ $en_anchor := site.Data.headings.["heading1"] }}

I get the following error:

parse failed: template: _default/_markup/render-heading.html:1: bad character U+005B '['

These are equivalent:

{{ $en_anchor := site.Data.headings.heading1 }}
{{ $en_anchor := index site.Data.headings "heading1" }}
1 Like

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