Hugo 數據源
Hugo 可以訪問和 unmarshal 本地和遠程數據源,包括 CSV、JSON、TOML、YAML 和 XML。使用這些數據來增強現有內容或創建新內容。
數據源可以是 data 目錄中的文件、全局資源、頁面資源 或 遠程資源。
數據目錄
項目根目錄中的 data 目錄可以包含一個或多個數據文件,可以是扁平結構或嵌套樹結構。Hugo 合並這些數據文件以創建單個數據結構,可通過 Site 對象上的 Data 方法訪問。
Hugo 還將主題和模塊中的數據目錄合並到這個單一數據結構中,其中項目根目錄中的 data 目錄優先。
Hugo 將合並後的數據結構讀入內存並在整個構建過程中保留在那裡。對於不經常訪問的數據,請使用全局或頁面資源。
主題和模塊作者可能希望命名空間他們的數據文件以防止沖突。例如:
project/
└── data/
└── mytheme/
└── foo.json不要將 CSV 文件放在 data 目錄中。將 CSV 文件作為頁面、全局或遠程資源訪問。
有關 Site 對象上 Data 方法的詳細信息和示例,請參閱文檔。
全局資源
使用 resources.Get 和 transform.Unmarshal 函數訪問作為全局資源存在的數據文件。
有關詳細信息和示例,請參閱 transform.Unmarshal 文檔。
頁面資源
使用 Page 對象上的 Resources.Get 方法結合 transform.Unmarshal 函數訪問作為頁面資源存在的數據文件。
有關詳細信息和示例,請參閱 transform.Unmarshal 文檔。
遠程資源
使用 resources.GetRemote 和 transform.Unmarshal 函數訪問遠程數據。
有關詳細信息和示例,請參閱 transform.Unmarshal 文檔。
增強現有內容
使用數據源來增強現有內容。例如,創建 shortcode 來渲染來自全局 CSV 資源的 HTML 表格。
"name","type","breed","age"
"Spot","dog","Collie","3"
"Felix","cat","Malicious","7"{{< csv-to-table "pets.csv" >}}{{ 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 |
創建新內容
使用 內容適配器 創建新內容。