HUGO

  • 新闻
  • 文档
  • 主题
  • 社区
  • GitHub
  • 关于 Hugo
    • In this section
    • Introduction
    • Features
    • Privacy
    • Security
    • License
  • 安装
    • In this section
    • macOS
    • Linux
    • Windows
    • BSD
  • 入门
    • In this section
    • Quick start
    • Basic usage
    • Directory structure
    • Configuration
    • Configure markup
    • Glossary of terms
    • External learning resources
  • Quick reference
    • In this section
    • Emojis
    • Functions
    • Methods
    • Page collections
  • 内容管理
    • In this section
    • Organization
    • Page bundles
    • Content formats
    • Front matter
    • Build options
    • Page resources
    • Image processing
    • Shortcodes
    • Related content
    • Sections
    • Content types
    • Archetypes
    • Taxonomies
    • Summaries
    • Links and cross references
    • URL management
    • Menus
    • Comments
    • Multilingual
    • Markdown attributes
    • Syntax highlighting
    • Diagrams
    • Mathematics
    • Data sources
    • Content adapters
  • 模板
    • In this section
    • Introduction
    • Template types
    • Lookup order
    • Base templates
    • Home templates
    • Single templates
    • Section templates
    • Taxonomy templates
    • Term templates
    • Partial templates
    • Content view templates
    • Shortcode templates
    • Sitemap templates
    • RSS templates
    • 404 templates
    • robots.txt templates
    • Menus
    • Pagination
    • Embedded templates
    • Custom output formats
  • 函数
    • In this section
    • cast
    • collections
    • compare
    • crypto
    • css
    • data
    • debug
    • diagrams
    • encoding
    • fmt
    • global
    • go template
    • hash
    • hugo
    • images
    • inflect
    • js
    • lang
    • math
    • openapi3
    • os
    • partials
    • path
    • reflect
    • resources
    • safe
    • strings
    • templates
    • time
    • transform
    • urls
  • 方法
    • In this section
    • Duration
    • Menu
    • Menu entry
    • Page
    • Pager
    • Pages
    • Resource
    • Shortcode
    • Site
    • Taxonomy
    • Time
  • Render hooks
    • In this section
    • Introduction
    • Blockquotes
    • Code blocks
    • Headings
    • Images
    • Links
    • Passthrough
    • Tables
  • Hugo Modules
    • In this section
    • Configure Hugo modules
    • Use Hugo Modules
    • Theme components
  • Hugo Pipes
    • In this section
    • Introduction
    • Transpile Sass to CSS
    • PostCSS
    • PostProcess
    • JavaScript building
    • Babel
    • Asset minification
    • Concatenating assets
    • Fingerprinting and SRI hashing
    • Resource from string
    • Resource from template
  • CLI
  • 故障排除
    • In this section
    • Audit
    • Logging
    • Inspection
    • Deprecation
    • Performance
    • FAQs
  • 开发工具
    • In this section
    • Editor plugins
    • Front-ends
    • Search
    • Migrations
    • Other projects
  • 托管 & 部署
    • In this section
    • Hugo Deploy
    • Deploy with Rclone
    • Deploy with Rsync
    • Host on 21YunBox
    • Host on AWS Amplify
    • Host on Azure Static Web Apps
    • Host on Cloudflare Pages
    • Host on Firebase
    • Host on GitHub Pages
    • Host on GitLab Pages
    • Host on KeyCDN
    • Host on Netlify
    • Host on Render
  • 贡献
    • In this section
    • Development
    • Documentation
    • Themes
  • Maintenance
CONTENT MANAGEMENT

Content adapters

Create content adapters to dynamically add content when building your site.
New in v0.126.0

Overview

A content adapter is a template that dynamically creates pages when building a site. For example, use a content adapter to create pages from a remote data source such as JSON, TOML, YAML, or XML.

Unlike templates that reside in the layouts directory, content adapters reside in the content directory, no more than one per directory per language. When a content adapter creates a page, the page’s logical path will be relative to the content adapter.

content/
├── articles/
│   ├── _index.md
│   ├── article-1.md
│   └── article-2.md
├── books/
│   ├── _content.gotmpl  <-- content adapter
│   └── _index.md
└── films/
    ├── _content.gotmpl  <-- content adapter
    └── _index.md

Each content adapter is named _content.gotmpl and uses the same syntax as templates in the layouts directory. You can use any of the template functions within a content adapter, as well as the methods described below.

Methods

Use these methods within a content adapter.

AddPage

Adds a page to the site.

content/books/_content.gotmpl
{{ $content := dict
  "mediaType" "text/markdown"
  "value" "The _Hunchback of Notre Dame_ was written by Victor Hugo."
}}
{{ $page := dict
  "content" $content
  "kind" "page"
  "path" "the-hunchback-of-notre-dame"
  "title" "The Hunchback of Notre Dame"
}}
{{ .AddPage $page }}
AddResource

Adds a page resource to the site.

content/books/_content.gotmpl
{{ with resources.Get "images/a.jpg" }}
  {{ $content := dict
    "mediaType" .MediaType.Type
    "value" .
  }}
  {{ $resource := dict
    "content" $content
    "path" "the-hunchback-of-notre-dame/cover.jpg"
  }}
  {{ $.AddResource $resource }}
{{ end }}

Then retrieve the new page resource with something like:

layouts/_default/single.html
{{ with .Resources.Get "cover.jpg" }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
Site

Returns the Site to which the pages will be added.

content/books/_content.gotmpl
{{ .Site.Title }}

Note that the Site returned isn’t fully built when invoked from the content adapters; if you try to call methods that depends on pages, e.g. .Site.Pages, you will get an error saying “this method cannot be called before the site is fully initialized”.

Store

Returns a persistent “scratch pad” to store and manipulate data. The main use case for this is to transfer values between executions when EnableAllLanguages is set. See examples.

content/books/_content.gotmpl
{{ .Store.Set "key" "value" }}
{{ .Store.Get "key" }}
EnableAllLanguages

By default, Hugo executes the content adapter for the language defined by the _content.gotmpl file . Use this method to activate the content adapter for all languages.

content/books/_content.gotmpl
{{ .EnableAllLanguages }}
{{ $content := dict
  "mediaType" "text/markdown"
  "value" "The _Hunchback of Notre Dame_ was written by Victor Hugo."
}}
{{ $page := dict
  "content" $content
  "kind" "page"
  "path" "the-hunchback-of-notre-dame"
  "title" "The Hunchback of Notre Dame"
}}
{{ .AddPage $page }}

Page map

Set any front matter field in the map passed to the AddPage method, excluding markup. Instead of setting the markup field, specify the content.mediaType as described below.

This table describes the fields most commonly passed to the AddPage method.

Key Description Required
content.mediaType The content media type. Default is text/markdown. See content formats for examples.  
content.value The content value as a string.  
dates.date The page creation date as a time.Time value.  
dates.expiryDate The page expiry date as a time.Time value.  
dates.lastmod The page last modification date as a time.Time value.  
dates.publishDate The page publication date as a time.Time value.  
kind The page kind. Default is page.  
params A map of page parameters.  
path The page’s logical path relative to the content adapter. Do not include a leading slash or file extension. ✔️
title The page title.  

While path is the only required field, we recommend setting title as well.

When setting the path, Hugo transforms the given string to a logical path. For example, setting path to A B C produces a logical path of /section/a-b-c.

Resource map

Construct the map passed to the AddResource method using the fields below.

Key Description Required
content.mediaType The content media type. ✔️
content.value The content value as a string or resource. ✔️
name The resource name.  
params A map of resource parameters.  
path The resources’s logical path relative to the content adapter. Do not include a leading slash. ✔️
title The resource title.  

If the content.value is a string Hugo creates a new resource. If the content.value is a resource, Hugo obtains the value from the existing resource.

When setting the path, Hugo transforms the given string to a logical path. For example, setting path to A B C/cover.jpg produces a logical path of /section/a-b-c/cover.jpg.

Example

Create pages from remote data, where each page represents a book review.

Step 1
Create the content structure.
content/
└── books/
    ├── _content.gotmpl  <-- content adapter
    └── _index.md
Step 2
Inspect the remote data to determine how to map key-value pairs to front matter fields.

https://gohugo.io/shared/examples/data/books.json

Step 3
Create the content adapter.
content/books/_content.gotmpl
{{/* Get remote data. */}}
{{ $data := dict }}
{{ $url := "https://gohugo.io/shared/examples/data/books.json" }}
{{ with resources.GetRemote $url }}
  {{ with .Err }}
    {{ errorf "Unable to get remote resource %s: %s" $url . }}
  {{ else }}
    {{ $data = . | transform.Unmarshal }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get remote resource %s" $url }}
{{ end }}

{{/* Add pages and page resources. */}}
{{ range $data }}

  {{/* Add page. */}}
  {{ $content := dict "mediaType" "text/markdown" "value" .summary }}
  {{ $dates := dict "date" (time.AsTime .date) }}
  {{ $params := dict "author" .author "isbn" .isbn "rating" .rating "tags" .tags }}
  {{ $page := dict
    "content" $content
    "dates" $dates
    "kind" "page"
    "params" $params
    "path" .title
    "title" .title
  }}
  {{ $.AddPage $page }}

  {{/* Add page resource. */}}
  {{ $item := . }}
  {{ with $url := $item.cover }}
    {{ with resources.GetRemote $url }}
      {{ with .Err }}
        {{ errorf "Unable to get remote resource %s: %s" $url . }}
      {{ else }}
        {{ $content := dict "mediaType" .MediaType.Type "value" .Content }}
        {{ $params := dict "alt" $item.title }}
        {{ $resource := dict
          "content" $content
          "params" $params
          "path" (printf "%s/cover.%s" $item.title .MediaType.SubType)
        }}
        {{ $.AddResource $resource }}
      {{ end }}
    {{ else }}
      {{ errorf "Unable to get remote resource %s" $url }}
    {{ end }}
  {{ end }}

{{ end }}
Step 4
Create a single template to render each book review.
layouts/books/single.html
{{ define "main" }}
  <h1>{{ .Title }}</h1>

  {{ with .Resources.GetMatch "cover.*" }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ .Params.alt }}">
  {{ end }}

  <p>Author: {{ .Params.author }}</p>

  <p>
    ISBN: {{ .Params.isbn }}<br>
    Rating: {{ .Params.rating }}<br>
    Review date: {{ .Date | time.Format ":date_long" }}
  </p>

  {{ with .GetTerms "tags" }}
    <p>Tags:</p>
    <ul>
      {{ range . }}
        <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
      {{ end }}
    </ul>
  {{ end }}

  {{ .Content }}
{{ end }}

Multilingual sites

With multilingual sites you can:

  1. Create one content adapter for all languages using the EnableAllLanguages method as described above.
  2. Create content adapters unique to each language. See the examples below.

Translations by file name

With this site configuration:

hugo.
     
languages:
  de:
    weight: 2
  en:
    weight: 1
[languages]
  [languages.de]
    weight = 2
  [languages.en]
    weight = 1
{
   "languages": {
      "de": {
         "weight": 2
      },
      "en": {
         "weight": 1
      }
   }
}

Include a language designator in the content adapter’s file name.

content/
└── books/
    ├── _content.de.gotmpl
    ├── _content.en.gotmpl
    ├── _index.de.md
    └── _index.en.md

Translations by content directory

With this site configuration:

hugo.
     
languages:
  de:
    contentDir: content/de
    weight: 2
  en:
    contentDir: content/en
    weight: 1
[languages]
  [languages.de]
    contentDir = 'content/de'
    weight = 2
  [languages.en]
    contentDir = 'content/en'
    weight = 1
{
   "languages": {
      "de": {
         "contentDir": "content/de",
         "weight": 2
      },
      "en": {
         "contentDir": "content/en",
         "weight": 1
      }
   }
}

Create a single content adapter in each directory:

content/
├── de/
│   └── books/
│       ├── _content.gotmpl
│       └── _index.md
└── en/
    └── books/
        ├── _content.gotmpl
        └── _index.md

Page collisions

Two or more pages collide when they have the same publication path. Due to concurrency, the content of the published page is indeterminate. Consider this example:

content/
└── books/
    ├── _content.gotmpl  <-- content adapter
    ├── _index.md
    └── the-hunchback-of-notre-dame.md

If the content adapter also creates books/the-hunchback-of-notre-dame, the content of the published page is indeterminate. You can not define the processing order.

To detect page collisions, use the --printPathWarnings flag when building your site.

On this page

  • Overview
  • Methods
  • Page map
  • Resource map
  • Example
  • Multilingual sites
  • Page collisions
Last updated: September 10, 2024: Update content-adapters.md (bfe9cdc3)
By the Hugo Authors
Hugo Logo
  • File an Issue
  • Get Help
  • @GoHugoIO
  • @spf13
  • @bepsays
 

The Hugo logos are copyright © Steve Francia 2013–2024.

The Hugo Gopher is based on an original work by Renée French.

  • 新闻
  • 文档
  • 主题
  • 社区
  • GitHub
  • 关于 Hugo
  • 安装
  • 入门
  • Quick reference
  • 内容管理
  • 模板
  • 函数
  • 方法
  • Render hooks
  • Hugo Modules
  • Hugo Pipes
  • CLI
  • 故障排除
  • 开发工具
  • 托管 & 部署
  • 贡献
  • Maintenance