数据
语法
SITE.Data
返回
map
在 `Site` 对象上使用 `Data` 方法来访问 `data` 目录中或任何 挂载到 `data` 目录的目录中的数据。支持的数据格式包括 JSON、TOML、YAML 和 XML。
考虑以下 `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" }}