7/3/2017 - 1:24 PM

How to use Data Files in Hugo

How to use Data Files in Hugo

In Hugo, Data Files are placed inside the data folder. Inside, you can further organise the files into different levels of sub-folders. For example, I have a folder named novelists, and inside novelists I have one more level of sub-folders, in which I store my data in YAML (you can choose to use TOML and JSON).

└── novelists
        ├── Knausgaard_Karl_Ove.yaml
        ├── Kundera_Milan.yaml
        ├── Proust_Marcel.yaml
        └── Tolstoy_Leo.yaml

The data files

Inside each YAML file, the data are organised as follow:

name: Leo Tolstoy
bio: "Russian novelist, best known for his novels *War and Peace*, *Anna Karenina* and various essays."

- title: "Anna Karenina"
  - entry: "quote no. 1"
    comment: "comment no. 1"
    credits: "credit no. 1"
  - entry: "quote no. 2"
    comment: "comment no. 2"
    credits: "credit no. 2"

- title: "War and Peace"
  - entry: "quote no. 3"
    comment: "comment no. 3"
    credits: "credit no. 3"

Accessing the data

The data stored inside ./data/novelists/everything/*.yml can be accessed via .Site.Data.novelists.everything. The snippet below is a simplified version of the actual code used in this website:

{{ range .Site.Data.novelists.everything }}
  <h3>{{ .name }}</h3>
  <p>{{ .bio }}</p>
  {{ range .sources }}
    <h4>{{ .title }}</h4>
    {{ range .quotes }}
        <p>{{ .entry }}</p>
        {{ if .credits }}<p><small><em>{{ .credits }}</em></small></p>{{ end }}
      {{ if .comment }}<p>{{ .comment }}</p>{{ end }}
      <p><br /></p>
    {{ end }}
{{ end }}

This block of codes does the following things:

  • Shows the name of the novelist
  • Shows the brief biography
  • Lists the books
  • Under each book, shows quotes, comments, and credits.