数据源
Hugo 可以访问和 反序列化 本地和远程数据源,包括 CSV、JSON、TOML、YAML 和 XML。 使用这些数据来增强现有内容或创建新内容。
数据源可以是数据目录中的文件、 全局资源 、 页面资源 或 远程资源 。
数据目录
项目根目录中的数据目录可能包含一个或多个数据文件,这些文件可以采用扁平结构或嵌套树状结构。Hugo 会合并数据文件以创建单个数据结构,可以通过 Site
对象上的 Data
方法访问该结构。
Hugo 还将主题和模块中的数据目录合并到此单个数据结构中,其中项目根目录中的数据目录优先。
主题和模块作者可能希望为其数据文件命名空间,以防止冲突。例如:
project/
└── data/
└── mytheme/
└── foo.json
有关详细信息和示例,请参阅 Site
对象上的 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 |
创建新内容
使用 内容适配器 创建新内容。