hugo.Data
- Syntax
- hugo.Data
- Returns
- map
Usage
The hugo.Data function returns a data structure composed from the files in the data directory of the unified file system. Supported data formats include JSON, TOML, YAML, and XML.
Each subdirectory and file name, without its extension, becomes a key in the data structure. Access the data by chaining the keys as identifiers. To access a key that is not a valid identifier, such as a key that contains a hyphen, use the collections.Index function.
Although Hugo can unmarshal CSV files with the transform.Unmarshal function, do not place CSV files in the data directory. You cannot access data within CSV files using this function.
Examples
These examples use this data directory:
data/
├── books/
│ ├── fiction.yaml
│ └── nonfiction.yaml
├── films.json
├── paintings.xml
└── sculptures.tomlThe books directory contains these data files:
- title: The Hunchback of Notre Dame
author: Victor Hugo
isbn: 978-0140443530
- title: Les Misérables
author: Victor Hugo
isbn: 978-0451419439- title: The Ancien Régime and the Revolution
author: Alexis de Tocqueville
isbn: 978-0141441641
- title: Interpreting the French Revolution
author: François Furet
isbn: 978-0521280495Listing the books in each category:
{{ range $category, $books := hugo.Data.books }}
<p>{{ $category | title }}</p>
<ul>
{{ range $books }}
<li>{{ .title }} ({{ .isbn }})</li>
{{ end }}
</ul>
{{ end }}The rendered output:
<p>Fiction</p>
<ul>
<li>The Hunchback of Notre Dame (978-0140443530)</li>
<li>Les Misérables (978-0451419439)</li>
</ul>
<p>Nonfiction</p>
<ul>
<li>The Ancien Régime and the Revolution (978-0141441641)</li>
<li>Interpreting the French Revolution (978-0521280495)</li>
</ul>Listing the fiction books sorted by title:
<ul>
{{ range sort hugo.Data.books.fiction "title" }}
<li>{{ .title }} ({{ .author }})</li>
{{ end }}
</ul>Finding a fiction book by ISBN:
{{ range where hugo.Data.books.fiction "isbn" "978-0140443530" }}
<p>{{ .title }} ({{ .author }})</p>
{{ end }}Accessing a key that is not a valid identifier:
{{ index hugo.Data.books "historical-fiction" }}