Data
返回由 data 目录中的文件组成的数据结构。
Syntax
SITE.Data
Returns
map
使用 Site 对象上的 Data 方法来访问 data 目录中的数据,或访问任何 挂载 到 data 目录的目录中的数据。支持的数据格式包括 JSON、TOML、YAML 和 XML。
虽然 Hugo 可以使用 transform.Unmarshal 函数解包 CSV 文件,但不要将 CSV 文件放在 data 目录中。您无法使用此方法访问 CSV 文件内的数据。
考虑此 data 目录:
data/
├── books/
│ ├── fiction.yaml
│ └── nonfiction.yaml
├── films.json
├── paintings.xml
└── sculptures.toml以及这些数据文件:
data/books/fiction.yaml
- title: The Hunchback of Notre Dame
author: Victor Hugo
isbn: 978-0140443530
- title: Les Misérables
author: Victor Hugo
isbn: 978-0451419439
data/books/nonfiction.yaml
- 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-0521280495{{ range $category, $books := .Site.Data.books }}
<p>{{ $category | title }}</p>
<ul>
{{ range $books }}
<li>{{ .title }} ({{ .isbn }})</li>
{{ end }}
</ul>
{{ end }}Hugo 将其渲染为:
<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>要将列表限制为小说并按标题排序:
<ul>
{{ range sort .Site.Data.books.fiction "title" }}
<li>{{ .title }} ({{ .author }})</li>
{{ end }}
</ul>要按 ISBN 查找小说书籍:
{{ range where .Site.Data.books.fiction "isbn" "978-0140443530" }}
<li>{{ .title }} ({{ .author }})</li>
{{ end }}在上面的模板示例中,每个键都是有效的标识符。例如,没有键包含连字符。要访问不是有效标识符的键,请使用 index 函数。例如:
{{ index .Site.Data.books "historical-fiction" }}