arrow_back
Back

Hugo data sources: local files, remote JSON, and GetPage

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Local data files

The data/ directory holds YAML, JSON, or TOML that layouts can read.

data/socialmedia.json:

{
  "accounts": [
    {
      "name": "Twitter",
      "url": "https://twitter.com/bphogan"
    },
    {
      "name": "LinkedIn",
      "url": "https://linkedin.com/in/bphogan"
    }
  ]
}

In a layout:

{{ range .Site.Data.socialmedia.accounts }}
  <li><a href="{{ .url }}">{{ .name }}</a></li>
{{ end }}

Remote JSON

Store API pieces in config:

[params]
gh_url = "https://api.github.com/users"
gh_user = "everhard"

Build the URL and fetch (legacy getJSON; newer Hugo prefers resources.GetRemote):

{{ $url := printf "%s/%s/repos" .Site.Params.gh_url .Site.Params.gh_user }}
{{ $repos := getJSON $url }}

{{ range $repos }}
  <article>
    <h3><a href="{{ .html_url }}">{{ .name }}</a></h3>
    <p>{{ .description }}</p>
  </article>
{{ end }}

Pulling data from another page

.Site.GetPage loads another content file by path so you can reuse its title, summary, and URL without hardcoding links:

{{ with .Site.GetPage "/opensource.md" }}
  <h3><a href="{{ .RelPermalink }}">{{ .Title }}</a></h3>
  <p>{{ .Summary }}</p>
{{ end }}
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Hugo related content: keywords, Related, and related indices

arrow_forward