Data
使用 Data
方法於 Site
物件上訪問資料目錄中的資料,或是任何掛載到資料目錄中的目錄。支持的資料格式包括 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" }}