Data sources
Hugo 可以訪問並 unmarshal 本地和遠端數據來源,包括 CSV、JSON、TOML、YAML 和 XML。使用這些數據來增強現有內容或創建新內容。
數據來源可以是數據目錄中的文件、[全局資源]、[頁面資源] 或 [遠程資源]。
數據目錄
您項目根目錄中的數據目錄可以包含一個或多個數據文件,這些文件可以是扁平的或是嵌套的樹狀結構。Hugo 合併這些數據文件以創建一個單一的數據結構,並可以通過 Site
物件上的 Data
方法訪問。
Hugo 還會將主題和模組中的數據目錄合併到這個單一的數據結構中,其中項目根目錄中的數據目錄會優先。
主題和模組作者可能希望將他們的數據文件命名空間化,以防止衝突。例如:
project/
└── data/
└── mytheme/
└── foo.json
請參閱 Data
方法的文檔,了解詳細信息和示例。
全局資源
使用 resources.Get
和 transform.Unmarshal
函數來訪問作為全局資源存在的數據文件。
請參閱 transform.Unmarshal
文檔,了解詳細信息和示例。
頁面資源
使用 Page
物件上的 Resources.Get
方法,並結合 transform.Unmarshal
函數來訪問作為頁面資源存在的數據文件。
請參閱 transform.Unmarshal
文檔,了解詳細信息和示例。
遠程資源
使用 resources.GetRemote
和 transform.Unmarshal
函數來訪問遠程數據。
請參閱 transform.Unmarshal
文檔,了解詳細信息和示例。
增強現有內容
使用數據來源來增強現有內容。例如,創建一個短代碼來從全局 CSV 資源渲染 HTML 表格。
assets/pets.csv
"name","type","breed","age"
"Spot","dog","Collie","3"
"Felix","cat","Malicious","7"
content/example.md
{{< csv-to-table "pets.csv" >}}
layouts/shortcodes/csv-to-table.html
{{ with $file := .Get 0 }}
{{ with resources.Get $file }}
{{ with . | transform.Unmarshal }}
<table>
<thead>
<tr>
{{ range index . 0 }}
<th>{{ . }}</th>
{{ end }}
</tr>
</thead>
<tbody>
{{ range after 1 . }}
<tr>
{{ range . }}
<td>{{ . }}</td>
{{ end }}
</tr>
{{ end }}
</tbody>
</table>
{{ end }}
{{ else }}
{{ errorf "The %q shortcode was unable to find %s. See %s" $.Name $file $.Position }}
{{ end }}
{{ else }}
{{ errorf "The %q shortcode requires one positional argument, the path to the CSV file relative to the assets directory. See %s" .Name .Position }}
{{ end }}
Hugo 會渲染如下內容:
name | type | breed | age |
---|---|---|---|
Spot | dog | Collie | 3 |
Felix | cat | Malicious | 7 |
創建新內容
使用 [內容適配器] 來創建新內容。