Debian Codegraph @

docs/content/en/functions/hugo/Data.md

raw
1 ---
2 title: hugo.Data
3 description: Returns a data structure composed from the files in the data directory.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 returnType: map
9 signatures: [hugo.Data]
10 ---
11
12 {{< new-in 0.156.0 />}}
13
14 Use the `hugo.Data` function to access data within the `data` directory, or within any directory [mounted][] to the `data` directory. Supported data formats include JSON, TOML, YAML, and XML.
15
16 > [!NOTE]
17 > Although Hugo can [unmarshal](g) 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 method.
18
19 Consider this `data` directory:
20
21 ```tree
22 data/
23 ├── books/
24 │ ├── fiction.yaml
25 │ └── nonfiction.yaml
26 ├── films.json
27 ├── paintings.xml
28 └── sculptures.toml
29 ```
30
31 And these data files:
32
33 ```yaml {file="data/books/fiction.yaml"}
34 - title: The Hunchback of Notre Dame
35 author: Victor Hugo
36 isbn: 978-0140443530
37 - title: Les Misérables
38 author: Victor Hugo
39 isbn: 978-0451419439
40 ```
41
42 ```yaml {file="data/books/nonfiction.yaml"}
43 - title: The Ancien Régime and the Revolution
44 author: Alexis de Tocqueville
45 isbn: 978-0141441641
46 - title: Interpreting the French Revolution
47 author: François Furet
48 isbn: 978-0521280495
49 ```
50
51 Access the data by [chaining](g) the [identifiers](g):
52
53 ```go-html-template
54 {{ range $category, $books := hugo.Data.books }}
55 <p>{{ $category | title }}</p>
56 <ul>
57 {{ range $books }}
58 <li>{{ .title }} ({{ .isbn }})</li>
59 {{ end }}
60 </ul>
61 {{ end }}
62 ```
63
64 Hugo renders this to:
65
66 ```html
67 <p>Fiction</p>
68 <ul>
69 <li>The Hunchback of Notre Dame (978-0140443530)</li>
70 <li>Les Misérables (978-0451419439)</li>
71 </ul>
72 <p>Nonfiction</p>
73 <ul>
74 <li>The Ancien Régime and the Revolution (978-0141441641)</li>
75 <li>Interpreting the French Revolution (978-0521280495)</li>
76 </ul>
77 ```
78
79 To limit the listing to fiction, and sort by title:
80
81 ```go-html-template
82 <ul>
83 {{ range sort hugo.Data.books.fiction "title" }}
84 <li>{{ .title }} ({{ .author }})</li>
85 {{ end }}
86 </ul>
87 ```
88
89 To find a fiction book by ISBN:
90
91 ```go-html-template
92 {{ range where hugo.Data.books.fiction "isbn" "978-0140443530" }}
93 <li>{{ .title }} ({{ .author }})</li>
94 {{ end }}
95 ```
96
97 In the template examples above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`][] function. For example:
98
99 ```go-html-template
100 {{ index hugo.Data.books "historical-fiction" }}
101 ```
102
103 [`index`]: /functions/collections/indexfunction/
104 [`transform.Unmarshal`]: /functions/transform/unmarshal/
105 [mounted]: /configuration/module/#mounts