数据
Syntax
SITE.Data
Returns
map
使用 Site
对象的 Data
方法访问数据目录或挂载到数据目录的任何目录中的数据。支持的数据格式包括JSON、TOML、YAML和XML。
考虑这个数据目录:
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" }}