数据源
Hugo 可以访问和解组本地和远程数据源,包括 CSV、JSON、TOML、YAML 和 XML。 使用这些数据来增强现有内容或创建新内容。
数据源可以是 data
目录中的文件、全局资源、页面资源或远程资源。
数据目录
项目根目录中的 data
目录可能包含一个或多个数据文件,可以是平面结构或嵌套树结构。 Hugo 合并数据文件以创建一个单一的数据结构,可以使用 Site
对象上的 Data
方法访问。
Hugo 还将来自主题和模块的数据目录合并到这个单一的数据结构中,其中项目根目录中的 data
目录具有优先权。
主题和模块作者可能希望对他们的数据文件进行命名空间,以防止冲突。例如
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 将其渲染为
姓名 | 类型 | 品种 | 年龄 |
---|---|---|---|
斑点 | 狗 | 柯利犬 | 3 |
菲利克斯 | 猫 | 恶意 | 7 |
创建新内容
使用内容适配器来创建新内容。