HUGO
Menu
GitHub 87548 stars Mastodon

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.Gettransform.Unmarshal 函数访问作为全局资源存在的数据文件。

有关详细信息和示例,请参阅 transform.Unmarshal 文档。

页面资源

使用 Page 对象上的 Resources.Get 方法结合 transform.Unmarshal 函数访问作为页面资源存在的数据文件。

有关详细信息和示例,请参阅 transform.Unmarshal 文档。

远程资源

使用 resources.GetRemotetransform.Unmarshal 函数访问远程数据。

有关详细信息和示例,请参阅 transform.Unmarshal 文档。

增强现有内容

使用数据源来增强现有内容。例如,创建 shortcode 来渲染来自全局 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

创建新内容

使用 内容适配器 创建新内容。


Last updated: January 1, 0001
Improve this page