Merge commit '5be51ac3db225d5df501ed1fa1499c41d97dbf65'

This commit is contained in:
Bjørn Erik Pedersen
2025-04-10 13:04:51 +02:00
987 changed files with 12379 additions and 14083 deletions

View File

@@ -1,6 +1,6 @@
---
cascade:
_build:
build:
list: never
publishResources: false
render: never
@@ -9,5 +9,5 @@ cascade:
<!--
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -0,0 +1,13 @@
---
_comment: Do not remove front matter.
---
Content format|Media type|Identifier|File extensions
:--|:--|:--|:--
Markdown|`text/markdown`|`markdown`|`markdown`,`md`, `mdown`
HTML|`text/html`|`html`|`htm`, `html`
Emacs Org Mode|`text/org`|`org`|`org`
AsciiDoc|`text/asciidoc`|`asciidoc`|`ad`, `adoc`, `asciidoc`
Pandoc|`text/pandoc`|`pandoc`|`pandoc`, `pdc`
reStructuredText|`text/rst`|`rst`|`rst`
<!-- do not remove this comment -->

View File

@@ -0,0 +1,8 @@
---
_comment: Do not remove front matter.
---
> [!note]
> The [page collections quick reference guide] describes methods and functions to filter, sort, and group page collections.
[page collections quick reference guide]: /quick-reference/page-collections/

View File

@@ -0,0 +1,108 @@
---
_comment: Do not remove front matter.
---
params
: (`map` or `slice`) Params that can be imported as JSON in your JS files, e.g.
```go-html-template
{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}
```
And then in your JS file:
```js
import * as params from '@params';
```
Note that this is meant for small data sets, e.g., configuration settings. For larger data sets, please put/mount the files into `assets` and import them directly.
minify
: (`bool`) Whether to let `js.Build` handle the minification.
loaders
: {{< new-in 0.140.0 />}}
: (`map`) Configuring a loader for a given file type lets you load that file type with an `import` statement or a `require` call. For example, configuring the `.png` file extension to use the data URL loader means importing a `.png` file gives you a data URL containing the contents of that image. Loaders available are `none`, `base64`, `binary`, `copy`, `css`, `dataurl`, `default`, `empty`, `file`, `global-css`, `js`, `json`, `jsx`, `local-css`, `text`, `ts`, `tsx`. See https://esbuild.github.io/api/#loader.
inject
: (`slice`) This option allows you to automatically replace a global variable with an import from another file. The path names must be relative to `assets`. See https://esbuild.github.io/api/#inject.
shims
: (`map`) This option allows swapping out a component with another. A common use case is to load dependencies like React from a CDN (with _shims_) when in production, but running with the full bundled `node_modules` dependency during development:
```go-html-template
{{ $shims := dict "react" "js/shims/react.js" "react-dom" "js/shims/react-dom.js" }}
{{ $js = $js | js.Build dict "shims" $shims }}
```
The _shim_ files may look like these:
```js
// js/shims/react.js
module.exports = window.React;
```
```js
// js/shims/react-dom.js
module.exports = window.ReactDOM;
```
With the above, these imports should work in both scenarios:
```js
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
```
target
: (`string`) The language target. One of: `es5`, `es2015`, `es2016`, `es2017`, `es2018`, `es2019`, `es2020`, `es2021`, `es2022`, `es2023`, `es2024`, or `esnext`. Default is `esnext`.
platform
: {{< new-in 0.140.0 />}}
: (`string`) One of `browser`, `node`, `neutral`. Default is `browser`. See https://esbuild.github.io/api/#platform.
externals
: (`slice`) External dependencies. Use this to trim dependencies you know will never be executed. See https://esbuild.github.io/api/#external.
defines
: (`map`) This option allows you to define a set of string replacements to be performed when building. It must be a map where each key will be replaced by its value.
```go-html-template
{{ $defines := dict "process.env.NODE_ENV" `"development"` }}
```
drop
: {{< new-in 0.144.0 />}}
: (`string`) Edit your source code before building to drop certain constructs: One of `debugger` or `console`.
: See https://esbuild.github.io/api/#drop
sourceMap
: (`string`) Whether to generate `inline`, `linked`, or `external` source maps from esbuild. Linked and external source maps will be written to the target with the output file name + ".map". When `linked` a `sourceMappingURL` will also be written to the output file. By default, source maps are not created. Note that the `linked` option was added in Hugo 0.140.0.
sourcesContent
: {{< new-in 0.140.0 />}}
: (`bool`) Whether to include the content of the source files in the source map. By default, this is `true`.
JSX
: {{< new-in 0.124.0 />}}
: (`string`) How to handle/transform JSX syntax. One of: `transform`, `preserve`, `automatic`. Default is `transform`. Notably, the `automatic` transform was introduced in React 17+ and will cause the necessary JSX helper functions to be imported automatically. See https://esbuild.github.io/api/#jsx.
JSXImportSource
: {{< new-in 0.124.0 />}}
: (`string`) Which library to use to automatically import its JSX helper functions from. This only works if `JSX` is set to `automatic`. The specified library needs to be installed through npm and expose certain exports. See https://esbuild.github.io/api/#jsx-import-source.
The combination of `JSX` and `JSXImportSource` is helpful if you want to use a non-React JSX library like Preact, e.g.:
```go-html-template
{{ $js := resources.Get "js/main.jsx" | js.Build (dict "JSX" "automatic" "JSXImportSource" "preact") }}
```
With the above, you can use Preact components and JSX without having to manually import `h` and `Fragment` every time:
```jsx
import { render } from 'preact';
const App = () => <>Hello world!</>;
const container = document.getElementById('app');
if (container) render(<App />, container);
```

View File

@@ -0,0 +1,8 @@
---
_comment: Do not remove front matter.
---
> [!note]
> Localization of dates, currencies, numbers, and percentages is performed by the [gohugoio/locales] package. The language tag of the current site must match one of the listed locales.
[gohugoio/locales]: https://github.com/gohugoio/locales

View File

@@ -2,7 +2,7 @@
_comment: Do not remove front matter.
---
The [`anchorize`] and [`urlize`] functions are similar:
The [`anchorize`] and [`urlize`] functions are similar:
[`anchorize`]: /functions/urls/anchorize/
[`urlize`]: /functions/urls/urlize/

View File

@@ -0,0 +1,13 @@
---
_comment: Do not remove front matter.
---
> [!note] Hugo Modules are Go Modules
> You need [Go] version 1.18 or later and [Git] to use Hugo Modules. For older sites hosted on Netlify, please ensure the `GO_VERSION` environment variable is set to `1.18` or higher.
>
> Go Modules resources:
> - [go.dev/wiki/Modules](https://go.dev/wiki/Modules)
> - [blog.golang.org/using-go-modules](https://go.dev/blog/using-go-modules)
[Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
[Go]: https://go.dev/doc/install

View File

@@ -13,4 +13,4 @@ Deploy your site directly to a Google Cloud Storage bucket, an AWS S3 bucket, or
[dart sass]: /functions/css/sass/#dart-sass
[processing images]: /content-management/image-processing/
[transpile sass to css]: /functions/css/sass/
[details]: /hosting-and-deployment/hugo-deploy/
[details]: /host-and-deploy/deploy-with-hugo-deploy/

View File

@@ -7,7 +7,7 @@ _comment: Do not remove front matter.
To build the extended or extended/deploy edition from source you must:
1. Install [Git]
1. Install [Go] version 1.20 or later
1. Install [Go] version 1.23.0 or later
1. Install a C compiler, either [GCC] or [Clang]
1. Update your `PATH` environment variable as described in the [Go documentation]

View File

@@ -0,0 +1,31 @@
---
_comment: Do not remove front matter.
---
<!--
This description list intentionally excludes the `pageRef` and `url` properties. Add those properties manually after using the include shortcode to include this list.
-->
identifier
: (`string`) Required when two or more menu entries have the same `name`, or when localizing the `name` using translation tables. Must start with a letter, followed by letters, digits, or underscores.
name
: (`string`) The text to display when rendering the menu entry.
params
: (`map`) User-defined properties for the menu entry.
parent
: (`string`) The `identifier` of the parent menu entry. If `identifier` is not defined, use `name`. Required for child entries in a nested menu.
post
: (`string`) The HTML to append when rendering the menu entry.
pre
: (`string`) The HTML to prepend when rendering the menu entry.
title
: (`string`) The HTML `title` attribute of the rendered menu entry.
weight
: (`int`) A non-zero integer indicating the entry's position relative the root of the menu, or to its parent for a child entry. Lighter entries float to the top, while heavier entries sink to the bottom.

View File

@@ -32,13 +32,13 @@ content/
And these templates:
{{< code file=layouts/_default/list.html >}}
```go-html-template {file="layouts/_default/list.html"}
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
```
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ with .Prev }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
@@ -46,7 +46,7 @@ And these templates:
{{ with .Next }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
```
When you visit page-2:
@@ -55,6 +55,6 @@ When you visit page-2:
To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility.
[site configuration]: /getting-started/configuration/#configure-page
[site configuration]: /configuration/page/
[`Next`]: /methods/pages/prev
[`Prev`]: /methods/pages/prev

View File

@@ -32,13 +32,13 @@ content/
And these templates:
{{< code file=layouts/_default/list.html >}}
```go-html-template {file="layouts/_default/list.html"}
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
```
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
@@ -46,7 +46,7 @@ And these templates:
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
```
When you visit page-2:
@@ -55,7 +55,7 @@ When you visit page-2:
To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility.
[site configuration]: /getting-started/configuration/#configure-page
[site configuration]: /configuration/page/
[`Next`]: /methods/pages/prev
[`Prev`]: /methods/pages/prev

View File

@@ -0,0 +1,35 @@
---
_comment: Do not remove front matter.
---
### Get IDENTIFIER
(`any`) Returns the `OutputFormat` object with the given identifier.
### MediaType
(`media.Type`) Returns the media type of the output format.
### MediaType.MainType
(`string`) Returns the main type of the output format's media type.
### MediaType.SubType
(`string`) Returns the subtype of the current format's media type.
### Name
(`string`) Returns the output identifier of the output format.
### Permalink
(`string`) Returns the permalink of the page generated by the current output format.
### Rel
(`string`) Returns the `rel` value of the output format, either the default or as defined in the site configuration.
### RelPermalink
(`string`) Returns the relative permalink of the page generated by the current output format.

View File

@@ -32,13 +32,13 @@ content/
And these templates:
{{< code file=layouts/_default/list.html >}}
{{ range .Pages.ByWeight}}
```go-html-template {file="layouts/_default/list.html"}
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
```
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ $pages := .CurrentSection.Pages.ByWeight }}
{{ with $pages.Prev . }}
@@ -48,7 +48,7 @@ And these templates:
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
```
When you visit page-2:
@@ -57,7 +57,7 @@ When you visit page-2:
To reverse the meaning of _next_ and _previous_ you can chain the [`Reverse`] method to the page collection definition:
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ $pages := .CurrentSection.Pages.ByWeight.Reverse }}
{{ with $pages.Prev . }}
@@ -67,6 +67,6 @@ To reverse the meaning of _next_ and _previous_ you can chain the [`Reverse`] me
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
```
[`Reverse`]: /methods/pages/reverse/

View File

@@ -0,0 +1,6 @@
---
_comment: Do not remove front matter.
---
> [!note]
> Use this method with [global resources](g), [page resources](g), or [remote resources](g).

View File

@@ -34,9 +34,9 @@ To capture the "genres" `Taxonomy` object from within any template, use the [`Ta
To capture the "genres" `Taxonomy` object when rendering its page with a taxonomy template, use the [`Terms`] method on the page's [`Data`] object:
{{< code file=layouts/_default/taxonomy.html >}}
```go-html-template {file="layouts/_default/taxonomy.html"}
{{ $taxonomyObject := .Data.Terms }}
{{< /code >}}
```
To inspect the data structure:

View File

@@ -0,0 +1,71 @@
---
_comment: Do not remove front matter.
---
`:year`
: The 4-digit year as defined in the front matter `date` field.
`:month`
: The 2-digit month as defined in the front matter `date` field.
`:monthname`
: The name of the month as defined in the front matter `date` field.
`:day`
: The 2-digit day as defined in the front matter `date` field.
`:weekday`
: The 1-digit day of the week as defined in the front matter `date` field (Sunday = `0`).
`:weekdayname`
: The name of the day of the week as defined in the front matter `date` field.
`:yearday`
: The 1- to 3-digit day of the year as defined in the front matter `date` field.
`:section`
: The content's section.
`:sections`
: The content's sections hierarchy. You can use a selection of the sections using _slice syntax_: `:sections[1:]` includes all but the first, `:sections[:last]` includes all but the last, `:sections[last]` includes only the last, `:sections[1:2]` includes section 2 and 3. Note that this slice access will not throw any out-of-bounds errors, so you don't have to be exact.
`:title`
: The `title` as defined in front matter, else the automatic title. Hugo generates titles automatically for section, taxonomy, and term pages that are not backed by a file.
`:slug`
: The `slug` as defined in front matter, else the `title` as defined in front matter, else the automatic title. Hugo generates titles automatically for section, taxonomy, and term pages that are not backed by a file.
`:filename`
: The content's file name without extension, applicable to the `page` page kind.
{{< deprecated-in v0.144.0 >}}
The `:filename` token has been deprecated. Use `:contentbasename` instead.
{{< /deprecated-in >}}
`:slugorfilename`
: The `slug` as defined in front matter, else the content's file name without extension, applicable to the `page` page kind.
{{< deprecated-in v0.144.0 >}}
The `:slugorfilename` token has been deprecated. Use `:slugorcontentbasename` instead.
{{< /deprecated-in >}}
`:contentbasename`
: {{< new-in 0.144.0 />}}
: The [content base name].
[content base name]: /methods/page/file/#contentbasename
`:slugorcontentbasename`
: {{< new-in 0.144.0 />}}
: The `slug` as defined in front matter, else the [content base name].
For time-related values, you can also use the layout string components defined in Go's [time package]. For example:
[time package]: https://pkg.go.dev/time#pkg-constants
{{< code-toggle file=hugo >}}
permalinks:
posts: /:06/:1/:2/:title/
{{< /code-toggle >}}
[content base name]: /methods/page/file/#contentbasename

View File

@@ -0,0 +1,10 @@
---
_comment: Do not remove front matter.
---
By default, Hugo will throw an error and fail the build if it cannot resolve the path. You can change this to a warning in your site configuration, and specify a URL to return when the path cannot be resolved.
{{< code-toggle file=hugo >}}
refLinksErrorLevel = 'warning'
refLinksNotFoundURL = '/some/other/url'
{{< /code-toggle >}}

View File

@@ -0,0 +1,12 @@
---
_comment: Do not remove front matter.
---
path
: (`string`) The path to the target page. Paths without a leading slash (`/`) are resolved first relative to the current page, and then relative to the rest of the site.
lang
: (`string`) The language of the target page. Default is the current language. Optional.
outputFormat
: (`string`) The output format of the target page. Default is the current output format. Optional.

View File

@@ -8,7 +8,7 @@ _comment: Do not remove front matter.
The primary use case for `PageInner` is to resolve links and [page resources](g) relative to an included `Page`. For example, create an "include" shortcode to compose a page from multiple content files, while preserving a global context for footnotes and the table of contents:
{{< code file=layouts/shortcodes/include.html >}}
```go-html-template {file="layouts/shortcodes/include.html" copy=true}
{{ with .Get 0 }}
{{ with $.Page.GetPage . }}
{{- .RenderShortcodes }}
@@ -18,13 +18,13 @@ The primary use case for `PageInner` is to resolve links and [page resources](g)
{{ else }}
{{ errorf "The %q shortcode requires a positional parameter indicating the logical path of the file to include. See %s" .Name .Position }}
{{ end }}
{{< /code >}}
```
Then call the shortcode in your Markdown:
{{< code file=content/posts/p1.md >}}
```text {file="content/posts/p1.md"}
{{%/* include "/posts/p2" */%}}
{{< /code >}}
```
Any render hook triggered while rendering `/posts/p2` will get:
@@ -33,15 +33,15 @@ Any render hook triggered while rendering `/posts/p2` will get:
`PageInner` falls back to the value of `Page` if not relevant, and always returns a value.
{{% note %}}
The `PageInner` method is only relevant for shortcodes that invoke the [`RenderShortcodes`] method, and you must call the shortcode using the `{{%/*..*/%}}` notation.
[`RenderShortcodes`]: /methods/page/rendershortcodes/
{{% /note %}}
> [!note]
> The `PageInner` method is only relevant for shortcodes that invoke the [`RenderShortcodes`] method, and you must call the shortcode using [Markdown notation].
As a practical example, Hugo's embedded link and image render hooks use the `PageInner` method to resolve markdown link and image destinations. See the source code for each:
- [Embedded link render hook]({{% eturl render-link %}})
- [Embedded image render hook]({{% eturl render-image %}})
- [Embedded link render hook]
- [Embedded image render hook]
[`RenderShortcodes`]: /methods/page/rendershortcodes/
[Markdown notation]: /content-management/shortcodes/#notation
[Embedded link render hook]: {{% eturl render-link %}}
[Embedded image render hook]: {{% eturl render-image %}}

View File

@@ -4,7 +4,7 @@
## Methods
###### Set
### Set
Sets the value of the given key.
@@ -12,7 +12,7 @@ Sets the value of the given key.
{{ .Store.Set "greeting" "Hello" }}
```
###### Get
### Get
Gets the value of the given key.
@@ -21,7 +21,7 @@ Gets the value of the given key.
{{ .Store.Get "greeting" }} → Hello
```
###### Add
### Add
Adds the given value to the existing value(s) of the given key.
@@ -45,7 +45,7 @@ For single values, `Add` accepts values that support Go's `+` operator. If the f
{{ .Store.Get "greetings" }} → [Hello Welcome Cheers]
```
###### SetInMap
### SetInMap
Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`.
@@ -53,9 +53,9 @@ Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to th
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.Get "greetings" }} → map[english:Hello french:Bonjour]
```
```
###### DeleteInMap
### DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
@@ -66,7 +66,7 @@ Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
{{ .Store.Get "greetings" }} → map[french:Bonjour]
```
###### GetSortedMapValues
### GetSortedMapValues
Returns an array of values from `key` sorted by `mapKey`.
@@ -76,7 +76,7 @@ Returns an array of values from `key` sorted by `mapKey`.
{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour]
```
###### Delete
### Delete
Removes the given key.

View File

@@ -11,9 +11,8 @@ codeFences
guessSyntax
: (`bool`) Whether to automatically detect the language if the `LANG` argument is blank or set to a language for which there is no corresponding [lexer](g). Falls back to a plain text lexer if unable to automatically detect the language. Default is `false`.
{{% note %}}
The Chroma syntax highlighter includes lexers for approximately 250 languages, but only 5 of these have implemented automatic language detection.
{{% /note %}}
> [!note]
> The Chroma syntax highlighter includes lexers for approximately 250 languages, but only 5 of these have implemented automatic language detection.
hl_Lines
: (`string`) A space-delimited list of lines to emphasize within the highlighted code. To emphasize lines 2, 3, 4, and 7, set this value to `2-4 7`. This option is independent of the `lineNoStart` option.
@@ -28,32 +27,30 @@ lineNoStart
: (`int`) The number to display at the beginning of the first line. Irrelevant if `lineNos` is `false`. Default is `1`.
lineNos
: (`bool`) Whether to display a number at the beginning of each line. Default is `false`.
: (`any`) Controls line number display. Default is `false`.
- `true`: Enable line numbers, controlled by `lineNumbersInTable`.
- `false`: Disable line numbers.
- `inline`: Enable inline line numbers (sets `lineNumbersInTable` to `false`).
- `table`: Enable table-based line numbers (sets `lineNumbersInTable` to `true`).
lineNumbersInTable
: (`bool`) Whether to render the highlighted code in an HTML table with two cells. The left table cell contains the line numbers, while the right table cell contains the code. Irrelevant if `lineNos` is `false`. Default is `true`.
noClasses
: (`bool`) Whether to use inline CSS styles instead of an external CSS file. To use an external CSS file, set this value to `false` and generate the CSS file using the `hugo gen chromastyles` command. Default is `true`.
: (`bool`) Whether to use inline CSS styles instead of an external CSS file. Default is `true`. To use an external CSS file, set this value to `false` and generate the CSS file from the command line:
```text
hugo gen chromastyles --style=monokai > syntax.css
```
style
: (`string`) The CSS styles to apply to the highlighted code. See the [style gallery] for examples. Case-sensitive. Default is `monokai`.
[style gallery]: https://xyproto.github.io/splash/docs/
: (`string`) The CSS styles to apply to the highlighted code. Case-sensitive. Default is `monokai`. See [syntax highlighting styles].
tabWidth
: (`int`) Substitute this number of spaces for each tab character in your highlighted code. Irrelevant if `noClasses` is `false`. Default is `4`.
wrapperClass
{{< new-in 0.140.2 />}}
: {{< new-in 0.140.2 />}}
: (`string`) The class or classes to use for the outermost element of the highlighted code. Default is `highlight`.
{{% note %}}
Instead of specifying both `lineNos` and `lineNumbersInTable`, you can use the following shorthand notation:
lineNos=inline
: equivalent to `lineNos=true` and `lineNumbersInTable=false`
lineNos=table
: equivalent to `lineNos=true` and `lineNumbersInTable=true`
{{% /note %}}
[syntax highlighting styles]: /quick-reference/syntax-highlighting-styles/

View File

@@ -1,49 +1,4 @@
---
title: The worlds fastest framework for building websites
date: 2017-03-02T12:00:00-05:00
features:
- heading: Blistering Speed
image_path: /images/icon-fast.svg
tagline: What's modern about waiting for your site to build?
copy: Hugo is the fastest tool of its kind. At <1 ms per page, the average site builds in less than a second.
- heading: Robust Content Management
image_path: /images/icon-content-management.svg
tagline: Flexibility rules. Hugo is a content strategist's dream.
copy: Hugo supports unlimited content types, taxonomies, menus, dynamic API-driven content, and more, all without plugins.
- heading: Shortcodes
image_path: /images/icon-shortcodes.svg
tagline: Hugo's shortcodes are Markdown's hidden superpower.
copy: We love the beautiful simplicity of Markdowns syntax, but there are times when we want more flexibility. Hugo shortcodes allow for both beauty and flexibility.
- heading: Built-in Templates
image_path: /images/icon-built-in-templates.svg
tagline: Hugo has common patterns to get your work done quickly.
copy: Hugo ships with pre-made templates to make quick work of SEO, commenting, analytics and other functions. One line of code, and you're done.
- heading: Multilingual and i18n
image_path: /images/icon-multilingual2.svg
tagline: Polyglot baked in.
copy: Hugo provides full i18n support for multi-language sites with the same straightforward development experience Hugo users love in single-language sites.
- heading: Custom Outputs
image_path: /images/icon-custom-outputs.svg
tagline: HTML not enough?
copy: Hugo allows you to output your content in multiple formats, including JSON or AMP, and makes it easy to create your own.
sections:
- heading: "300+ Themes"
cta: Check out the Hugo themes.
link: https://themes.gohugo.io/
color_classes: bg-accent-color white
image: /images/homepage-screenshot-hugo-themes.jpg
copy: "Hugo provides a robust theming system that is easy to implement but capable of producing even the most complicated websites."
- heading: "Capable Templating"
cta: Get Started.
link: templates/
color_classes: bg-primary-color-light black
image: /images/home-page-templating-example.png
copy: "Hugo's Go-based templating provides just the right amount of logic to build anything from the simple to complex."
title: The world's fastest framework for building websites
description: Hugo is one of the most popular open-source static site generators. With its amazing speed and flexibility, Hugo makes building websites fun again.
---
Hugo is one of the most popular open-source static site generators. With its amazing speed and flexibility, Hugo makes building websites fun again.

View File

@@ -1,16 +1,9 @@
---
title: About Hugo
linktitle: About
linkTitle: About
description: Learn about Hugo and its features, privacy protections, and security model.
categories: []
keywords: []
menu:
docs:
identifier: about-hugo-in-this-section
parent: about
weight: 10
weight: 10
aliases: [/about-hugo/,/docs/]
---
Learn about Hugo and its features, privacy protections, and security model.

View File

@@ -1,14 +1,9 @@
---
title: Features
description: Hugo's rich and powerful feature set provides the framework and tools to create static sites that build in seconds, often less.
categories: [about]
categories: []
keywords: []
menu:
docs:
parent: about
weight: 30
weight: 30
toc: true
weight: 20
---
## Framework
@@ -61,7 +56,7 @@ toc: true
: Syntactically highlight code examples using Hugo's embedded syntax highlighter, enabled by default for fenced code blocks in Markdown. The syntax highlighter supports hundreds of code languages and dozens of styles.
[Shortcodes]
: Use Hugo's embedded shortcodes, or create your own, to insert complex content. For example, use shortcodes to include `audio` and `video` elements, render tables from local or remote data sources, insert snippets from other pages, and more.
: Use Hugo's embedded shortcodes, or create your own, to insert complex content. For example, use shortcodes to include `audio` and `video` elements, render tables from local or remote data sources, insert snippets from other pages, and more.
## Content management
@@ -83,7 +78,7 @@ toc: true
## Asset pipelines
[Image processing]
: Convert, resize, crop, rotate, adjust colors, apply filters, overlay text and images, and extract EXIF data.
: Convert, resize, crop, rotate, adjust colors, apply filters, overlay text and images, and extract EXIF data.
[JavaScript bundling]
: Transpile TypeScript and JSX to JavaScript, bundle, tree shake, minify, create source maps, and perform SRI hashing.
@@ -107,18 +102,18 @@ toc: true
[Multilingual]: /content-management/multilingual/
[Multiplatform]: /installation/
[Output formats]: /templates/output-formats/
[Output formats]: /configuration/output-formats/
[Templates]: /templates/introduction/
[Themes]: https://themes.gohugo.io/
[Modules]: /hugo-modules/
[Privacy]: /about/privacy/
[Privacy]: /configuration/privacy/
[Security]: /about/security/
[Content formats]: /content-management/formats/
[CommonMark]: https://spec.commonmark.org/current/
[GitHub Flavored Markdown]: https://github.github.com/gfm/
[Markdown attributes]: /content-management/markdown-attributes/
[Markdown extensions]: /getting-started/configuration-markup/#goldmark-extensions
[Markdown extensions]: /configuration/markup/#extensions
[Markdown render hooks]: /render-hooks/introduction/
[Diagrams]: /content-management/diagrams/
[Mathematics]: /content-management/mathematics/
@@ -137,5 +132,5 @@ toc: true
[Tailwind CSS processing]: /functions/css/tailwindcss/
[Caching]: /functions/partials/includecached/
[Segmentation]: /getting-started/configuration/#configure-segments
[Minification]: /getting-started/configuration/#configure-minify
[Segmentation]: /configuration/segments/
[Minification]: /configuration/minify/

View File

@@ -1,14 +1,9 @@
---
title: Introduction
description: Hugo is a static site generator written in Go, optimized for speed and designed for flexibility.
categories: [about]
description: Hugo is a static site generator written in Go, optimized for speed and designed for flexibility.
categories: []
keywords: []
menu:
docs:
identifier: about-introduction
parent: about
weight: 20
weight: 20
weight: 10
aliases: [/about/what-is-hugo/,/about/benefits/]
---
@@ -32,8 +27,8 @@ Learn more about Hugo's [features], [privacy protections], and [security model].
[Go]: https://go.dev
[Hugo Modules]: /hugo-modules/
[static site generator]: https://en.wikipedia.org/wiki/Static_site_generator
[features]: /about/features
[security model]: /about/security
[privacy protections]: /about/privacy
[features]: /about/features/
[security model]: about/security/
[privacy protections]: /configuration/privacy
{{< youtube 0RKpf3rK57I >}}

View File

@@ -1,18 +1,13 @@
---
title: License
description: Hugo is released under the Apache 2.0 license.
categories: [about]
keywords: [apache]
menu:
docs:
parent: about
weight: 60
weight: 60
categories: []
keywords: []
weight: 40
---
## Apache License
_Version 2.0, January 2004_
_<http://www.apache.org/licenses/>_

View File

@@ -2,71 +2,57 @@
title: Security model
linkTitle: Security
description: A summary of Hugo's security model.
categories: [about]
keywords: [security,privacy]
menu:
docs:
parent: about
weight: 50
weight: 50
toc: true
categories: []
keywords: []
weight: 30
aliases: [/about/security-model/]
---
## Runtime security
Hugo produces static output, so once built, the runtime is the browser (assuming the output is HTML) and any server (API) that you integrate with.
Hugo generates static websites, meaning the final output runs directly in the browser and interacts with any integrated APIs. However, during development and site building, the `hugo` executable itself is the runtime environment.
But when developing and building your site, the runtime is the `hugo` executable. Securing a runtime can be [a real challenge](https://blog.logrocket.com/how-to-protect-your-node-js-applications-from-malicious-dependencies-5f2e60ea08f9/).
Securing a runtime is a complex task. Hugo addresses this through a robust sandboxing approach and a strict security policy with default protections. Key features include:
**Hugo's main approach is that of sandboxing and a security policy with strict defaults:**
- Virtual file system: Hugo employs a virtual file system, limiting file access. Only the main project, not external components, can access files or directories outside the project root.
- Read-Only access: User-defined components have read-only access to the file system, preventing unintended modifications.
- Controlled external binaries: While Hugo utilizes external binaries for features like Asciidoctor support, these are strictly predefined with specific flags and are disabled by default. The [security policy] details these limitations.
- No arbitrary commands: To mitigate risks, Hugo intentionally avoids implementing general functions that would allow users to execute arbitrary operating system commands.
* Hugo has a virtual file system and only the main project (not third-party components) is allowed to mount directories or files outside the project root.
* User-defined components have read-only access to the filesystem.
* We shell out to some external binaries to support [Asciidoctor](/content-management/formats/#formats) and similar, but those binaries and their flags are predefined and disabled by default (see [Security Policy](#security-policy)). General functions to run arbitrary external OS commands have been [discussed](https://github.com/gohugoio/hugo/issues/796), but not implemented because of security concerns.
This combination of sandboxing and strict defaults effectively minimizes potential security vulnerabilities during the Hugo build process.
## Security policy
Hugo has a built-in security policy that restricts access to [os/exec](https://pkg.go.dev/os/exec), remote communication and similar.
The default configuration is listed below. Any build using features not in the allow list of the security policy will fail with a detailed message about what needs to be done. Most of these settings are allow lists (string or slice, [Regular Expressions](https://pkg.go.dev/regexp) or `none` which matches nothing).
{{< code-toggle config=security />}}
By default, Hugo permits the [`resources.GetRemote`] function to download files with media types corresponding to an internal allow list. To add media types to the allow list:
[`resources.GetRemote`]: /functions/resources/getremote
{{< code-toggle file=hugo >}}
[security.http]
mediaTypes = ['^image/avif$']
{{< /code-toggle >}}
Note that these and other configuration settings in Hugo can be overridden by the OS environment. For example, if you want to block all remote HTTP fetching of data:
```txt
HUGO_SECURITY_HTTP_URLS=none hugo
```
[security policy]: /configuration/security/
## Dependency security
Hugo is built as a static binary using [Go Modules](https://github.com/golang/go/wiki/Modules) to manage its dependencies. Go Modules have several safeguards, one of them being the `go.sum` file. This is a database of the expected cryptographic checksums of all of your dependencies, including transitive dependencies.
Hugo utilizes [Go Modules] to manage its dependencies, compiling as a static binary. Go Modules create a `go.sum` file, a critical security feature. This file acts as a database, storing the expected cryptographic checksums of all dependencies, including those required indirectly (transitive dependencies).
[Hugo Modules](/hugo-modules/) is a feature built on top of the functionality of Go Modules. Like Go Modules, a Hugo project using Hugo Modules will have a `go.sum` file. We recommend that you commit this file to your version control system. The Hugo build will fail if there is a checksum mismatch, which would be an indication of [dependency tampering](https://julienrenaux.fr/2019/12/20/github-actions-security-risk/).
[Hugo Modules], which extend Go Modules' functionality, also produce a `go.sum` file. To ensure dependency integrity, commit this `go.sum` file to your version control. If Hugo detects a checksum mismatch during the build process, it will fail, indicating a possible attempt to [tamper with your project's dependencies].
[Go Modules]: https://go.dev/wiki/Modules#modules
[Hugo Modules]: /hugo-modules/
[tamper with your project's dependencies]: https://julienrenaux.fr/2019/12/20/github-actions-security-risk/
## Web application security
These are the security threats as defined by [OWASP](https://en.wikipedia.org/wiki/OWASP).
Hugo's security philosophy is rooted in established security standards, primarily aligning with the threats defined by [OWASP]. For HTML output, Hugo operates under a clear trust model. This model assumes that template and configuration authors, the developers, are trustworthy. However, the data supplied to these templates is inherently considered untrusted. This distinction is crucial for understanding how Hugo handles potential security risks.
For HTML output, this is the core security model:
[OWASP]: https://en.wikipedia.org/wiki/OWASP
<https://pkg.go.dev/html/template#hdr-Security_Model>
To prevent unintended escaping of data that developers know is safe, Hugo provides [`safe`] functions, such as [`safeHTML`]. These functions allow developers to explicitly mark data as trusted, bypassing the default escaping mechanisms. This is essential for scenarios where data is generated or sourced from reliable sources. However, an exception exists: enabling [inline shortcodes]. By activating this feature, you are implicitly trusting the logic within the shortcodes and the data contained within your content files.
In short:
[`safeHTML`]: /functions/safe/html/
[inline shortcodes]: /content-management/shortcodes/#inline
Template and configuration authors (you) are trusted, but the data you send in is not.
This is why you sometimes need to use the _safe_ functions, such as `safeHTML`, to avoid escaping of data you know is safe.
There is one exception to the above, as noted in the documentation: If you enable inline shortcodes, you also say that the shortcodes and data handling in content files are trusted, as those macros are treated as pure text.
It may be worth adding that Hugo is a static site generator with no concept of dynamic user input.
It's vital to remember that Hugo is a static site generator. This architectural choice significantly reduces the attack surface by eliminating the complexities and vulnerabilities associated with dynamic user input. Unlike dynamic websites, Hugo generates static HTML files, minimizing the risk of real-time attacks. Regarding content, Hugo's default Markdown renderer is [configured to sanitize] potentially unsafe content. This default behavior ensures that potentially malicious code or scripts are removed or escaped. However, this setting can be reconfigured if you have a high degree of confidence in the safety of your content sources.
For content, the default Markdown renderer is [configured](/getting-started/configuration-markup) to remove or escape potentially unsafe content. This behavior can be reconfigured if you trust your content.
[configured to sanitize]: /configuration/markup/#rendererunsafe
In essence, Hugo prioritizes secure output by establishing a clear trust boundary between developers and data. By default, it errs on the side of caution, sanitizing potentially unsafe content and escaping data. Developers have the flexibility to adjust these defaults through [`safe`] functions and [configuration options], but they must do so with a clear understanding of the security implications. Hugo's static site generation model further strengthens its security posture by minimizing dynamic vulnerabilities.
[`safe`]: /functions/safe
[configuration options]: /configuration/security
## Configuration
See [configure security](/configuration/security/).

View File

@@ -4,9 +4,5 @@ linkTitle: CLI
description: Use the command line interface (CLI) to manage your site.
categories: []
keywords: []
menu:
docs:
parent: commands
weight: 10
weight: 10
---

View File

@@ -72,6 +72,7 @@ hugo [flags]
* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell
* [hugo config](/commands/hugo_config/) - Display site configuration
* [hugo convert](/commands/hugo_convert/) - Convert front matter to another format
* [hugo deploy](/commands/hugo_deploy/) - Deploy your site to a cloud provider
* [hugo env](/commands/hugo_env/) - Display version and environment info
* [hugo gen](/commands/hugo_gen/) - Generate documentation and syntax highlighting styles
* [hugo import](/commands/hugo_import/) - Import a site from another system

View File

@@ -0,0 +1,7 @@
---
title: Configuration
description: Configure your site.
categories: []
keywords: []
weight: 10
---

View File

@@ -0,0 +1,362 @@
---
title: All settings
description: The complete list of Hugo configuration settings.
categories: []
keywords: []
weight: 20
aliases: [/getting-started/configuration/]
---
## Settings
archetypeDir
: (`string`) The designated directory for [archetypes](g). Default is `archetypes`. {{% module-mounts-note %}}
assetDir
: (`string`) The designated directory for [global resources](g). Default is `assets`. {{% module-mounts-note %}}
baseURL
: (`string`) The absolute URL of your published site including the protocol, host, path, and a trailing slash.
build
: See [configure build](/configuration/build/).
buildDrafts
: (`bool`) Whether to include draft content when building a site. Default is `false`.
buildExpired
: (`bool`) Whether to include expired content when building a site. Default is `false`.
buildFuture
: (`bool`) Whether to include future content when building a site. Default is `false`.
cacheDir
: (`string`) The designated cache directory. See&nbsp;[details](#cache-directory).
caches
: See [configure file caches](/configuration/caches/).
canonifyURLs
: (`bool`) See&nbsp;[details](/content-management/urls/#canonical-urls) before enabling this feature. Default is `false`.
capitalizeListTitles
: {{< new-in 0.123.3 />}}
: (`bool`) Whether to capitalize automatic list titles. Applicable to section, taxonomy, and term pages. Default is `true`. Use the [`titleCaseStyle`](#titlecasestyle) setting to configure capitalization rules.
cascade
: See [configure cascade](/configuration/cascade/).
cleanDestinationDir
: (`bool`) Whether to remove files from the site's destination directory that do not have corresponding files in the `static` directory during the build. Default is `false`.
contentDir
: (`string`) The designated directory for content files. Default is `content`. {{% module-mounts-note %}}
copyright
: (`string`) The copyright notice for a site, typically displayed in the footer.
dataDir
: (`string`) The designated directory for data files. Default is `data`. {{% module-mounts-note %}}
defaultContentLanguage
: (`string`) The project's default language key, conforming to the syntax described in [RFC 5646]. This value must match one of the defined language keys. Default is `en`.
defaultContentLanguageInSubdir
: (`bool`) Whether to publish the default language site to a subdirectory matching the `defaultContentLanguage`. Default is `false`.
defaultOutputFormat
: (`string`) The default output format for the site. If unspecified, the first available format in the defined order (by weight, then alphabetically) will be used.
deployment
: See [configure deployment](/configuration/deployment/).
disableAliases
: (`bool`) Whether to disable generation of alias redirects. Even if this option is enabled, the defined aliases will still be present on the page. This allows you to manage redirects separately, for example, by generating 301 redirects in an `.htaccess` file or a Netlify `_redirects` file using a custom output format. Default is `false`.
disableDefaultLanguageRedirect
: {{< new-in 0.140.0 />}}
: (`bool`) Whether to disable generation of the alias redirect to the default language when `DefaultContentLanguageInSubdir` is `true`. Default is `false`.
disableHugoGeneratorInject
: (`bool`) Whether to disable injection of a `<meta name="generator">` tag into the home page. Default is `false`.
disableKinds
: (`[]string`) A slice of page [kinds](g) to disable during the build process, any of `404`, `home`, `page`, `robotstxt`, `rss`, `section`, `sitemap`, `taxonomy`, or `term`.
disableLanguages
: (`[]string]`) A slice of language keys representing the languages to disable during the build process. Although this is functional, consider using the [`disabled`] key under each language instead.
disableLiveReload
: (`bool`) Whether to disable automatic live reloading of the browser window. Default is `false`.
disablePathToLower
: (`bool`) Whether to disable transformation of page URLs to lower case.
enableEmoji
: (`bool`) Whether to allow emoji in Markdown. Default is `false`.
enableGitInfo
: (`bool`) For sites under Git version control, whether to enable the [`GitInfo`] object for each page. With the [default front matter configuration], the `Lastmod` method on a `Page` object will return the Git author date. Default is `false`.
enableMissingTranslationPlaceholders
: (`bool`) Whether to show a placeholder instead of the default value or an empty string if a translation is missing. Default is `false`.
enableRobotsTXT
: (`bool`) Whether to enable generation of a `robots.txt` file. Default is `false`.
environment
: (`string`) The build environment. Default is `production` when running `hugo` and `development` when running `hugo server`.
frontmatter
: See [configure front matter](/configuration/front-matter/).
hasCJKLanguage
: (`bool`) Whether to automatically detect [CJK](g) languages in content. Affects the values returned by the [`WordCount`] and [`FuzzyWordCount`] methods. Default is `false`.
HTTPCache
: See [configure HTTP cache](/configuration/http-cache/).
i18nDir
: (`string`) The designated directory for translation tables. Default is `i18n`. {{% module-mounts-note %}}
ignoreCache
: (`bool`) Whether to ignore the cache directory. Default is `false`.
ignoreFiles
: (`[]string]`) A slice of [regular expressions](g) used to exclude specific files from a build. These expressions are matched against the absolute file path and apply to files within the `content`, `data`, and `i18n` directories. For more advanced file exclusion options, see the section on [module mounts].
ignoreLogs
: (`[]string`) A slice of message identifiers corresponding to warnings and errors you wish to suppress. See [`erroridf`] and [`warnidf`].
ignoreVendorPaths
: (`string`) A [glob](g) pattern matching the module paths to exclude from the `_vendor` directory.
imaging
: See [configure imaging](/configuration/imaging/).
languageCode
: (`string`) The site's language tag, conforming to the syntax described in [RFC 5646]. This value does not affect translations or localization. Hugo uses this value to populate:
- The `language` element in the [embedded RSS template]
- The `lang` attribute of the `html` element in the [embedded alias template]
- The `og:locale` `meta` element in the [embedded Open Graph template]
When present in the root of the configuration, this value is ignored if one or more language keys exists. Please specify this value independently for each language key.
languages
: See [configure languages](/configuration/languages/).
layoutDir
: (`string`) The designated directory for templates. Default is `layouts`. {{% module-mounts-note %}}
mainSections
: (`string` or `[]string`) The main sections of a site. If set, the [`MainSections`] method on the `Site` object returns the given sections, otherwise it returns the section with the most pages.
markup
: See [configure markup](/configuration/markup/).
mediaTypes
: See [configure media types](/configuration/media-types/).
menus
: See [configure menus](/configuration/menus/).
minify
: See [configure minify](/configuration/minify/).
module
: See [configure modules](/configuration/module/).
newContentEditor
: (`string`) The editor to use when creating new content.
noBuildLock
: (`bool`) Whether to disable creation of the `.hugo_build.lock` file. Default is `false`.
noChmod
: (`bool`) Whether to disable synchronization of file permission modes. Default is `false`.
noTimes
: (`bool`) Whether to disable synchronization of file modification times. Default is `false`.
outputFormats
: See [configure output formats](/configuration/output-formats/).
outputs
: See [configure outputs](/configuration/outputs/).
page
: See [configure page](/configuration/page/).
pagination
: See [configure pagination](/configuration/pagination/).
panicOnWarning
: (`bool`) Whether to panic on the first WARNING. Default is `false`.
params
: See [configure params](/configuration/params/).
permalinks
: See [configure permalinks](/configuration/permalinks/).
pluralizeListTitles
: (`bool`) Whether to pluralize automatic list titles. Applicable to section pages. Default is `true`.
printI18nWarnings
: (`bool`) Whether to log WARNINGs for each missing translation. Default is `false`.
printPathWarnings
: (`bool`) Whether to log WARNINGs when Hugo publishes two or more files to the same path. Default is `false`.
printUnusedTemplates
: (`bool`) Whether to log WARNINGs for each unused template. Default is `false`.
privacy
: See [configure privacy](/configuration/privacy/).
publishDir
: (`string`) The designated directory for publishing the site. Default is `public`.
refLinksErrorLevel
: (`string`) The logging error level to use when the `ref` and `relref` functions, methods, and shortcodes are unable to resolve a reference to a page. Either `ERROR` or `WARNING`. Any `ERROR` will fail the build. Default is `ERROR`.
refLinksNotFoundURL
: (`string`) The URL to return when the `ref` and `relref` functions, methods, and shortcodes are unable to resolve a reference to a page.
related
: See [configure related content](/configuration/related-content/).
relativeURLs
: (`bool`) See&nbsp;[details](/content-management/urls/#relative-urls) before enabling this feature. Default is `false`.
removePathAccents
: (`bool`) Whether to remove [non-spacing marks](https://www.compart.com/en/unicode/category/Mn) from [composite characters](https://en.wikipedia.org/wiki/Precomposed_character) in content paths. Default is `false`.
renderSegments
: {{< new-in 0.124.0 />}}
: (`[]string`) A slice of [segments](g) to render. If omitted, all segments are rendered. This option is typically set via a command-line flag, such as `hugo --renderSegments segment1,segment2`. The provided segment names must correspond to those defined in the [`segments`] configuration.
resourceDir
: (`string`) The designated directory for caching output from [asset pipelines](g). Default is `resources`.
security
: See [configure security](/configuration/security/).
sectionPagesMenu
: (`string`) When set, each top-level section will be added to the menu identified by the provided value. See&nbsp;[details](/content-management/menus/#define-automatically).
segments
: See [configure segments](/configuration/segments/).
server
: See [configure server](/configuration/server/).
services
: See [configure services](/configuration/services/).
sitemap
: See [configure sitemap](/configuration/sitemap/).
staticDir
: (`string`) The designated directory for static files. Default is `static`. {{% module-mounts-note %}}
summaryLength
: (`int`) Applicable to [automatic summaries], the minimum number of words returned by the [`Summary`] method on a `Page` object. The `Summary` method will return content truncated at the paragraph boundary closest to the specified `summaryLength`, but at least this minimum number of words.
taxonomies
: See [configure taxonomies](/configuration/taxonomies/).
templateMetrics
: (`bool`) Whether to print template execution metrics to the console. Default is `false`. See&nbsp;[details](/troubleshooting/performance/#template-metrics).
templateMetricsHints
: (`bool`) Whether to print template execution improvement hints to the console. Applicable when `templateMetrics` is `true`. Default is `false`. See&nbsp;[details](/troubleshooting/performance/#template-metrics).
theme
: (`string` or `[]string`) The [theme](g) to use. Multiple themes can be listed, with precedence given from left to right. See&nbsp;[details](/hugo-modules/theme-components/).
themesDir
: (`string`) The designated directory for themes. Default is `themes`.
timeout
: (`string`) The timeout for generating page content, either as a [duration] or in seconds. This timeout is used to prevent infinite recursion during content generation. You may need to increase this value if your pages take a long time to generate, for example, due to extensive image processing or reliance on remote content. Default is `30s`.
timeZone
: (`string`) The time zone used to parse dates without time zone offsets, including front matter date fields and values passed to the [`time.AsTime`] and [`time.Format`] template functions. The list of valid values may be system dependent, but should include `UTC`, `Local`, and any location in the [IANA Time Zone Database]. For example, `America/Los_Angeles` and `Europe/Oslo` are valid time zones.
title
: (`string`) The site title.
titleCaseStyle
: (`string`) The capitalization rules to follow when Hugo automatically generates a section title, or when using the [`strings.Title`] function. One of `ap`, `chicago`, `go`, `firstupper`, or `none`. Default is `ap`. See&nbsp;[details](#title-case-style).
uglyurls
: See [configure ugly URLs](/configuration/ugly-urls/).
## Cache directory
Hugo's file cache directory is configurable via the [`cacheDir`] configuration option or the `HUGO_CACHEDIR` environment variable. If neither is set, Hugo will use, in order of preference:
1. If running on Netlify: `/opt/build/cache/hugo_cache/`. This means that if you run your builds on Netlify, all caches configured with `:cacheDir` will be saved and restored on the next build. For other [CI/CD](g) vendors, please read their documentation. For an CircleCI example, see [this configuration].
1. In a `hugo_cache` directory below the OS user cache directory as defined by Go's [os.UserCacheDir] function. On Unix systems, per the [XDG base directory specification], this is `$XDG_CACHE_HOME` if non-empty, else `$HOME/.cache`. On MacOS, this is `$HOME/Library/Caches`. On Windows, this is`%LocalAppData%`. On Plan 9, this is `$home/lib/cache`.
1. In a `hugo_cache_$USER` directory below the OS temp dir.
To determine the current `cacheDir`:
```sh
hugo config | grep cachedir
```
## Title case style
Hugo's [`titleCaseStyle`] setting governs capitalization for automatically generated section titles and the [`strings.Title`] function. By default, it follows the capitalization rules published in the Associated Press Stylebook. Change this setting to use other capitalization rules.
ap
: Use the capitalization rules published in the [Associated Press Stylebook]. This is the default.
chicago
: Use the capitalization rules published in the [Chicago Manual of Style].
go
: Capitalize the first letter of every word.
firstupper
: Capitalize the first letter of the first word.
none
: Disable transformation of automatic section titles, and disable the transformation performed by the `strings.Title` function. This is useful if you would prefer to manually capitalize section titles as needed, and to bypass opinionated theme usage of the `strings.Title` function.
## Localized settings
Some configuration settings, such as menus and custom parameters, can be defined separately for each language. See [configure languages](/configuration/languages/#localized-settings).
[`cacheDir`]: #cachedir
[`disabled`]: /configuration/languages/#disabled
[`erroridf`]: /functions/fmt/erroridf/
[`FuzzyWordCount`]: /methods/page/fuzzywordcount/
[`GitInfo`]: /methods/page/gitinfo/
[`MainSections`]: /methods/site/mainsections/
[`segments`]: /configuration/segments/
[`strings.Title`]: /functions/strings/title/
[`strings.Title`]: /functions/strings/title
[`Summary`]: /methods/page/summary/
[`time.AsTime`]: /functions/time/astime/
[`time.Format`]: /functions/time/format/
[`titleCaseStyle`]: #titlecasestyle
[`warnidf`]: /functions/fmt/warnidf/
[`WordCount`]: /methods/page/wordcount/
[Associated Press Stylebook]: https://www.apstylebook.com/
[automatic summaries]: /content-management/summaries/#automatic-summary
[Chicago Manual of Style]: https://www.chicagomanualofstyle.org/home.html
[default front matter configuration]: /configuration/front-matter/
[duration]: https://pkg.go.dev/time#Duration
[embedded alias template]: {{% eturl alias %}}
[embedded Open Graph template]: {{% eturl opengraph %}}
[embedded RSS template]: {{% eturl rss %}}
[IANA Time Zone Database]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
[module mounts]: /configuration/module/#mounts
[os.UserCacheDir]: https://pkg.go.dev/os#UserCacheDir
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
[this configuration]: https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml
[XDG base directory specification]: https://specifications.freedesktop.org/basedir-spec/latest/

View File

@@ -0,0 +1,81 @@
---
title: Configure build
linkTitle: Build
description: Configure global build options.
categories: []
keywords: []
aliases: [/getting-started/configuration-build/]
---
The `build` configuration section contains global build-related configuration options.
{{< code-toggle config=build />}}
buildStats
: See the [build stats](#build-stats) section below.
cachebusters
: See the [cache busters](#cache-busters) section below.
noJSConfigInAssets
: (`bool`) Whether to disable writing a `jsconfig.json` in your `assets` directory with mapping of imports from running [js.Build](/hugo-pipes/js). This file is intended to help with intellisense/navigation inside code editors such as [VS Code](https://code.visualstudio.com/). Note that if you do not use `js.Build`, no file will be written.
useResourceCacheWhen
: (`string`) When to use the resource file cache, one of `never`, `fallback`, or `always`. Applicable when transpiling Sass to CSS. Default is `fallback`.
## Cache busters
The `build.cachebusters` configuration option was added to support development using Tailwind 3.x's JIT compiler where a `build` configuration may look like this:
{{< code-toggle file=hugo >}}
[build]
[build.buildStats]
enable = true
[[build.cachebusters]]
source = "assets/watching/hugo_stats\\.json"
target = "styles\\.css"
[[build.cachebusters]]
source = "(postcss|tailwind)\\.config\\.js"
target = "css"
[[build.cachebusters]]
source = "assets/.*\\.(js|ts|jsx|tsx)"
target = "js"
[[build.cachebusters]]
source = "assets/.*\\.(.*)$"
target = "$1"
{{< /code-toggle >}}
When `buildStats` is enabled, Hugo writes a `hugo_stats.json` file on each build with HTML classes etc. that's used in the rendered output. Changes to this file will trigger a rebuild of the `styles.css` file. You also need to add `hugo_stats.json` to Hugo's server watcher. See [Hugo Starter Tailwind Basic](https://github.com/bep/hugo-starter-tailwind-basic) for a running example.
source
: (`string`) A [regular expression](g) matching file(s) relative to one of the virtual component directories in Hugo, typically `assets/...`.
target
: (`string`) A [regular expression](g) matching the keys in the resource cache that should be expired when `source` changes. You can use the matching regexp groups from `source` in the expression, e.g. `$1`.
## Build stats
{{< code-toggle config=build.buildStats />}}
enable
: (`bool`) Whether to create a `hugo_stats.json` file in the root of your project. This file contains arrays of the `class` attributes, `id` attributes, and tags of every HTML element within your published site. Use this file as data source when [removing unused CSS] from your site. This process is also known as pruning, purging, or tree shaking. Default is `false`.
[removing unused CSS]: /functions/resources/postprocess/
disableIDs
: (`bool`) Whether to exclude `id` attributes. Default is `false`.
disableTags
: (`bool`) Whether to exclude element tags. Default is `false`.
disableClasses
: (`bool`) Whether to exclude `class` attributes. Default is `false`.
> [!note]
> Given that CSS purging is typically limited to production builds, place the `buildStats` object below [`config/production`].
>
> Built for speed, there may be "false positive" detections (e.g., HTML elements that are not HTML elements) while parsing the published site. These "false positives" are infrequent and inconsequential.
Due to the nature of partial server builds, new HTML entities are added while the server is running, but old values will not be removed until you restart the server or run a regular `hugo` build.
[`config/production`]: /configuration/introduction/#configuration-directory

View File

@@ -0,0 +1,30 @@
---
title: Configure file caches
linkTitle: Caches
description: Configure file caches.
categories: []
keywords: []
---
This is the default configuration:
{{< code-toggle config=caches />}}
## Keys
dir
: (`string`) The absolute file system path where the cached files will be stored. You can begin the path with the `:cacheDir` or `:resourceDir` token. These tokens will be replaced with the actual configured cache directory and resource directory paths, respectively.
maxAge
: (`string`) The [duration](g) a cached entry remains valid before being evicted. A value of `0` disables the cache. A value of `-1` means the cache entry never expires (the default).
## Tokens
`:cacheDir`
: (`string`) The designated cache directory. See&nbsp;[details](/configuration/all/#cachedir).
`:project`
: (`string`) The base directory name of the current Hugo project. By default, this ensures each project has isolated file caches, so running `hugo --gc` will only affect the current project's cache and not those of other Hugo projects on the same machine.
`:resourceDir`
: (`string`) The designated directory for caching output from [asset pipelines](g). See&nbsp;[details](/configuration/all/#resourcedir).

View File

@@ -0,0 +1,77 @@
---
title: Configure cascade
linkTitle: Cascade
description: Configure cascade.
categories: []
keywords: []
---
You can configure your site to cascade front matter values to the home page and any of its descendants. However, this cascading will be prevented if the descendant already defines the field, or if a closer ancestor [node](g) has already cascaded a value for the same field through its front matter's `cascade` key.
> [!note]
> You can also configure cascading behavior within a page's front matter. See&nbsp;[details].
For example, to cascade a "color" parameter to the home page and all its descendants:
{{< code-toggle file=hugo >}}
title = 'Home'
[cascade.params]
color = 'red'
{{< /code-toggle >}}
## Target
<!-- TODO
Update the <version> and <date> below when we actually get around to deprecating _target.
We deprecated the `_target` front matter key in favor of `target` in <version> on <date>. Remove footnote #1 on or after 2026-03-10 (15 months after deprecation).
-->
The `target`[^1] keyword allows you to target specific pages or [environments](g). For example, to cascade a "color" parameter to pages within the "articles" section, including the "articles" section page itself:
[^1]: The `_target` alias for `target` is deprecated and will be removed in a future release.
{{< code-toggle file=hugo >}}
[cascade.params]
color = 'red'
[cascade.target]
path = '{/articles,/articles/**}'
{{< /code-toggle >}}
Use any combination of these keywords to target pages and/or environments:
environment
: (`string`) A [glob](g) pattern matching the build [environment](g). For example: `{staging,production}`.
kind
: (`string`) A [glob](g) pattern matching the [page kind](g). For example: ` {taxonomy,term}`.
lang
: (`string`) A [glob](g) pattern matching the [page language]. For example: `{en,de}`.
path
: (`string`) A [glob](g) pattern matching the page's [logical path](g). For example: `{/books,/books/**}`.
## Array
Define an array of cascade parameters to apply different values to different targets. For example:
{{< code-toggle file=hugo >}}
[[cascade]]
[cascade.params]
color = 'red'
[cascade.target]
path = '{/books/**}'
kind = 'page'
lang = '{en,de}'
[[cascade]]
[cascade.params]
color = 'blue'
[cascade.target]
path = '{/films/**}'
kind = 'page'
environment = 'production'
{{< /code-toggle >}}
[details]: /content-management/front-matter/#cascade-1
[page language]: /methods/page/language/

View File

@@ -0,0 +1,63 @@
---
title: Configure content types
linkTitle: Content types
description: Configure content types.
categories: []
keywords: []
---
{{< new-in 0.144.0 />}}
Hugo supports six [content formats](g):
{{% include "/_common/content-format-table.md" %}}
These can be used as either page content or [page resources](g). When used as page resources, their [resource type](g) is `page`.
Consider this example of a [page bundle](g):
```text
content/
└── example/
├── index.md <-- content
├── a.adoc <-- resource (resource type: page)
├── b.html <-- resource (resource type: page)
├── c.md <-- resource (resource type: page)
├── d.org <-- resource (resource type: page)
├── e.pdc <-- resource (resource type: page)
├── f.rst <-- resource (resource type: page)
├── g.jpg <-- resource (resource type: image)
└── h.png <-- resource (resource type: image)
```
The `index.md` file is the page's content, while the other files are page resources. Files `a` through `f` are of resource type `page`, while `g` and `h` are of resource type `image`.
When you build a site, Hugo does not publish page resources having a resource type of `page`. For example, this is the result of building the site above:
```text
public/
├── example/
│ ├── g.jpg
│ ├── h.png
│ └── index.html
└── index.html
```
The default behavior is appropriate in most cases. Given that page resources containing markup are typically intended for inclusion in the main content, publishing them independently is generally undesirable.
The default behavior is determined by the `contentTypes` configuration:
{{< code-toggle config=contentTypes />}}
In this default configuration, page resources with those media types will have a resource type of `page`, and will not be automatically published. To change the resource type assignment from `page` to `text` for a given media type, remove the corresponding entry from the list.
For example, to set the resource type of `text/html` files to `text`, thereby enabling automatic publication, remove the `text/html` entry:
{{< code-toggle file=hugo >}}
contentTypes:
text/asciidoc: {}
text/markdown: {}
text/org: {}
text/pandoc: {}
text/rst: {}
{{< /code-toggle >}}

View File

@@ -0,0 +1,159 @@
---
title: Configure deployment
linkTitle: Deployment
description: Configure deployments to Amazon S3, Azure Blob Storage, or Google Cloud Storage.
categories: []
keywords: []
---
> [!note]
> This configuration is only relevant when running `hugo deploy`. See&nbsp;[details](/host-and-deploy/deploy-with-hugo-deploy/).
## Top-level options
These settings control the overall behavior of the deployment process. This is the default configuration:
{{< code-toggle file=hugo config=deployment />}}
confirm
: (`bool`) Whether to prompt for confirmation before deploying. Default is `false`.
dryRun
: (`bool`) Whether to simulate the deployment without any remote changes. Default is `false`.
force
: (`bool`) Whether to re-upload all files. Default is `false`.
invalidateCDN
: (`bool`) Whether to invalidate the CDN cache listed in the deployment target. Default is `true`.
maxDeletes
: (`int`) The maximum number of files to delete, or `-1` to disable. Default is `256`.
matchers
: (`[]*Matcher`) A slice of [matchers](#matchers-1).
order
: (`[]string`) An ordered slice of [regular expressions](g) that determines upload priority (left to right). Files not matching any expression are uploaded last in an arbitrary order.
target
: (`string`) The target deployment [`name`](#name). Defaults to the first target.
targets
: (`[]*Target`) A slice of [targets](#targets-1).
workers
: (`int`) The number of concurrent workers to use when uploading files. Default is `10`.
## Targets
A target represents a deployment target such as "staging" or "production".
cloudFrontDistributionID
: (`string`) The CloudFront Distribution ID, applicable if you are using the Amazon Web Services CloudFront CDN. Hugo will invalidate the CDN when deploying this target.
exclude
: (`string`) A [glob](g) pattern matching files to exclude when deploying to this target. Local files failing the include/exclude filters are not uploaded, and remote files failing these filters are not deleted.
googleCloudCDNOrigin
: (`string`) The Google Cloud project and CDN origin to invalidate when deploying this target, specified as `<project>/<origin>`.
include
: (`string`) A [glob](g) pattern matching files to include when deploying to this target. Local files failing the include/exclude filters are not uploaded, and remote files failing these filters are not deleted.
name
: (`string`) An arbitrary name for this target.
stripIndexHTML
: (`bool`) Whether to map files named `<dir>/index.html` to `<dir>` on the remote (except for the root `index.html`). This is useful for key-value cloud storage (e.g., Amazon S3, Google Cloud Storage, Azure Blob Storage) to align canonical URLs with object keys. Default is `false`.
url
: (`string`) The [destination URL](#destination-urls) for deployment.
## Matchers
A Matcher represents a configuration to be applied to files whose paths match
the specified pattern.
cacheControl
: (`string`) The caching attributes to use when serving the blob. See&nbsp;[details][cacheControl].
contentEncoding
: (`string`) The encoding used for the blob's content, if any. See&nbsp;[details][contentEncoding].
contentType
: (`string`) The media type of the blob being written. See&nbsp;[details][contentType].
force
: (`bool`) Whether matching files should be re-uploaded. Useful when other route-determined metadata (e.g., `contentType`) has changed. Default is `false`.
gzip
: (`bool`) Whether the file should be gzipped before upload. If so, the `ContentEncoding` field will automatically be set to `gzip`. Default is `false`.
pattern
: (`string`) A [regular expression](g) used to match paths. Paths are converted to use forward slashes (`/`) before matching.
[cacheControl]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
[contentEncoding]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
[contentType]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
## Destination URLs
Service|URL example
:--|:--
Amazon Simple Storage Service (S3)|`s3://my-bucket?region=us-west-1`
Azure Blob Storage|`azblob://my-container`
Google Cloud Storage (GCS)|`gs://my-bucket`
With Google Cloud Storage you can target a subdirectory:
```text
gs://my-bucket?prefix=a/subdirectory
```
You can also to deploy to storage servers compatible with Amazon S3 such as:
- [Ceph]
- [MinIO]
- [SeaweedFS]
[Ceph]: https://ceph.com/
[Minio]: https://www.minio.io/
[SeaweedFS]: https://github.com/chrislusf/seaweedfs
For example, the `url` for a MinIO deployment target might resemble this:
```text
s3://my-bucket?endpoint=https://my.minio.instance&awssdk=v2&use_path_style=true&disable_https=false
```
## Example
{{< code-toggle file=hugo >}}
[deployment]
order = ['.jpg$', '.gif$']
[[deployment.matchers]]
cacheControl = 'max-age=31536000, no-transform, public'
gzip = true
pattern = '^.+\.(js|css|svg|ttf)$'
[[deployment.matchers]]
cacheControl = 'max-age=31536000, no-transform, public'
gzip = false
pattern = '^.+\.(png|jpg)$'
[[deployment.matchers]]
contentType = 'application/xml'
gzip = true
pattern = '^sitemap\.xml$'
[[deployment.matchers]]
gzip = true
pattern = '^.+\.(html|xml|json)$'
[[deployment.targets]]
url = 's3://my_production_bucket?region=us-west-1'
cloudFrontDistributionID = 'E1234567890ABCDEF0'
exclude = '**.{heic,psd}'
name = 'production'
[[deployment.targets]]
url = 's3://my_staging_bucket?region=us-west-1'
exclude = '**.{heic,psd}'
name = 'staging'
{{< /code-toggle >}}

View File

@@ -0,0 +1,91 @@
---
title: Configure front matter
linkTitle: Front matter
description: Configure front matter.
categories: []
keywords: []
---
## Dates
There are four methods on a `Page` object that return a date.
Method|Description
:--|:--
[`Date`]|Returns the date of the given page.
[`ExpiryDate`]|Returns the expiry date of the given page.
[`Lastmod`]|Returns the last modification date of the given page.
[`PublishDate`]|Returns the publish date of the given page.
[`Date`]: /methods/page/date
[`ExpiryDate`]: /methods/page/expirydate
[`Lastmod`]: /methods/page/lastmod
[`PublishDate`]: /methods/page/publishdate
Hugo determines the values to return based on this configuration:
{{< code-toggle config=frontmatter />}}
The `ExpiryDate` method, for example, returns the `expirydate` value if it exists, otherwise it returns `unpublishdate`.
You can also use custom date parameters:
{{< code-toggle file=hugo >}}
[frontmatter]
date = ["myDate", "date"]
{{< /code-toggle >}}
In the example above, the `Date` method returns the `myDate` value if it exists, otherwise it returns `date`.
To fall back to the default sequence of dates, use the `:default` token:
{{< code-toggle file=hugo >}}
[frontmatter]
date = ["myDate", ":default"]
{{< /code-toggle >}}
In the example above, the `Date` method returns the `myDate` value if it exists, otherwise it returns the first valid date from `date`, `publishdate`, `pubdate`, `published`, `lastmod`, and `modified`.
## Aliases
Some of the front matter fields have aliases.
Front matter field|Aliases
:--|:--
`expiryDate`|`unpublishdate`
`lastmod`|`modified`
`publishDate`|`pubdate`, `published`
The default front matter configuration includes these aliases.
## Tokens
Hugo provides several [tokens](g) to assist with front matter configuration.
Token|Description
:--|:--
`:default`|The default ordered sequence of date fields.
`:fileModTime`|The file's last modification timestamp.
`:filename`|The date from the file name, if present.
`:git`|The Git author date for the file's last revision.
When Hugo extracts a date from a file name, it uses the rest of the file name to generate the page's [`slug`], but only if a slug isn't already specified in the page's front matter. For example, given the name `2025-02-01-article.md`, Hugo will set the `date` to `2025-02-01` and the `slug` to `article`.
[`slug`]: /content-management/front-matter/#slug
To enable access to the Git author date, set [`enableGitInfo`] to `true`, or use\
the `--enableGitInfo` flag when building your site.
[`enableGitInfo`]: /configuration/all/#enablegitinfo
Consider this example:
{{< code-toggle file=hugo >}}
[frontmatter]
date = [':filename', ':default']
lastmod = ['lastmod', ':fileModTime']
{{< /code-toggle >}}
To determine `date`, Hugo tries to extract the date from the file name, falling back to the default ordered sequence of date fields.
To determine `lastmod`, Hugo looks for a `lastmod` field in front matter, falling back to the file's last modification timestamp.

View File

@@ -0,0 +1,107 @@
---
title: Configure the HTTP cache
linkTitle: HTTP cache
description: Configure the HTTP cache.
categories: []
keywords: []
---
> [!note]
> This configuration is only relevant when using the [`resources.GetRemote`] function.
## Layered caching
Hugo employs a layered caching system.
```goat {.w-40}
.-----------.
| dynacache |
'-----+-----'
|
v
.----------.
| HTTP cache |
'-----+----'
|
v
.----------.
| file cache |
'-----+----'
```
Dynacache
: An in-memory cache employing a Least Recently Used (LRU) eviction policy. Entries are removed from the cache when changes occur, when they match [cache-busting] patterns, or under low-memory conditions.
HTTP Cache
: An HTTP cache for remote resources as specified in [RFC 9111]. Optimal performance is achieved when resources include appropriate HTTP cache headers. The HTTP cache utilizes the file cache for storage and retrieval of cached resources.
File cache
: See [configure file caches].
The HTTP cache involves two key aspects: determining which content to cache (the caching process itself) and defining the frequency with which to check for updates (the polling strategy).
## HTTP caching
The HTTP cache behavior is defined for a configured set of resources. Stale resources will be refreshed from the file cache, even if their configured Time-To-Live (TTL) has not expired. If HTTP caching is disabled for a resource, Hugo will bypass the cache and access the file directly.
The default configuration disables everything:
{{< code-toggle file=hugo >}}
[HTTPCache.cache.for]
excludes = ['**']
includes = []
{{< /code-toggle >}}
cache.for.excludes
: (`string`) A list of [glob](g) patterns to exclude from caching.
cache.for.includes
: (`string`) A list of [glob](g) patterns to cache.
## HTTP polling
Polling is used in watch mode (e.g., `hugo server`) to detect changes in remote resources. Polling can be enabled even if HTTP caching is disabled. Detected changes trigger a rebuild of pages using the affected resource. Polling can be disabled for specific resources, typically those known to be static.
The default configuration disables everything:
{{< code-toggle file=hugo >}}
[[HTTPCache.polls]]
disable = true
high = '0s'
low = '0s'
[HTTPCache.polls.for]
includes = ['**']
excludes = []
{{< /code-toggle >}}
polls
: A slice of polling configurations.
polls.disable
: (`bool`) Whether to disable polling for this configuration.
polls.low
: (`string`) The minimum polling interval expressed as a [duration](g). This is used after a recent change and gradually increases towards `polls.high`.
polls.high
: (`string`) The maximum polling interval expressed as a [duration](g). This is used when the resource is considered stable.
polls.for.excludes
: (`string`) A list of [glob](g) patterns to exclude from polling for this configuration.
polls.for.includes
: (`string`) A list of [glob](g) patterns to include in polling for this configuration.
## Behavior
Polling and HTTP caching interact as follows:
- With polling enabled, rebuilds are triggered only by actual changes, detected via `eTag` changes (Hugo generates an MD5 hash if the server doesn't provide one).
- If polling is enabled but HTTP caching is disabled, the remote is checked for changes only after the file cache's TTL expires (e.g., a `maxAge` of `10h` with a `1s` polling interval is inefficient).
- If both polling and HTTP caching are enabled, changes are checked for even before the file cache's TTL expires. Cached `eTag` and `last-modified` values are sent in `if-none-match` and `if-modified-since` headers, respectively, and a cached response is returned on HTTP [304].
[`resources.GetRemote`]: /functions/resources/getremote/
[304]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
[cache-busting]: /configuration/build/#cache-busters
[configure file caches]: /configuration/caches/
[RFC 9111]: https://datatracker.ietf.org/doc/html/rfc9111

View File

@@ -0,0 +1,69 @@
---
title: Configure imaging
linkTitle: Imaging
description: Configure imaging.
categories: []
keywords: []
---
## Processing options
These are the default settings for processing images:
{{< code-toggle file=hugo >}}
[imaging]
anchor = 'Smart'
bgColor = '#ffffff'
hint = 'photo'
quality = 75
resampleFilter = 'box'
{{< /code-toggle >}}
anchor
: (`string`) When using the [`Crop`] or [`Fill`] method, the anchor determines the placement of the crop box. One of `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. Default is `Smart`.
bgColor
: (`string`) The background color of the resulting image. Applicable when converting from a format that supports transparency to a format that does not support transparency, for example, when converting from PNG to JPEG. Expressed as an RGB [hexadecimal] value. Default is `#ffffff`.
[hexadecimal]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
hint
: (`string`) Applicable to WebP images, this option corresponds to a set of predefined encoding parameters. One of `drawing`, `icon`, `photo`, `picture`, or `text`. Default is `photo`. See&nbsp;[details](/content-management/image-processing/#hint).
quality
: (`int`) Applicable to JPEG and WebP images, this value determines the quality of the converted image. Higher values produce better quality images, while lower values produce smaller files. Set this value to a whole number between `1` and `100`, inclusive. Default is `75`.
resampleFilter
: (`string`) The resampling filter used when resizing an image. Default is `box`. See&nbsp;[details](/content-management/image-processing/#resampling-filter)
## EXIF data
These are the default settings for extracting EXIF data from images:
{{< code-toggle file=hugo >}}
[imaging.exif]
includeFields = ""
excludeFields = ""
disableDate = false
disableLatLong = false
{{< /code-toggle >}}
disableDate
: (`bool`) Whether to disable extraction of the image creation date/time. Default is `false`.
disableLatLong
: (`bool`) Whether to disable extraction of the GPS latitude and longitude. Default is `false`.
excludeFields
: (`string`) A [regular expression](g) matching the tags to exclude when extracting EXIF data.
includeFields
: (`string`) A [regular expression](g) matching the tags to include when extracting EXIF data. To include all available tags, set this value to&nbsp;`".*"`.
> [!note]
> To improve performance and decrease cache size, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`.
>
> To control tag availability, change the `excludeFields` or `includeFields` settings as described above.
[`Crop`]: /methods/resource/crop/
[`Fill`]: /methods/resource/fill/

View File

@@ -0,0 +1,284 @@
---
title: Introduction
description: Configure your site using files, directories, and environment variables.
categories: []
keywords: []
weight: 10
---
## Sensible defaults
Hugo offers many configuration options, but its defaults are often sufficient. A new site requires only these settings:
{{< code-toggle file=hugo >}}
baseURL = 'https://example.org/'
languageCode = 'en-us'
title = 'My New Hugo Site'
{{< /code-toggle >}}
Only define settings that deviate from the defaults. A smaller configuration file is easier to read, understand, and debug. Keep your configuration concise.
> [!note]
> The best configuration file is a short configuration file.
## Configuration file
Create a site configuration file in the root of your project directory, naming it `hugo.toml`, `hugo.yaml`, or `hugo.json`, with that order of precedence.
```text
my-project/
└── hugo.toml
```
> [!note]
> For versions v0.109.0 and earlier, the site configuration file was named `config`. While you can still use this name, it's recommended to switch to the newer naming convention, `hugo`.
A simple example:
{{< code-toggle file=hugo >}}
baseURL = 'https://example.org/'
languageCode = 'en-us'
title = 'ABC Widgets, Inc.'
[params]
subtitle = 'The Best Widgets on Earth'
[params.contact]
email = 'info@example.org'
phone = '+1 202-555-1212'
{{< /code-toggle >}}
To use a different configuration file when building your site, use the `--config` flag:
```sh
hugo --config other.toml
```
Combine two or more configuration files, with left-to-right precedence:
```sh
hugo --config a.toml,b.yaml,c.json
```
> [!note]
> See the specifications for each file format: [TOML], [YAML], and [JSON].
## Configuration directory
Instead of a single site configuration file, split your configuration by [environment](g), root configuration key, and language. For example:
```text
my-project/
└── config/
├── _default/
│ ├── hugo.toml
│ ├── menus.en.toml
│ ├── menus.de.toml
│ └── params.toml
└── production/
└── params.toml
```
The root configuration keys are {{< root-configuration-keys >}}.
### Omit the root key
When splitting the configuration by root key, omit the root key in the component file. For example, these are equivalent:
{{< code-toggle file=config/_default/hugo >}}
[params]
foo = 'bar'
{{< /code-toggle >}}
{{< code-toggle file=config/_default/params >}}
foo = 'bar'
{{< /code-toggle >}}
### Recursive parsing
Hugo parses the `config` directory recursively, allowing you to organize the files into subdirectories. For example:
```text
my-project/
└── config/
└── _default/
├── navigation/
│ ├── menus.de.toml
│ └── menus.en.toml
└── hugo.toml
```
### Example
```text
my-project/
└── config/
├── _default/
│ ├── hugo.toml
│ ├── menus.en.toml
│ ├── menus.de.toml
│ └── params.toml
├── production/
│ ├── hugo.toml
│ └── params.toml
└── staging/
├── hugo.toml
└── params.toml
```
Considering the structure above, when running `hugo --environment staging`, Hugo will use every setting from `config/_default` and merge `staging`'s on top of those.
Let's take an example to understand this better. Let's say you are using Google Analytics for your website. This requires you to specify a [Google tag ID] in your site configuration:
{{< code-toggle file=hugo >}}
[services.googleAnalytics]
ID = 'G-XXXXXXXXX'
{{< /code-toggle >}}
Now consider the following scenario:
1. You don't want to load the analytics code when running `hugo server`.
1. You want to use different Google tag IDs for your production and staging environments. For example:
- `G-PPPPPPPPP` for production
- `G-SSSSSSSSS` for staging
To satisfy these requirements, configure your site as follows:
1. `config/_default/hugo.toml`
- Exclude the `services.googleAnalytics` section. This will prevent loading of the analytics code when you run `hugo server`.
- By default, Hugo sets its `environment` to `development` when running `hugo server`. In the absence of a `config/development` directory, Hugo uses the `config/_default` directory.
1. `config/production/hugo.toml`
- Include this section only:
{{< code-toggle file=hugo >}}
[services.googleAnalytics]
ID = 'G-PPPPPPPPP'
{{< /code-toggle >}}
- You do not need to include other parameters in this file. Include only those parameters that are specific to your production environment. Hugo will merge these parameters with the default configuration.
- By default, Hugo sets its `environment` to `production` when running `hugo`. The analytics code will use the `G-PPPPPPPPP` tag ID.
1. `config/staging/hugo.toml`
- Include this section only:
{{< code-toggle file=hugo >}}
[services.googleAnalytics]
ID = 'G-SSSSSSSSS'
{{< /code-toggle >}}
- You do not need to include other parameters in this file. Include only those parameters that are specific to your staging environment. Hugo will merge these parameters with the default configuration.
- To build your staging site, run `hugo --environment staging`. The analytics code will use the `G-SSSSSSSSS` tag ID.
## Merge configuration settings
Hugo merges configuration settings from themes and modules, prioritizing the project's own settings. Given this simplified project structure with two themes:
```text
project/
├── themes/
│ ├── theme-a/
│ │ └── hugo.toml
│ └── theme-b/
│ └── hugo.toml
└── hugo.toml
```
and this project-level configuration:
{{< code-toggle file=hugo >}}
baseURL = 'https://example.org/'
languageCode = 'en-us'
title = 'My New Hugo Site'
theme = ['theme-a','theme-b']
{{< /code-toggle >}}
Hugo merges settings in this order:
1. Project configuration (`hugo.toml` in the project root)
1. `theme-a` configuration
1. `theme-b` configuration
The `_merge` setting within each top-level configuration key controls _which_ settings are merged and _how_ they are merged.
The value for `_merge` can be one of:
none
: No merge.
shallow
: Only add values for new keys.
deep
: Add values for new keys, merge existing.
Note that you don't need to be so verbose as in the default setup below; a `_merge` value higher up will be inherited if not set.
{{< code-toggle file=hugo dataKey="config_helpers.mergeStrategy" skipHeader=true />}}
## Environment variables
You can also configure settings using operating system environment variables:
```sh
export HUGO_BASEURL=https://example.org/
export HUGO_ENABLEGITINFO=true
export HUGO_ENVIRONMENT=staging
hugo
```
The above sets the [`baseURL`], [`enableGitInfo`], and [`environment`] configuration options and then builds your site.
> [!note]
> An environment variable takes precedence over the values set in the configuration file. This means that if you set a configuration value with both an environment variable and in the configuration file, the value in the environment variable will be used.
Environment variables simplify configuration for [CI/CD](g) deployments like GitHub Pages, GitLab Pages, and Netlify by allowing you to set values directly within their respective configuration and workflow files.
> [!note]
> Environment variable names must be prefixed with `HUGO_`.
>
> To set custom site parameters, prefix the name with `HUGO_PARAMS_`.
For snake_case variable names, the standard `HUGO_` prefix won't work. Hugo infers the delimiter from the first character following `HUGO`. This allows for variations like `HUGOxPARAMSxAPI_KEY=abcdefgh` using any [permitted delimiter].
In addition to configuring standard settings, environment variables may be used to override default values for certain internal settings:
DART_SASS_BINARY
: (`string`) The absolute path to the Dart Sass executable. By default, Hugo searches for the executable in each of the paths in the `PATH` environment variable.
HUGO_FILE_LOG_FORMAT
: (`string`) A format string for the file path, line number, and column number displayed when reporting errors, or when calling the `Position` method from a shortcode or Markdown render hook. Valid tokens are `:file`, `:line`, and `:col`. Default is `:file::line::col`.
HUGO_MEMORYLIMIT
: {{< new-in 0.123.0 />}}
: (`int`) The maximum amount of system memory, in gigabytes, that Hugo can use while rendering your site. Default is 25% of total system memory. Note that The `HUGO_MEMORYLIMIT` is a “best effort” setting. Don't expect Hugo to build a million pages with only 1 GB memory. You can get more information about how this behaves during the build by building with `hugo --logLevel info` and look for the `dynacache` label.
HUGO_NUMWORKERMULTIPLIER
: (`int`) The number of workers used in parallel processing. Default is the number of logical CPUs.
## Current configuration
Display the complete site configuration with:
```sh
hugo config
```
Display a specific configuration setting with:
```sh
hugo config | grep [key]
```
Display the configured file mounts with:
```sh
hugo config mounts
```
[`baseURL`]: /configuration/all#baseurl
[`enableGitInfo`]: /configuration/all#enablegitinfo
[`environment`]: /configuration/all#environment
[Google tag ID]: https://support.google.com/tagmanager/answer/12326985?hl=en
[JSON]: https://datatracker.ietf.org/doc/html/rfc7159
[permitted delimiter]: https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html
[TOML]: https://toml.io/en/latest
[YAML]: https://yaml.org/spec/

View File

@@ -0,0 +1,193 @@
---
title: Configure languages
linkTitle: Languages
description: Configure the languages in your multilingual site.
categories: []
keywords: []
---
## Base settings
Configure the following base settings within the site's root configuration:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = false
disableDefaultLanguageRedirect = false
disableLanguages = []
{{< /code-toggle >}}
defaultContentLanguage
: (`string`) The project's default language key, conforming to the syntax described in [RFC 5646]. This value must match one of the defined [language keys](#language-keys). Default is `en`.
defaultContentLanguageInSubdir
: (`bool`) Whether to publish the default language site to a subdirectory matching the `defaultContentLanguage`. Default is `false`.
disableDefaultLanguageRedirect
: {{< new-in 0.140.0 />}}
: (`bool`) Whether to disable generation of the alias redirect to the default language when `DefaultContentLanguageInSubdir` is `true`. Default is `false`.
disableLanguages
: (`[]string]`) A slice of language keys representing the languages to disable during the build process. Although this is functional, consider using the [`disabled`](#disabled) key under each language instead.
## Language settings
Configure each language under the `languages` key:
{{< code-toggle config=languages />}}
In the above, `en` is the [language key](#language-keys).
disabled
: (`bool`) Whether to disable this language when building the site. Default is `false`.
languageCode
: (`string`) The language tag as described in [RFC 5646]. This value does not affect localization or URLs. Hugo uses this value to populate:
- The `lang` attribute of the `html` element in the [embedded alias template]
- The `language` element in the [embedded RSS template]
- The `locale` property in the [embedded OpenGraph template]
Access this value from a template using the [`Language.LanguageCode`] method on a `Site` or `Page` object.
languageDirection
: (`string`) The language direction, either left-to-right (`ltr`) or right-to-left (`rtl`). Use this value in your templates with the global [`dir`] HTML attribute. Access this value from a template using the [`Language.LanguageDirection`] method on a `Site` or `Page` object.
languageName
: (`string`) The language name, typically used when rendering a language switcher. Access this value from a template using the [`Language.LanguageName`] method on a `Site` or `Page` object.
title
: (`string`) The site title for this language. Access this value from a template using the [`Title`] method on a `Site` object.
weight
: (`int`) The language [weight](g). When set to a non-zero value, this is the primary sort criteria for this language. Access this value from a template using the [`Language.Weight`] method on a `Site` or `Page` object.
## Localized settings
Some configuration settings can be defined separately for each language. For example:
{{< code-toggle file=hugo >}}
[languages.en]
languageCode = 'en-US'
languageName = 'English'
weight = 1
title = 'Project Documentation'
timeZone = 'America/New_York'
[languages.en.pagination]
path = 'page'
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
{{< /code-toggle >}}
The following configuration keys can be defined separately for each language:
{{< per-lang-config-keys >}}
Any key not defined in a `languages` object will fall back to the global value in the root of the site configuration.
## Language keys
Language keys must conform to the syntax described in [RFC 5646]. For example:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'de'
[languages.de]
weight = 1
[languages.en-US]
weight = 2
[languages.pt-BR]
weight = 3
{{< /code-toggle >}}
Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7] are also supported. Omit the `art-x-` prefix from the language key. For example:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'en'
[languages.en]
weight = 1
[languages.hugolang]
weight = 2
{{< /code-toggle >}}
> [!note]
> Private use subtags must not exceed 8 alphanumeric characters.
## Example
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true
disableDefaultLanguageRedirect = false
[languages.de]
contentDir = 'content/de'
disabled = false
languageCode = 'de-DE'
languageDirection = 'ltr'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.de.params]
subtitle = 'Referenz, Tutorials und Erklärungen'
[languages.en]
contentDir = 'content/en'
disabled = false
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
title = 'Project Documentation'
weight = 2
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
{{< /code-toggle >}}
> [!note]
> In the example above, omit `contentDir` if [translating by file name].
## Multihost
Hugo supports multiple languages in a multihost configuration. This means you can configure a `baseURL` per `language`.
> [!note]
> If you define a `baseURL` for one language, you must define a unique `baseURL` for all languages.
For example:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'fr'
[languages]
[languages.en]
baseURL = 'https://en.example.org/'
languageName = 'English'
title = 'In English'
weight = 2
[languages.fr]
baseURL = 'https://fr.example.org'
languageName = 'Français'
title = 'En Français'
weight = 1
{{</ code-toggle >}}
With the above, Hugo publishes two sites, each with their own root:
```text
public
├── en
└── fr
```
[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir
[`Language.LanguageCode`]: /methods/site/language/#languagecode
[`Language.LanguageDirection`]: /methods/site/language/#languagedirection
[`Language.LanguageName`]: /methods/site/language/#languagename
[`Language.Weight`]: /methods/site/language/#weight
[`Title`]: /methods/site/title/
[embedded alias template]: {{% eturl alias %}}
[embedded OpenGraph template]: {{% eturl opengraph %}}
[embedded RSS template]: {{% eturl rss %}}
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7
[translating by file name]: /content-management/multilingual/#translation-by-file-name

View File

@@ -0,0 +1,341 @@
---
title: Configure markup
linkTitle: Markup
description: Configure markup.
categories: []
keywords: []
aliases: [/getting-started/configuration-markup/]
---
## Default handler
In its default configuration, Hugo uses [Goldmark] to render Markdown to HTML.
{{< code-toggle file=hugo >}}
[markup]
defaultMarkdownHandler = 'goldmark'
{{< /code-toggle >}}
Files with ending with `.md`, `.mdown`, or `.markdown` are processed as Markdown, unless you've explicitly set a different format using the `markup` field in your front matter.
To use a different renderer for Markdown files, specify one of `asciidocext`, `org`, `pandoc`, or `rst` in your site configuration.
`defaultMarkdownHandler`|Renderer
:--|:--
`asciidocext`|[AsciiDoc]
`goldmark`|[Goldmark]
`org`|[Emacs Org Mode]
`pandoc`|[Pandoc]
`rst`|[reStructuredText]
To use AsciiDoc, Pandoc, or reStructuredText you must install the relevant renderer and update your [security policy].
> [!note]
> Unless you need a unique capability provided by one of the alternative Markdown handlers, we strongly recommend that you use the default setting. Goldmark is fast, well maintained, conforms to the [CommonMark] specification, and is compatible with [GitHub Flavored Markdown] (GFM).
## Goldmark
This is the default configuration for the Goldmark Markdown renderer:
{{< code-toggle config=markup.goldmark />}}
### Extensions
The extensions below, excluding Extras and Passthrough, are enabled by default.
Extension|Documentation|Enabled
:--|:--|:-:
`cjk`|[Goldmark Extensions: CJK]|:heavy_check_mark:
`definitionList`|[PHP Markdown Extra: Definition lists]|:heavy_check_mark:
`extras`|[Hugo Goldmark Extensions: Extras]||
`footnote`|[PHP Markdown Extra: Footnotes]|:heavy_check_mark:
`linkify`|[GitHub Flavored Markdown: Autolinks]|:heavy_check_mark:
`passthrough`|[Hugo Goldmark Extensions: Passthrough]||
`strikethrough`|[GitHub Flavored Markdown: Strikethrough]|:heavy_check_mark:
`table`|[GitHub Flavored Markdown: Tables]|:heavy_check_mark:
`taskList`|[GitHub Flavored Markdown: Task list items]|:heavy_check_mark:
`typographer`|[Goldmark Extensions: Typographer]|:heavy_check_mark:
#### Extras
{{< new-in 0.126.0 />}}
Enable [deleted text], [inserted text], [mark text], [subscript], and [superscript] elements in Markdown.
Element|Markdown|Rendered
:--|:--|:--
Deleted text|`~~foo~~`|`<del>foo</del>`
Inserted text|`++bar++`|`<ins>bar</ins>`
Mark text|`==baz==`|`<mark>baz</mark>`
Subscript|`H~2~O`|`H<sub>2</sub>O`
Superscript|`1^st^`|`1<sup>st</sup>`
To avoid a conflict when enabling the "subscript" feature of the Extras extension, if you want to render subscript and strikethrough text concurrently you must:
1. Disable the Strikethrough extension
1. Enable the "deleted text" feature of the Extras extension
For example:
{{< code-toggle file=hugo >}}
[markup.goldmark.extensions]
strikethrough = false
[markup.goldmark.extensions.extras.delete]
enable = true
[markup.goldmark.extensions.extras.subscript]
enable = true
{{< /code-toggle >}}
#### Passthrough
{{< new-in 0.122.0 />}}
Enable the Passthrough extension to include mathematical equations and expressions in Markdown using LaTeX markup. See [mathematics in Markdown] for details.
#### Typographer
The Typographer extension replaces certain character combinations with HTML entities as specified below:
Markdown|Replaced by|Description
:--|:--|:--
`...`|`&hellip;`|horizontal ellipsis
`'`|`&rsquo;`|apostrophe
`--`|`&ndash;`|en dash
`---`|`&mdash;`|em dash
`«`|`&laquo;`|left angle quote
`“`|`&ldquo;`|left double quote
``|`&lsquo;`|left single quote
`»`|`&raquo;`|right angle quote
`”`|`&rdquo;`|right double quote
``|`&rsquo;`|right single quote
### Settings explained
Most of the Goldmark settings above are self-explanatory, but some require explanation.
duplicateResourceFiles
: {{< new-in 0.123.0 />}}
: (`bool`) Whether to duplicate shared page resources for each language on multilingual single-host sites. See [multilingual page resources] for details. Default is `false`.
> [!note]
> With multilingual single-host sites, setting this parameter to `false` will enable Hugo's [embedded link render hook] and [embedded image render hook]. This is the default configuration for multilingual single-host sites.
parser.wrapStandAloneImageWithinParagraph
: (`bool`) Whether to wrap image elements without adjacent content within a `p` element when rendered. This is the default Markdown behavior. Set to `false` when using an [image render hook] to render standalone images as `figure` elements. Default is `true`.
parser.autoDefinitionTermID
: {{< new-in 0.144.0 />}}
: (`bool`) Whether to automatically add `id` attributes to description list terms (i.e., `dt` elements). When `true`, the `id` attribute of each `dt` element is accessible through the [`Fragments.Identifiers`] method on a `Page` object.
parser.autoHeadingID
: (`bool`) Whether to automatically add `id` attributes to headings (i.e., `h1`, `h2`, `h3`, `h4`, `h5`, and `h6` elements).
parser.autoIDType
: (`string`) The strategy used to automatically generate `id` attributes, one of `github`, `github-ascii` or `blackfriday`.
- `github` produces GitHub-compatible `id` attributes
- `github-ascii` drops any non-ASCII characters after accent normalization
- `blackfriday` produces `id` attributes compatible with the Blackfriday Markdown renderer
This is also the strategy used by the [anchorize](/functions/urls/anchorize) template function. Default is `github`.
parser.attribute.block
: (`bool`) Whether to enable [Markdown attributes] for block elements. Default is `false`.
parser.attribute.title
: (`bool`) Whether to enable [Markdown attributes] for headings. Default is `true`.
renderHooks.image.enableDefault
: {{< new-in 0.123.0 />}}
: (`bool`) Whether to enable the [embedded image render hook]. Default is `false`.
> [!note]
> The embedded image render hook is automatically enabled for multilingual single-host sites if [duplication of shared page resources] is disabled. This is the default configuration for multilingual single-host sites.
renderHooks.link.enableDefault
: {{< new-in 0.123.0 />}}
: (`bool`) Whether to enable the [embedded link render hook]. Default is `false`.
> [!note]
> The embedded link render hook is automatically enabled for multilingual single-host sites if [duplication of shared page resources] is disabled. This is the default configuration for multilingual single-host sites.
renderer.hardWraps
: (`bool`) Whether to replace newline characters within a paragraph with `br` elements. Default is `false`.
renderer.unsafe
: (`bool`) Whether to render raw HTML mixed within Markdown. This is unsafe unless the content is under your control. Default is `false`.
## AsciiDoc
This is the default configuration for the AsciiDoc renderer:
{{< code-toggle config=markup.asciidocExt />}}
### Settings explained
attributes
: (`map`) A map of key-value pairs, each a document attribute. See Asciidoctor's [attributes].
backend
: (`string`) The backend output file format. Default is `html5`.
extensions
: (`string array`) An array of enabled extensions, one or more of `asciidoctor-html5s`, `asciidoctor-bibtex`, `asciidoctor-diagram`, `asciidoctor-interdoc-reftext`, `asciidoctor-katex`, `asciidoctor-latex`, `asciidoctor-mathematical`, or `asciidoctor-question`.
> [!note]
> To mitigate security risks, entries in the extension array may not contain forward slashes (`/`), backslashes (`\`), or periods. Due to this restriction, extensions must be in Ruby's `$LOAD_PATH`.
failureLevel
: (`string`) The minimum logging level that triggers a non-zero exit code (failure). Default is `fatal`.
noHeaderOrFooter
: (`bool`) Whether to output an embeddable document, which excludes the header, the footer, and everything outside the body of the document. Default is `true`.
preserveTOC
: (`bool`) Whether to preserve the table of contents (TOC) rendered by Asciidoctor. By default, to make the TOC compatible with existing themes, Hugo removes the TOC rendered by Asciidoctor. To render the TOC, use the [`TableOfContents`] method on a `Page` object in your templates. Default is `false`.
safeMode
: (`string`) The safe mode level, one of `unsafe`, `safe`, `server`, or `secure`. Default is `unsafe`.
sectionNumbers
: (`bool`) Whether to number each section title. Default is `false`.
trace
: (`bool`) Whether to include backtrace information on errors. Default is `false`.
verbose
: (`bool`) Whether to verbosely print processing information and configuration file checks to stderr. Default is `false`.
workingFolderCurrent
: (`bool`) Whether to set the working directory to be the same as that of the AsciiDoc file being processed, allowing [includes] to work with relative paths. Set to `true` to render diagrams with the [asciidoctor-diagram] extension. Default is `false`.
### Configuration example
{{< code-toggle file=hugo >}}
[markup.asciidocExt]
extensions = ["asciidoctor-html5s", "asciidoctor-diagram"]
workingFolderCurrent = true
[markup.asciidocExt.attributes]
my-base-url = "https://example.com/"
my-attribute-name = "my value"
{{< /code-toggle >}}
### Syntax highlighting
Follow the steps below to enable syntax highlighting.
#### Step 1
Set the `source-highlighter` attribute in your site configuration. For example:
{{< code-toggle file=hugo >}}
[markup.asciidocExt.attributes]
source-highlighter = 'rouge'
{{< /code-toggle >}}
#### Step 2
Generate the highlighter CSS. For example:
```text
rougify style monokai.sublime > assets/css/syntax.css
```
#### Step 3
In your base template add a link to the CSS file:
```go-html-template {file="layouts/_default/baseof.html"}
<head>
...
{{ with resources.Get "css/syntax.css" }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
...
</head>
```
Then add the code to be highlighted to your markup:
```text
[#hello,ruby]
----
require 'sinatra'
get '/hi' do
"Hello World!"
end
----
```
### Troubleshooting
Run `hugo --logLevel debug` to examine Hugo's call to the Asciidoctor executable:
```txt
INFO 2019/12/22 09:08:48 Rendering book-as-pdf.adoc with C:\Ruby26-x64\bin\asciidoctor.bat using asciidoc args [--no-header-footer -r asciidoctor-html5s -b html5s -r asciidoctor-diagram --base-dir D:\prototypes\hugo_asciidoc_ddd\docs -a outdir=D:\prototypes\hugo_asciidoc_ddd\build -] ...
```
## Highlight
This is the default configuration.
{{< code-toggle config=markup.highlight />}}
{{% include "/_common/syntax-highlighting-options.md" %}}
## Table of contents
This is the default configuration for the table of contents, applicable to Goldmark and Asciidoctor:
{{< code-toggle config=markup.tableOfContents />}}
startLevel
: (`int`) Heading levels less than this value will be excluded from the table of contents. For example, to exclude `h1` elements from the table of contents, set this value to `2`. Default is `2`.
endLevel
: (`int`) Heading levels greater than this value will be excluded from the table of contents. For example, to exclude `h4`, `h5`, and `h6` elements from the table of contents, set this value to `3`. Default is `3`.
ordered
: (`bool`) Whether to generates an ordered list instead of an unordered list. Default is `false`.
[`Fragments.Identifiers`]: /methods/page/fragments/#identifiers
[`TableOfContents`]: /methods/page/tableofcontents/
[asciidoctor-diagram]: https://asciidoctor.org/docs/asciidoctor-diagram/
[attributes]: https://asciidoctor.org/docs/asciidoc-syntax-quick-reference/#attributes-and-substitutions
[CommonMark]: https://spec.commonmark.org/current/
[deleted text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del
[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles
[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles
[embedded image render hook]: /render-hooks/images/#default
[embedded image render hook]: /render-hooks/images/#default
[embedded link render hook]: /render-hooks/links/#default
[embedded link render hook]: /render-hooks/links/#default
[GitHub Flavored Markdown]: https://github.github.com/gfm/
[GitHub Flavored Markdown: Autolinks]: https://github.github.com/gfm/#autolinks-extension-
[GitHub Flavored Markdown: Strikethrough]: https://github.github.com/gfm/#strikethrough-extension-
[GitHub Flavored Markdown: Tables]: https://github.github.com/gfm/#tables-extension-
[GitHub Flavored Markdown: Task list items]: https://github.github.com/gfm/#task-list-items-extension-
[Goldmark]: https://github.com/yuin/goldmark/
[Goldmark Extensions: CJK]: https://github.com/yuin/goldmark?tab=readme-ov-file#cjk-extension
[Goldmark Extensions: Typographer]: https://github.com/yuin/goldmark?tab=readme-ov-file#typographer-extension
[Hugo Goldmark Extensions: Extras]: https://github.com/gohugoio/hugo-goldmark-extensions?tab=readme-ov-file#extras-extension
[Hugo Goldmark Extensions: Passthrough]: https://github.com/gohugoio/hugo-goldmark-extensions?tab=readme-ov-file#passthrough-extension
[image render hook]: /render-hooks/images/
[includes]: https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/#includes
[inserted text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins
[mark text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark
[Markdown attributes]: /content-management/markdown-attributes/
[mathematics in Markdown]: content-management/mathematics/
[multilingual page resources]: /content-management/page-resources/#multilingual
[PHP Markdown Extra: Definition lists]: https://michelf.ca/projects/php-markdown/extra/#def-list
[PHP Markdown Extra: Footnotes]: https://michelf.ca/projects/php-markdown/extra/#footnotes
[security policy]: /configuration/security/
[subscript]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub
[superscript]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup
[AsciiDoc]: https://asciidoc.org/
[Emacs Org Mode]: https://orgmode.org/
[Pandoc]: https://www.pandoc.org/
[reStructuredText]: https://docutils.sourceforge.io/rst.html

View File

@@ -0,0 +1,82 @@
---
title: Configure media types
linkTitle: Media types
description: Configure media types.
categories: []
keywords: []
---
{{% glossary-term "media type" %}}
Configured media types serve multiple purposes in Hugo, including the definition of [output formats](g). This is the default media type configuration in tabular form:
{{< datatable "config" "mediaTypes" "_key" "suffixes" >}}
The `suffixes` column in the table above shows the suffixes associated with each media type. For example, Hugo associates `.html` and `.htm` files with the `text/html` media type.
> [!note]
> The first suffix is the primary suffix. Use the primary suffix when naming template files. For example, when creating a template for an RSS feed, use the `xml` suffix.
## Default configuration
The following is the default configuration that matches the table above:
{{< code-toggle file=hugo config=mediaTypes />}}
delimiter
: (`string`) The delimiter between the file name and the suffix. The delimiter, in conjunction with the suffix, forms the file extension. Default is `"."`.
suffixes
: (`[]string`) The suffixes associated with this media type. The first suffix is the primary suffix.
## Modify a media type
You can modify any of the default media types. For example, to switch the primary suffix for `text/html` from `html` to `htm`:
{{< code-toggle file=hugo >}}
[mediaTypes.'text/html']
suffixes = ['htm','html']
{{< /code-toggle >}}
If you alter a default media type, you must also explicitly redefine all output formats that utilize that media type. For example, to ensure the changes above affect the `html` output format, redefine the `html` output format:
{{< code-toggle file=hugo >}}
[outputFormats.html]
mediaType = 'text/html'
{{< /code-toggle >}}
## Create a media type
You can create new media types as needed. For example, to create a media type for an Atom feed:
{{< code-toggle file=hugo >}}
[mediaTypes.'application/atom+xml']
suffixes = ['atom']
{{< /code-toggle >}}
## Media types without suffixes
Occasionally, you may need to create a media type without a suffix or delimiter. For example, [Netlify] recognizes configuration files named `_redirects` and `_headers`, which Hugo can generate using custom [output formats](g).
To support these custom output formats, register a custom media type with no suffix or delimiter:
{{< code-toggle file=hugo >}}
[mediaTypes."text/netlify"]
delimiter = ""
{{< /code-toggle >}}
The custom output format definitions would look something like this:
{{< code-toggle file=hugo >}}
[outputFormats.redir]
baseName = "_redirects"
isPlainText = true
mediatype = "text/netlify"
[outputFormats.headers]
baseName = "_headers"
isPlainText = true
mediatype = "text/netlify"
notAlternative = true
{{< /code-toggle >}}
[Netlify]: https://www.netlify.com/

View File

@@ -0,0 +1,135 @@
---
title: Configure menus
linkTitle: Menus
description: Centrally define menu entries for one or more menus.
categories: []
keywords: []
---
> [!note]
> To understand Hugo's menu system, please refer to the [menus] page.
There are three ways to define menu entries:
1. [Automatically]
1. [In front matter]
1. In site configuration
This page covers the site configuration method.
## Example
To define entries for a "main" menu:
{{< code-toggle file=hugo >}}
[[menus.main]]
name = 'Home'
pageRef = '/'
weight = 10
[[menus.main]]
name = 'Products'
pageRef = '/products'
weight = 20
[[menus.main]]
name = 'Services'
pageRef = '/services'
weight = 30
{{< /code-toggle >}}
This creates a menu structure that you can access with [`Menus`] method on a `Site` object:
```go-html-template
{{ range .Site.Menus.main }}
...
{{ end }}
```
See [menu templates] for a detailed example.
To define entries for a "footer" menu:
{{< code-toggle file=hugo >}}
[[menus.footer]]
name = 'Terms'
pageRef = '/terms'
weight = 10
[[menus.footer]]
name = 'Privacy'
pageRef = '/privacy'
weight = 20
{{< /code-toggle >}}
Access this menu structure in the same way:
```go-html-template
{{ range .Site.Menus.footer }}
...
{{ end }}
```
## Properties
Menu entries usually include at least three properties: `name`, `weight`, and either `pageRef` or `url`. Use `pageRef` for internal page destinations and `url` for external destinations.
These are the available menu entry properties:
{{% include "/_common/menu-entry-properties.md" %}}
pageRef
: (`string`) The [logical path](g) of the target page. For example:
page kind|pageRef
:--|:--
home|`/`
page|`/books/book-1`
section|`/books`
taxonomy|`/tags`
term|`/tags/foo`
url
: (`string`) The destination URL. Use this for external destinations only.
## Nested menu
This nested menu demonstrates some of the available properties:
{{< code-toggle file=hugo >}}
[[menus.main]]
name = 'Products'
pageRef = '/products'
weight = 10
[[menus.main]]
name = 'Hardware'
pageRef = '/products/hardware'
parent = 'Products'
weight = 1
[[menus.main]]
name = 'Software'
pageRef = '/products/software'
parent = 'Products'
weight = 2
[[menus.main]]
name = 'Services'
pageRef = '/services'
weight = 20
[[menus.main]]
name = 'Hugo'
pre = '<i class="fa fa-heart"></i>'
url = 'https://gohugo.io/'
weight = 30
[menus.main.params]
rel = 'external'
{{< /code-toggle >}}
[`Menus`]: /methods/site/menus/
[Automatically]: /content-management/menus/#define-automatically
[In front matter]: /content-management/menus/#define-in-front-matter
[menu templates]: /templates/menu/
[menus]: /content-management/menus/

View File

@@ -0,0 +1,15 @@
---
title: Configure minify
linkTitle: Minify
description: Configure minify.
categories: []
keywords: []
---
This is the default configuration:
{{< code-toggle config=minify />}}
See the [tdewolff/minify] project page for details.
[tdewolff/minify]: https://github.com/tdewolff/minify

View File

@@ -0,0 +1,179 @@
---
title: Configure modules
linkTitle: Modules
description: Configure modules.
categories: []
keywords: []
aliases: [/hugo-modules/configuration/]
---
## Top-level options
This is the default configuration:
{{< code-toggle file=hugo >}}
[module]
noProxy = 'none'
noVendor = ''
private = '*.*'
proxy = 'direct'
vendorClosest = false
workspace = 'off'
{{< /code-toggle >}}
auth
: {{< new-in 0.144.0 />}}
: (`string`) Configures `GOAUTH` when running the Go command for module operations. This is a semicolon-separated list of authentication commands for go-import and HTTPS module mirror interactions. This is useful for private repositories. See `go help goauth` for more information.
noProxy
: (`string`) A comma-separated list of [glob](g) patterns matching paths that should not use the [configured proxy server](#proxy).
noVendor
: (`string`) A [glob](g) pattern matching module paths to skip when vendoring.
private
: (`string`) A comma-separated list of [glob](g) patterns matching paths that should be treated as private.
proxy
: (`string`) The proxy server to use to download remote modules. Default is `direct`, which means `git clone` and similar.
replacements
: (`string`) Primarily useful for local module development, a comma-separated list of mappings from module paths to directories. Paths may be absolute or relative to the [`themesDir`].
{{< code-toggle file=hugo >}}
[module]
replacements = 'github.com/bep/my-theme -> ../..,github.com/bep/shortcodes -> /some/path'
{{< /code-toggle >}}
vendorClosest
: (`bool`) Whether to pick the vendored module closest to the module using it. The default behavior is to pick the first. Note that there can still be only one dependency of a given module path, so once it is in use it cannot be redefined. Default is `false`.
workspace
: (`string`) The Go workspace file to use, either as an absolute path or a path relative to the current working directory. Enabling this activates Go workspace mode and requires Go 1.18 or later. The default is `off`.
You may also use environment variables to set any of the above. For example:
```sh
export HUGO_MODULE_PROXY="https://proxy.example.org"
export HUGO_MODULE_REPLACEMENTS="github.com/bep/my-theme -> ../.."
export HUGO_MODULE_WORKSPACE="/my/hugo.work"
```
{{% include "/_common/gomodules-info.md" %}}
## Hugo version
You can specify a required Hugo version for your module in the `module` section. Users will then receive a warning if their Hugo version is incompatible.
This is the default configuration:
{{< code-toggle config=module.hugoVersion />}}
You can omit any of the settings above.
extended
: (`bool`) Whether the extended edition of Hugo is required, satisfied by installing either the extended or extended/deploy edition.
max
: (`string`) The maximum Hugo version supported, for example `0.143.0`.
min
: (`string`) The minimum Hugo version supported, for example `0.123.0`.
[`themesDir`]: /configuration/all/#themesdir
## Imports
{{< code-toggle file=hugo >}}
[[module.imports]]
disable = false
ignoreConfig = false
ignoreImports = false
path = "github.com/gohugoio/hugoTestModules1_linux/modh1_2_1v"
[[module.imports]]
path = "my-shortcodes"
{{< /code-toggle >}}
disable
: (`bool`) Whether to disable the module but keep version information in the `go.*` files. Default is `false`.
ignoreConfig
: (`bool`) Whether to ignore module configuration files, for example, `hugo.toml`. This will also prevent loading of any transitive module dependencies. Default is `false`.
ignoreImports
: (`bool`) Whether to ignore module imports. Default is `false`.
noMounts
: (`bool`) Whether to disable directory mounting for this import. Default is `false`.
noVendor
: (`bool`) Whether to disable vendoring for this import. This setting is restricted to the main project. Default is `false`.
path
: (`string`) The module path, either a valid Go module path (e.g., `github.com/gohugoio/myShortcodes`) or the directory name if stored in the [`themesDir`].
[`themesDir`]: /configuration/all#themesDir
{{% include "/_common/gomodules-info.md" %}}
## Mounts
Before Hugo v0.56.0, custom component paths could only be configured by setting [`archetypeDir`], [`assetDir`], [`contentDir`], [`dataDir`], [`i18nDir`], [`layoutDi`], or [`staticDir`] in the site configuration. Module mounts offer greater flexibility than these legacy settings, but
you cannot use both.
[`archetypeDir`]: /configuration/all/
[`assetDir`]: /configuration/all/
[`contentDir`]: /configuration/all/
[`dataDir`]: /configuration/all/
[`i18nDir`]: /configuration/all/
[`layoutDi`]: /configuration/all/
[`staticDir`]: /configuration/all/
> [!note]
> If you use module mounts do not use the legacy settings.
### Default mounts
> [!note]
> Adding a new mount to a target root will cause the existing default mount for that root to be ignored. If you still need the default mount, you must explicitly add it along with the new mount.
The are the default mounts:
{{< code-toggle config=module.mounts />}}
source
: (`string`) The source directory of the mount. For the main project, this can be either project-relative or absolute. For other modules it must be project-relative.
target
: (`string`) Where the mount will reside within Hugo's virtual file system. It must begin with one of Hugo's component directories: `archetypes`, `assets`, `content`, `data`, `i18n`, `layouts`, or `static`. For example, `content/blog`.
disableWatch
: {{< new-in 0.128.0 />}}
: (`bool`) Whether to disable watching in watch mode for this mount. Default is `false`.
lang
: (`string`) The language code, e.g. "en". Relevant for `content` mounts, and `static` mounts when in multihost mode.
includeFiles
: (`string` or `[]string`) One or more [glob](g) patterns matching files or directories to include. If `excludeFiles` is not set, the files matching `includeFiles` will be the files mounted.
The glob patterns are matched against file names relative to the source root. Use Unix-style forward slashes (`/`), even on Windows. A single forward slash (`/`) matches the mount root, and double asterisks (`**`) act as a recursive wildcard, matching all directories and files beneath a given point (e.g., `/posts/**.jpg`). The search is case-insensitive.
excludeFiles
: (`string` or `[]string`) One or more [glob](g) patterns matching files to exclude.
### Example
{{< code-toggle file=hugo >}}
[module]
[[module.mounts]]
source="content"
target="content"
excludeFiles="docs/*"
[[module.mounts]]
source="node_modules"
target="assets"
[[module.mounts]]
source="assets"
target="assets"
{{< /code-toggle >}}

View File

@@ -0,0 +1,209 @@
---
title: Configure output formats
linkTitle: Output formats
description: Configure output formats.
categories: []
keywords: []
---
{{% glossary-term "output format" %}}
You can output a page in as many formats as you want. Define an infinite number of output formats, provided they each resolve to a unique file system path.
This is the default output format configuration in tabular form:
{{< datatable
"config"
"outputFormats"
"_key"
"mediaType"
"weight"
"baseName"
"isHTML"
"isPlainText"
"noUgly"
"notAlternative"
"path"
"permalinkable"
"protocol"
"rel"
"root"
"ugly"
>}}
## Default configuration
The following is the default configuration that matches the table above:
{{< code-toggle config=outputFormats />}}
baseName
: (`string`) The base name of the published file. Default is `index`.
isHTML
: (`bool`) Whether to classify the output format as HTML. Hugo uses this value to determine when to create alias redirects and when to inject the LiveReload script. Default is `false`.
isPlainText
: (`bool`) Whether to parse templates for this output format with Go's [text/template] package instead of the [html/template] package. Default is `false`.
mediaType
: (`string`) The [media type](g) of the published file. This must match one of the [configured media types].
notAlternative
: (`bool`) Whether to exclude this output format from the values returned by the [`AlternativeOutputFormats`] method on a `Page` object. Default is `false`.
noUgly
: (`bool`) Whether to disable ugly URLs for this output format when [`uglyURLs`] are enabled in your site configuration. Default is `false`.
path
: (`string`) The published file's directory path, relative to the root of the publish directory. If not specified, the file will be published using its content path.
permalinkable
: (`bool`) Whether to return the rendering output format rather than main output format when invoking the [`Permalink`] and [`RelPermalink`] methods on a `Page` object. See&nbsp;[details](#link-to-output-formats). Enabled by default for the `html` and `amp` output formats. Default is `false`.
protocol
: (`string`) The protocol (scheme) of the URL for this output format. For example, `https://` or `webcal://`. Default is the scheme of the [`baseURL`] parameter in your site configuration, typically `https://`.
rel
: (`string`) If provided, you can assign this value to `rel` attributes in `link` elements when iterating over output formats in your templates. Default is `alternate`.
root
: (`bool`) Whether to publish files to the root of the publish directory. Default is `false`.
ugly
: (`bool`) Whether to enable uglyURLs for this output format when `uglyURLs` is `false` in your site configuration. Default is `false`.
weight
: (`int`) When set to a non-zero value, Hugo uses the `weight` as the first criteria when sorting output formats, falling back to the name of the output format. Lighter items float to the top, while heavier items sink to the bottom. Hugo renders output formats sequentially based on the sort order. Default is `0`, except for the `html` output format, which has a default weight of `10`.
## Modify an output format
You can modify any of the default output formats. For example, to prioritize `json` rendering over `html` rendering, when both are generated, adjust the [`weight`](#weight):
{{< code-toggle file=hugo >}}
[outputFormats.json]
weight = 1
[outputFormats.html]
weight = 2
{{< /code-toggle >}}
The example above shows that when you modify a default content format, you only need to define the properties that differ from their default values.
## Create an output format
You can create new output formats as needed. For example, you may wish to create an output format to support Atom feeds.
### Step 1
Output formats require a specified media type. Because Atom feeds use `application/atom+xml`, which is not one of the [default media types], you must create it first.
{{< code-toggle file=hugo >}}
[mediaTypes.'application/atom+xml']
suffixes = ['atom']
{{< /code-toggle >}}
See [configure media types] for more information.
### Step 2
Create a new output format:
{{< code-toggle file=hugo >}}
[outputFormats.atom]
mediaType = 'application/atom+xml'
noUgly = true
{{< /code-toggle >}}
Note that we use the default settings for all other output format properties.
### Step 3
Specify the page [kinds](g) for which to render this output format:
{{< code-toggle file=hugo >}}
[outputs]
home = ['html', 'rss', 'atom']
section = ['html', 'rss', 'atom']
taxonomy = ['html', 'rss', 'atom']
term = ['html', 'rss', 'atom']
{{< /code-toggle >}}
See [configure outputs] for more information.
### Step 4
Create a template to render the output format. Since Atom feeds are lists, you need to create a list template. Consult the [template lookup order] to find the correct template path:
```text
layouts/_default/list.atom.atom
```
We leave writing the template code as an exercise for you. Aim for a result similar to the [embedded RSS template].
## List output formats
To access output formats, each `Page` object provides two methods: [`OutputFormats`] (for all formats, including the current one) and [`AlternativeOutputFormats`]. Use `AlternativeOutputFormats` to create a link `rel` list within your site's `head` element, as shown below:
```go-html-template
{{ range .AlternativeOutputFormats }}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
{{ end }}
```
## Link to output formats
By default, a `Page` object's [`Permalink`] and [`RelPermalink`] methods return the URL of the [primary output format](g), typically `html`. This behavior remains consistent regardless of the template used.
For example, in `single.json.json`, you'll see:
```go-html-template
{{ .RelPermalink }} → /that-page/
{{ with .OutputFormats.Get "json" }}
{{ .RelPermalink }} → /that-page/index.json
{{ end }}
```
To make these methods return the URL of the _current_ template's output format, you must set the [`permalinkable`] setting to `true` for that format.
With `permalinkable` set to true for `json` in the same `single.json.json` template:
```go-html-template
{{ .RelPermalink }} → /that-page/index.json
{{ with .OutputFormats.Get "html" }}
{{ .RelPermalink }} → /that-page/
{{ end }}
```
## Template lookup order
Each output format requires a template conforming to the [template lookup order].
For the highest specificity in the template lookup order, include the page kind, output format, and suffix in the file name:
```text
[page kind].[output format].[suffix]
```
For example, for section pages:
Output format|Template path
:--|:--
`html`|`layouts/_default/section.html.html`
`json`|`layouts/_default/section.json.json`
`rss`|`layouts/_default/section.rss.xml`
[`AlternativeOutputFormats`]: /methods/page/alternativeoutputformats/
[`OutputFormats`]: /methods/page/outputformats/
[`Permalink`]: /methods/page/permalink/
[`RelPermalink`]: /methods/page/relpermalink/
[`baseURL`]: /configuration/all/#baseurl
[`permalinkable`]: #permalinkable
[`uglyURLs`]: /configuration/ugly-urls/
[configure media types]: /configuration/media-types/
[configure outputs]: /configuration/outputs/
[configured media types]: /configuration/media-types/
[default media types]: /configuration/media-types/
[embedded RSS template]: {{% eturl rss %}}
[html/template]: https://pkg.go.dev/html/template
[template lookup order]: /templates/lookup-order/
[text/template]: https://pkg.go.dev/text/template

View File

@@ -0,0 +1,49 @@
---
title: Configure outputs
linkTitle: Outputs
description: Configure which output formats to render for each page kind.
categories: []
keywords: []
---
{{% glossary-term "output format" %}}
Learn more about creating and configuring output formats in the [configure output formats] section.
## Outputs per page kind
The following default configuration determines the output formats generated for each page kind:
{{< code-toggle config=outputs />}}
To render the built-in `json` output format for the `home` page kind, assuming you've already created the necessary template, add the following to your configuration:
{{< code-toggle file=hugo >}}
[outputs]
home = ['html','rss','json']
{{< /code-toggle >}}
Notice in this example that we only specified the `home` page kind. You don't need to include entries for other page kinds unless you intend to modify their default output formats.
> [!note]
> The order of the output formats in the arrays above is important. The first element will be the _primary output format_ for that page kind, and in most cases that should be `html` as shown in the default configuration.
>
> The primary output format for a given page kind determines the value returned by the [`Permalink`] and [`RelPermalink`] methods on a `Page` object.
>
> See the [link to output formats] section for details.
## Outputs per page
Add output formats to a page's rendering using the `outputs` field in its front matter. For example, to include `json` in the output formats rendered for a specific page:
{{< code-toggle file=content/example.md fm=true >}}
title = 'Example'
outputs = ['json']
{{< /code-toggle >}}
In its default configuration, Hugo will render both the `html` and `json` output formats for this page. The `outputs` field appends to, rather than replaces, the site's configured outputs.
[`Permalink`]: /methods/page/permalink/
[`RelPermalink`]: /methods/page/relpermalink/
[configure output formats]: /configuration/output-formats/
[link to output formats]: configuration/output-formats/#link-to-output-formats

View File

@@ -0,0 +1,34 @@
---
title: Configure page
linkTitle: Page
description: Configure page behavior.
categories: []
keywords: []
---
{{< new-in 0.133.0 />}}
{{% glossary-term "default sort order" %}}
Hugo uses the default sort order to determine the _next_ and _previous_ page relative to the current page when calling these methods on a `Page` object:
- [`Next`](/methods/page/next/) and [`Prev`](/methods/page/prev/)
- [`NextInSection`](/methods/page/nextinsection/) and [`PrevInSection`](/methods/page/previnsection/)
This is based on this default site configuration:
{{< code-toggle config=page />}}
To reverse the meaning of _next_ and _previous_:
{{< code-toggle file=hugo >}}
[page]
nextPrevInSectionSortOrder = 'asc'
nextPrevSortOrder = 'asc'
{{< /code-toggle >}}
> [!note]
> These settings do not apply to the [`Next`] or [`Prev`] methods on a `Pages` object.
[`Next`]: /methods/pages/next
[`Prev`]: /methods/pages/next

View File

@@ -0,0 +1,45 @@
---
title: Configure pagination
linkTitle: Pagination
description: Configure pagination.
categories: []
keywords: []
---
This is the default configuration:
{{< code-toggle config=pagination />}}
disableAliases
: (`bool`) Whether to disable alias generation for the first pager. Default is `false`.
pagerSize
: (`int`) The number of pages per pager. Default is `10`.
path
: (`string`) The segment of each pager URL indicating that the target page is a pager. Default is `page`.
With multilingual sites you can define the pagination behavior for each language:
{{< code-toggle file=hugo >}}
[languages.en]
contentDir = 'content/en'
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
weight = 1
[languages.en.pagination]
disableAliases = true
pagerSize = 10
path = 'page'
[languages.de]
contentDir = 'content/de'
languageCode = 'de-DE'
languageDirection = 'ltr'
languageName = 'Deutsch'
weight = 2
[languages.de.pagination]
disableAliases = true
pagerSize = 20
path = 'blatt'
{{< /code-toggle >}}

View File

@@ -0,0 +1,100 @@
---
title: Configure params
linkTitle: Params
description: Create custom site parameters.
categories: []
keywords: []
---
Use the `params` key for custom parameters:
{{< code-toggle file=hugo >}}
baseURL = 'https://example.org/'
title = 'Project Documentation'
languageCode = 'en-US'
[params]
subtitle = 'Reference, Tutorials, and Explanations'
[params.contact]
email = 'info@example.org'
phone = '+1 206-555-1212'
{{< /code-toggle >}}
Access the custom parameters from your templates using the [`Params`] method on a `Site` object:
[`Params`]: /methods/site/params/
```go-html-template
{{ .Site.Params.subtitle }} → Reference, Tutorials, and Explanations
{{ .Site.Params.contact.email }} → info@example.org
```
Key names should use camelCase or snake_case. While TOML, YAML, and JSON allow kebab-case keys, they are not valid [identifiers](g) and cannot be used when [chaining](g) identifiers.
For example, you can do either of these:
```go-html-template
{{ .Site.params.camelCase.foo }}
{{ .Site.params.snake_case.foo }}
```
But you cannot do this:
```go-html-template
{{ .Site.params.kebab-case.foo }}
```
## Multilingual sites
For multilingual sites, create a `params` key under each language:
{{< code-toggle file=hugo >}}
baseURL = 'https://example.org/'
defaultContentLanguage = 'en'
[languages.de]
languageCode = 'de-DE'
languageDirection = 'ltr'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.de.params]
subtitle = 'Referenz, Tutorials und Erklärungen'
[languages.de.params.contact]
email = 'info@de.example.org'
phone = '+49 30 1234567'
[languages.en]
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
title = 'Project Documentation'
weight = 2
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
[languages.en.params.contact]
email = 'info@example.org'
phone = '+1 206-555-1212'
{{< /code-toggle >}}
## Namespacing
To prevent naming conflicts, module and theme developers should namespace any custom parameters specific to their module or theme.
{{< code-toggle file=hugo >}}
[params.modules.myModule.colors]
background = '#efefef'
font = '#222222'
{{< /code-toggle >}}
To access the module/theme settings:
```go-html-template
{{ $cfg := .Site.Params.module.mymodule }}
{{ $cfg.colors.background }} → #efefef
{{ $cfg.colors.font }} → #222222
```

View File

@@ -0,0 +1,162 @@
---
title: Configure permalinks
linkTitle: Permalinks
description: Configure permalinks.
categories: []
keywords: []
---
This is the default configuration:
{{< code-toggle config=permalinks />}}
Define a URL pattern for each top-level section. Each URL pattern can target a given language and/or page kind.
> [!note]
> The [`url`] front matter field overrides any matching permalink pattern.
## Monolingual example
With this content structure:
```text
content/
├── posts/
│ ├── bash-in-slow-motion.md
│ └── tls-in-a-nutshell.md
├── tutorials/
│ ├── git-for-beginners.md
│ └── javascript-bundling-with-hugo.md
└── _index.md
```
Render tutorials under "training", and render the posts under "articles" with a date-base hierarchy:
{{< code-toggle file=hugo >}}
[permalinks.page]
posts = '/articles/:year/:month/:slug/'
tutorials = '/training/:slug/'
[permalinks.section]
posts = '/articles/'
tutorials = '/training/'
{{< /code-toggle >}}
The structure of the published site will be:
```text
public/
├── articles/
│ ├── 2023/
│ │ ├── 04/
│ │ │ └── bash-in-slow-motion/
│ │ │ └── index.html
│ │ └── 06/
│ │ └── tls-in-a-nutshell/
│ │ └── index.html
│ └── index.html
├── training/
│ ├── git-for-beginners/
│ │ └── index.html
│ ├── javascript-bundling-with-hugo/
│ │ └── index.html
│ └── index.html
└── index.html
```
To create a date-based hierarchy for regular pages in the content root:
{{< code-toggle file=hugo >}}
[permalinks.page]
"/" = "/:year/:month/:slug/"
{{< /code-toggle >}}
Use the same approach with taxonomy terms. For example, to omit the taxonomy segment of the URL:
{{< code-toggle file=hugo >}}
[permalinks.term]
'tags' = '/:slug/'
{{< /code-toggle >}}
## Multilingual example
Use the `permalinks` configuration as a component of your localization strategy.
With this content structure:
```text
content/
├── en/
│ ├── books/
│ │ ├── les-miserables.md
│ │ └── the-hunchback-of-notre-dame.md
│ └── _index.md
└── es/
├── books/
│ ├── les-miserables.md
│ └── the-hunchback-of-notre-dame.md
└── _index.md
```
And this site configuration:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = true
[languages.en]
contentDir = 'content/en'
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
weight = 1
[languages.en.permalinks.page]
books = "/books/:slug/"
[languages.en.permalinks.section]
books = "/books/"
[languages.es]
contentDir = 'content/es'
languageCode = 'es-ES'
languageDirection = 'ltr'
languageName = 'Español'
weight = 2
[languages.es.permalinks.page]
books = "/libros/:slug/"
[languages.es.permalinks.section]
books = "/libros/"
{{< /code-toggle >}}
The structure of the published site will be:
```text
public/
├── en/
│ ├── books/
│ │ ├── les-miserables/
│ │ │ └── index.html
│ │ ├── the-hunchback-of-notre-dame/
│ │ │ └── index.html
│ │ └── index.html
│ └── index.html
├── es/
│ ├── libros/
│ │ ├── les-miserables/
│ │ │ └── index.html
│ │ ├── the-hunchback-of-notre-dame/
│ │ │ └── index.html
│ │ └── index.html
│ └── index.html
└── index.html
```
## Tokens
Use these tokens when defining a URL pattern.
{{% include "/_common/permalink-tokens.md" %}}
[`url`]: /content-management/front-matter/#url

View File

@@ -1,17 +1,10 @@
---
title: Privacy
title: Configure privacy
linkTitle: Privacy
description: Configure your site to help comply with regional privacy regulations.
categories: [about]
keywords: ["GDPR", "Privacy", "Data Protection"]
menu:
docs:
parent: about
weight: 40
weight: 40
toc: true
aliases: [/gdpr/,/about/hugo-and-gdpr/]
toc: true
categories: []
keywords: []
aliases: [/about/privacy/]
---
## Responsibility
@@ -31,12 +24,10 @@ Hugo provides [embedded templates](g) to simplify site and content creation. Som
Some of these templates include settings to enhance privacy.
## Configuration
{{% note %}}
These settings affect the behavior of some of Hugo's embedded templates. These settings may or may not affect the behavior of templates provided by third parties in their modules or themes.
{{% /note %}}
> [!note]
> These settings affect the behavior of some of Hugo's embedded templates. These settings may or may not affect the behavior of templates provided by third parties in their modules or themes.
These are the default privacy settings for Hugo's embedded templates:

View File

@@ -0,0 +1,111 @@
---
title: Configure related content
linkTitle: Related content
description: Configure related content.
categories: []
keywords: []
---
> [!note]
> To understand Hugo's related content identification, please refer to the [related content] page.
Hugo provides a sensible default configuration for identifying related content, but you can customize it in your site configuration, either globally or per language.
## Default configuration
This is the default configuration:
{{< code-toggle config=related />}}
> [!note]
> Adding a `related` section to your site configuration requires you to provide a full configuration. You cannot override individual default values without specifying all related settings.
## Top-level options
threshold
: (`int`) A value between 0-100, inclusive. A lower value will return more, but maybe not so relevant, matches.
includeNewer
: (`bool`) Whether to include pages newer than the current page in the related content listing. This will mean that the output for older posts may change as new related content gets added. Default is `false`.
toLower
: (`bool`) Whether to transform keywords in both the indexes and the queries to lower case. This may give more accurate results at a slight performance penalty. Default is `false`.
## Per-index options
name
: (`string`) The index name. This value maps directly to a page parameter. Hugo supports string values (`author` in the example) and lists (`tags`, `keywords` etc.) and time and date objects.
type
: (`string`) One of `basic` or `fragments`. Default is `basic`.
applyFilter
: (`string`) Apply a `type` specific filter to the result of a search. This is currently only used for the `fragments` type.
weight
: (`int`) An integer weight that indicates how important this parameter is relative to the other parameters. It can be `0`, which has the effect of turning this index off, or even negative. Test with different values to see what fits your content best. Default is `0`.
cardinalityThreshold
: (`int`) If between 1 and 100, this is a percentage. All keywords that are used in more than this percentage of documents are removed. For example, setting this to `60` will remove all keywords that are used in more than 60% of the documents in the index. If `0`, no keyword is removed from the index. Default is `0`.
pattern
: (`string`) This is currently only relevant for dates. When listing related content, we may want to list content that is also close in time. Setting "2006" (default value for date indexes) as the pattern for a date index will add weight to pages published in the same year. For busier blogs, "200601" (year and month) may be a better default.
toLower
: (`bool`) Whether to transform keywords in both the indexes and the queries to lower case. This may give more accurate results at a slight performance penalty. Default is `false`.
## Example
Imagine we're building a book review site. Our main content will be book reviews, and we'll use genres and authors as taxonomies. When someone views a book review, we want to show a short list of related reviews based on shared authors and genres.
Create the content:
```text
content/
└── book-reviews/
├── book-review-1.md
├── book-review-2.md
├── book-review-3.md
├── book-review-4.md
└── book-review-5.md
```
Configure the taxonomies:
{{< code-toggle file=hugo >}}
[taxonomies]
author = 'authors'
genre = 'genres'
{{< /code-toggle >}}
Configure the related content identification:
{{< code-toggle file=hugo >}}
[related]
includeNewer = true
threshold = 80
toLower = true
[[related.indices]]
name = 'authors'
weight = 2
[[related.indices]]
name = 'genres'
weight = 1
{{< /code-toggle >}}
We've configured the `authors` index with a weight of `2` and the `genres` index with a weight of `1`. This means Hugo prioritizes shared `authors` as twice as significant as shared `genres`.
Then render a list of 5 related reviews with a partial template like this:
```go-html-template {file="layouts/partials/related.html" copy=true}
{{ with site.RegularPages.Related . | first 5 }}
<p>Related content:</p>
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
```
[related content]: /content-management/related-content/

View File

@@ -0,0 +1,50 @@
---
title: Configure security
linkTitle: Security
description: Configure security.
categories: []
keywords: []
---
Hugo's built-in security policy, which restricts access to `os/exec`, remote communication, and similar operations, is configured via allow lists. By default, access is restricted. If a build attempts to use a feature not included in the allow list, it will fail, providing a detailed message.
This is the default security configuration:
{{< code-toggle config=security />}}
enableInlineShortcodes
: (`bool`) Whether to enable [inline shortcodes]. Default is `false`.
exec.allow
: (`[]string`) A slice of [regular expressions](g) matching the names of external executables that Hugo is allowed to run.
exec.osEnv
: (`[]string`) A slice of [regular expressions](g) matching the names of operating system environment variables that Hugo is allowed to access.
funcs.getenv
: (`[]string`) A slice of [regular expressions](g) matching the names of operating system environment variables that Hugo is allowed to access with the [`os.Getenv`] function.
http.methods
: (`[]string`) A slice of [regular expressions](g) matching the HTTP methods that the [`resources.GetRemote`] function is allowed to use.
http.mediaTypes
: (`[]string`) Applicable to the `resources.GetRemote` function, a slice of [regular expressions](g) matching the `Content-Type` in HTTP responses that Hugo trusts, bypassing file content analysis for media type detection.
http.urls
: (`[]string`) A slice of [regular expressions](g) matching the URLs that the `resources.GetRemote` function is allowed to access.
> [!note]
> Setting an allow list to the string `none` will completely disable the associated feature.
You can also override the site configuration with environment variables. For example, to block `resources.GetRemote` from accessing any URL:
```txt
export HUGO_SECURITY_HTTP_URLS=none
```
Learn more about [using environment variables] to configure your site.
[`os.Getenv`]: /functions/os/getenv
[`resources.GetRemote`]: /functions/resources/getremote
[inline shortcodes]: /content-management/shortcodes/#inline
[using environment variables]: /configuration/introduction/#environment-variables

View File

@@ -0,0 +1,77 @@
---
title: Configure segments
linkTitle: Segments
description: Configure your site for segmented rendering.
categories: []
keywords: []
---
{{< new-in 0.124.0 />}}
> [!note]
> The `segments` configuration applies only to segmented rendering. While it controls when content is rendered, it doesn't restrict access to Hugo's complete object graph (sites and pages), which remains fully available.
Segmented rendering offers several advantages:
- Faster builds: Process large sites more efficiently.
- Rapid development: Render only a subset of your site for quicker iteration.
- Scheduled rebuilds: Rebuild specific sections at different frequencies (e.g., home page and news hourly, full site weekly).
- Targeted output: Generate specific output formats (like JSON for search indexes).
## Segment definition
Each segment is defined by include and exclude filters:
- Filters: Each segment has zero or more exclude filters and zero or more include filters.
- Matchers: Each filter contains one or more field [glob](g) matchers.
- Logic: Matchers within a filter use AND logic. Filters within a section (include or exclude) use OR logic.
## Filter fields
Available fields for filtering:
kind
: (`string`) A [glob](g) pattern matching the [page kind](g). For example: ` {taxonomy,term}`.
lang
: (`string`) A [glob](g) pattern matching the [page language]. For example: `{en,de}`.
output
: (`string`) A [glob](g) pattern matching the [output format](g) of the page. For example: `{html,json}`.
path
: (`string`) A [glob](g) pattern matching the page's [logical path](g). For example: `{/books,/books/**}`.
## Example
Place broad filters, such as those for language or output format, in the excludes section. For example:
{{< code-toggle file=hugo >}}
[segments.segment1]
[[segments.segment1.excludes]]
lang = "n*"
[[segments.segment1.excludes]]
lang = "en"
output = "rss"
[[segments.segment1.includes]]
kind = "{home,term,taxonomy}"
[[segments.segment1.includes]]
path = "{/docs,/docs/**}"
{{< /code-toggle >}}
## Rendering segments
Render specific segments using the [`renderSegments`] configuration or the `--renderSegments` flag:
```bash
hugo --renderSegments segment1
```
You can configure multiple segments and use a comma-separated list with `--renderSegments` to render them all.
```bash
hugo --renderSegments segment1,segment2
```
[`renderSegments`]: /configuration/all/#rendersegments
[page language]: /methods/page/language/

View File

@@ -0,0 +1,128 @@
---
title: Configure server
linkTitle: Server
description: Configure the development server.
categories: []
keywords: []
---
These settings are exclusive to Hugo's development server, so a dedicated [configuration directory] for development, where the server is configured accordingly, is the recommended approach.
[configuration directory]: /configuration/introduction/#configuration-directory
```text
project/
└── config/
├── _default/
│ └── hugo.toml
└── development/
└── server.toml
```
## Default settings
The development server defaults to redirecting to `/404.html` for any requests to URLs that don't exist. See the [404 errors](#404-errors) section below for details.
{{< code-toggle config=server />}}
force
: (`bool`) Whether to force a redirect even if there is existing content in the path.
from
: (`string`) A [glob](g) pattern matching the requested URL. Either `from` or `fromRE` must be set. If both `from` and `fromRe` are specified, the URL must match both patterns.
fromHeaders
: {{< new-in 0.144.0 />}}
: (`map[string][string]`) Headers to match for the redirect. This maps the HTTP header name to a [glob](g) pattern with values to match. If the map is empty, the redirect will always be triggered.
fromRe
: {{< new-in 0.144.0 />}}
: (`string`) A [regular expression](g) used to match the requested URL. Either `from` or `fromRE` must be set. If both `from` and `fromRe` are specified, the URL must match both patterns. Capture groups from the regular expression are accessible in the `to` field as `$1`, `$2`, and so on.
status
: (`string`) The HTTP status code to use for the redirect. A status code of 200 will trigger a URL rewrite.
to
: (`string`) The URL to forward the request to.
## Headers
Include headers in every server response to facilitate testing, particularly for features like Content Security Policies.
[Content Security Policies]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
{{< code-toggle file=config/development/server >}}
[[headers]]
for = "/**"
[headers.values]
X-Frame-Options = "DENY"
X-XSS-Protection = "1; mode=block"
X-Content-Type-Options = "nosniff"
Referrer-Policy = "strict-origin-when-cross-origin"
Content-Security-Policy = "script-src localhost:1313"
{{< /code-toggle >}}
## Redirects
You can define simple redirect rules.
{{< code-toggle file=config/development/server >}}
[[redirects]]
from = "/myspa/**"
to = "/myspa/"
status = 200
force = false
{{< /code-toggle >}}
The `200` status code in this example triggers a URL rewrite, which is typically the desired behavior for [single-page applications].
[single-page applications]: https://en.wikipedia.org/wiki/Single-page_application
## 404 errors
The development server defaults to redirecting to /404.html for any requests to URLs that don't exist.
{{< code-toggle config=server />}}
If you've already defined other redirects, you must explicitly add the 404 redirect.
{{< code-toggle file=config/development/server >}}
[[redirects]]
force = false
from = "/**"
to = "/404.html"
status = 404
{{< /code-toggle >}}
For multilingual sites, ensure the default language 404 redirect is defined last:
{{< code-toggle file=config/development/server >}}
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = false
[[redirects]]
from = '/fr/**'
to = '/fr/404.html'
status = 404
[[redirects]] # Default language must be last.
from = '/**'
to = '/404.html'
status = 404
{{< /code-toggle >}}
When the default language is served from a subdirectory:
{{< code-toggle file=config/development/server >}}
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = true
[[redirects]]
from = '/fr/**'
to = '/fr/404.html'
status = 404
[[redirects]] # Default language must be last.
from = '/**'
to = '/en/404.html'
status = 404
{{< /code-toggle >}}

View File

@@ -0,0 +1,52 @@
---
title: Configure services
linkTitle: Services
description: Configure embedded templates.
categories: []
keywords: []
---
Hugo provides [embedded templates](g) to simplify site and content creation. Some of these templates are configurable. For example, the embedded Google Analytics template requires a Google tag ID.
This is the default configuration:
{{< code-toggle config=services />}}
disqus.shortname
: (`string`) The `shortname` used with the Disqus commenting system. See&nbsp;[details](/templates/embedded/#disqus). To access this value from a template:
```go-html-template
{{ .Site.Config.Services.Disqus.Shortname }}
```
googleAnalytics.id
: (`string`) The Google tag ID for Google Analytics 4 properties. See&nbsp;[details](/templates/embedded/#google-analytics). To access this value from a template:
```go-html-template
{{ .Site.Config.Services.GoogleAnalytics.ID }}
```
instagram.accessToken <!-- TODO: Remove when no longer in docs.yaml -->
: (`string`) Do not use. Deprecated in [v0.123.0]. The embedded `instagram` shortcode no longer uses this setting.
instagram.disableInlineCSS <!-- TODO: Remove when no longer in docs.yaml -->
: (`bool`) Do not use. Deprecated in [v0.123.0]. The embedded `instagram` shortcode no longer uses this setting.
rss.limit
: (`int`) The maximum number of items to include in an RSS feed. Set to `-1` for no limit. Default is `-1`. See&nbsp;[details](/templates/rss/). To access this value from a template:
```go-html-template
{{ .Site.Config.Services.RSS.Limit }}
```
twitter.disableInlineCSS <!-- TODO: Remove when no longer in docs.yaml -->
: (`bool`) Do not use. Deprecated in [v0.141.0]. Use the `x` shortcode instead.
x.disableInlineCSS
: (`bool`) Whether to disable the inline CSS rendered by the embedded `x` shortode. See&nbsp;[details](/shortcodes/x/#privacy). Default is `false`. To access this value from a template:
```go-html-template
{{ .Site.Config.Services.X.DisableInlineCSS }}
[v0.141.0]: https://github.com/gohugoio/hugo/releases/tag/v0.141.0
[v0.123.0]: https://github.com/gohugoio/hugo/releases/tag/v0.123.0

View File

@@ -0,0 +1,24 @@
---
title: Configure sitemap
linkTitle: Sitemap
description: Configure the sitemap.
categories: []
keywords: []
---
These are the default sitemap configuration values. They apply to all pages unless overridden in front matter.
{{< code-toggle config=sitemap />}}
changefreq
: (`string`) How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. With the default value of `""` Hugo will omit this field from the sitemap. See&nbsp;[details](https://www.sitemaps.org/protocol.html#changefreqdef).
disable
: {{< new-in 0.125.0 />}}
: (`bool`) Whether to disable page inclusion. Default is `false`. Set to `true` in front matter to exclude the page.
filename
: (`string`) The name of the generated file. Default is `sitemap.xml`.
priority
: (`float`) The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. With the default value of `-1` Hugo will omit this field from the sitemap. See&nbsp;[details](https://www.sitemaps.org/protocol.html#prioritydef).

View File

@@ -0,0 +1,68 @@
---
title: Configure taxonomies
linkTitle: Taxonomies
description: Configure taxonomies.
categories: []
keywords: []
---
The default configuration defines two [taxonomies](g), `categories` and `tags`.
{{< code-toggle config=taxonomies />}}
When creating a taxonomy:
- Use the singular form for the key (e.g., `category`).
- Use the plural form for the value (e.g., `categories`).
Then use the value as the key in front matter:
{{< code-toggle file=content/example.md fm=true >}}
---
title: Example
categories:
- vegetarian
- gluten-free
tags:
- appetizer
- main course
{{< /code-toggle >}}
If you do not expect to assign more than one [term](g) from a given taxonomy to a content page, you may use the singular form for both key and value:
{{< code-toggle file=hugo >}}
taxonomies:
author: author
{{< /code-toggle >}}
Then in front matter:
{{< code-toggle file=content/example.md fm=true >}}
---
title: Example
author:
- Robert Smith
{{< /code-toggle >}}
The example above illustrates that even with a single term, the value is still provided as an array.
You must explicitly define the default taxonomies to maintain them when adding a new one:
{{< code-toggle file=hugo >}}
taxonomies:
author: author
category: categories
tag: tags
{{< /code-toggle >}}
To disable the taxonomy system, use the [`disableKinds`] setting in the root of your site configuration to disable the `taxonomy` and `term` page [kinds](g).
{{< code-toggle file=hugo >}}
disableKinds = ['categories','tags']
{{< /code-toggle >}}
[`disableKinds`]: /configuration/all/#disablekinds
See the [taxonomies] section for more information.
[taxonomies]: /content-management/taxonomies/

View File

@@ -0,0 +1,36 @@
---
title: Configure ugly URLs
linkTitle: Ugly URLs
description: Configure ugly URLs.
categories: []
keywords: []
---
{{% glossary-term "ugly url" %}}&nbsp;For example:
```text
https://example.org/section/article.html
```
In its default configuration, Hugo generates [pretty URLs](g). For example:
```text
https://example.org/section/article/
```
This is the default configuration:
{{< code-toggle config=uglyURLs />}}
To generate ugly URLs for the entire site:
{{< code-toggle file=hugo >}}
uglyURLs = true
{{< /code-toggle >}}
To generate ugly URLs for specific sections of your site:
{{< code-toggle file=hugo >}}
[uglyURLs]
books = true
films = false
{{< /code-toggle >}}

View File

@@ -1,13 +0,0 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -1,17 +0,0 @@
---
_comment: Do not remove front matter.
---
| Kind | Description | Example |
|----------------|--------------------------------------------------------------------|-------------------------------------------------------------------------------|
| `home` | The landing page for the home page | `/index.html` |
| `page` | The landing page for a given page | `my-post` page (`/posts/my-post/index.html`) |
| `section` | The landing page of a given section | `posts` section (`/posts/index.html`) |
| `taxonomy` | The landing page for a taxonomy | `tags` taxonomy (`/tags/index.html`) |
| `term` | The landing page for one taxonomy's term | term `awesome` in `tags` taxonomy (`/tags/awesome/index.html`) |
Four other page kinds unrelated to content are `robotsTXT`, `RSS`, `sitemap`, and `404`. Although primarily for internal use, you can specify the name when disabling one or more page kinds on your site. For example:
{{< code-toggle file=hugo >}}
disableKinds = ['robotsTXT','404']
{{< /code-toggle >}}

View File

@@ -1,16 +1,8 @@
---
title: Content management
description: Hugo makes managing large static sites easy with support for archetypes, content types, menus, cross references, summaries, and more.
categories: []
keywords: []
menu:
docs:
identifier: content-management-in-this-section
parent: content-management
weight: 10
weight: 10
aliases: [/content/,/content/organization]
---
A static site generator needs to extend beyond front matter and a couple of templates to be both scalable and *manageable*. Hugo was designed with not only developers in mind, but also content managers and authors.

View File

@@ -1,15 +1,8 @@
---
title: Archetypes
description: An archetype is a template for new content.
categories: [content management]
keywords: [archetypes,generators,metadata,front matter]
menu:
docs:
parent: content-management
weight: 140
quicklinks:
weight: 140
toc: true
categories: []
keywords: []
aliases: [/content/archetypes/]
---
@@ -102,7 +95,7 @@ Although typically used as a front matter template, you can also use an archetyp
For example, in a documentation site you might have a section (content type) for functions. Every page within this section should follow the same format: a brief description, the function signature, examples, and notes. We can pre-populate the page to remind content authors of the standard format.
{{< code file=archetypes/functions.md >}}
````text {file="archetypes/functions.md"}
---
date: '{{ .Date }}'
draft: true
@@ -126,7 +119,7 @@ One or more practical examples, each within a fenced code block.
## Notes
Additional information to clarify as needed.
{{< /code >}}
````
Although you can include [template actions](g) within the content body, remember that Hugo evaluates these once---at the time of content creation. In most cases, place template actions in a [template](g) where Hugo evaluates the actions every time you [build](g) the site.

View File

@@ -1,18 +1,18 @@
---
title: Build options
description: Build options help define how Hugo must treat a given page when building the site.
categories: [content management,fundamentals]
keywords: [build,content,front matter, page resources]
menu:
docs:
parent: content-management
weight: 70
weight: 70
toc: true
categories: []
keywords: []
aliases: [/content/build-options/]
---
Build options are stored in a reserved front matter object named `build` with these defaults:
<!-- TODO
We deprecated the `_build` front matter key in favor of `build` in v0.145.0 on 2025-02-26. Remove footnote #1 on or after 2026-05-26 (15 months after deprecation).
-->
Build options are stored in a reserved front matter object named `build`[^1] with these defaults:
[^1]: The `_build` alias for `build` is deprecated and will be removed in a future release.
{{< code-toggle file=content/example/index.md fm=true >}}
[build]
@@ -23,49 +23,26 @@ render = 'always'
list
: When to include the page within page collections. Specify one of:
- `always`
: Include the page in _all_ page collections. For example, `site.RegularPages`, `.Pages`, etc. This is the default value.
- `local`
: Include the page in _local_ page collections. For example, `.RegularPages`, `.Pages`, etc. Use this option to create fully navigable but headless content sections.
- `never`
: Do not include the page in _any_ page collection.
- `always`: Include the page in _all_ page collections. For example, `site.RegularPages`, `.Pages`, etc. This is the default value.
- `local`: Include the page in _local_ page collections. For example, `.RegularPages`, `.Pages`, etc. Use this option to create fully navigable but headless content sections.
- `never`: Do not include the page in _any_ page collection.
publishResources
: Applicable to [page bundles], determines whether to publish the associated [page resources]. Specify one of:
- `true`
: Always publish resources. This is the default value.
- `false`
: Only publish a resource when invoking its [`Permalink`], [`RelPermalink`], or [`Publish`] method within a template.
- `true`: Always publish resources. This is the default value.
- `false`: Only publish a resource when invoking its [`Permalink`], [`RelPermalink`], or [`Publish`] method within a template.
render
: When to render the page. Specify one of:
- `always`
: Always render the page to disk. This is the default value.
- `always`: Always render the page to disk. This is the default value.
- `link`: Do not render the page to disk, but assign `Permalink` and `RelPermalink` values.
- `never`: Never render the page to disk, and exclude it from all page collections.
- `link`
: Do not render the page to disk, but assign `Permalink` and `RelPermalink` values.
- `never`
: Never render the page to disk, and exclude it from all page collections.
[page bundles]: /content-management/page-bundles/
[page resources]: /content-management/page-resources/
[`Permalink`]: /methods/resource/permalink/
[`RelPermalink`]: /methods/resource/relpermalink/
[`Publish`]: /methods/resource/publish/
{{% note %}}
Any page, regardless of its build options, will always be available by using the [`.Page.GetPage`] or [`.Site.GetPage`] method.
[`.Page.GetPage`]: /methods/page/getpage/
[`.Site.GetPage`]: /methods/site/getpage/
{{% /note %}}
> [!note]
> Any page, regardless of its build options, will always be available by using the [`.Page.GetPage`] or [`.Site.GetPage`] method.
## Example -- headless page
@@ -92,14 +69,14 @@ title = 'Headless page'
To include the content and images on the home page:
{{< code file=layouts/_default/home.html >}}
```go-html-template {file="layouts/_default/home.html"}
{{ with .Site.GetPage "/headless" }}
{{ .Content }}
{{ range .Resources.ByType "image" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
{{< /code >}}
```
The published site will have this structure:
@@ -120,8 +97,6 @@ In the example above, note that:
Create a unpublished section whose content and resources can be included in other pages.
[branch bundle]: /content-management/page-bundles/
```text
content/
├── headless/
@@ -152,7 +127,7 @@ In the front matter above, note that we have set `list` to `local` to include th
To include the content and images on the home page:
{{< code file=layouts/_default/home.html >}}
```go-html-template {file="layouts/_default/home.html"}
{{ with .Site.GetPage "/headless" }}
{{ range .Pages }}
{{ .Content }}
@@ -161,7 +136,7 @@ To include the content and images on the home page:
{{ end }}
{{ end }}
{{ end }}
{{< /code >}}
```
The published site will have this structure:
@@ -211,14 +186,14 @@ render = 'always'
To render the glossary:
{{< code file=layouts/glossary/list.html >}}
```go-html-template {file="layouts/glossary/list.html"}
<dl>
{{ range .Pages }}
<dt>{{ .Title }}</dt>
<dd>{{ .Content }}</dd>
{{ end }}
</dl>
{{< /code >}}
```
The published site will have this structure:
@@ -253,7 +228,7 @@ list = 'never'
The published site will have this structure:
```html
```text
public/
├── books/
│ ├── book-1/
@@ -296,13 +271,13 @@ title = 'Internal'
[cascade.build]
render = 'never'
list = 'never'
[cascade._target]
[cascade.target]
environment = 'production'
{{< /code-toggle >}}
The production site will have this structure:
```html
```text
public/
├── reference/
│ ├── reference-1/
@@ -318,3 +293,11 @@ public/
│ └── index.html
└── index.html
```
[`.Page.GetPage`]: /methods/page/getpage/
[`.Site.GetPage`]: /methods/site/getpage/
[`Permalink`]: /methods/resource/permalink/
[`Publish`]: /methods/resource/publish/
[`RelPermalink`]: /methods/resource/relpermalink/
[page bundles]: /content-management/page-bundles/
[page resources]: /content-management/page-resources/

View File

@@ -1,14 +1,8 @@
---
title: Comments
description: Hugo ships with an internal Disqus template, but this isn't the only commenting system that will work with your new Hugo website.
categories: [content management]
keywords: [sections,content,organization]
menu:
docs:
parent: content-management
weight: 220
weight: 220
toc: true
categories: []
keywords: []
aliases: [/extras/comments/]
---
@@ -31,9 +25,9 @@ shortname = 'your-disqus-shortname'
For many websites, this is enough configuration. However, you also have the option to set the following in the [front matter] of a single content file:
* `disqus_identifier`
* `disqus_title`
* `disqus_url`
- `disqus_identifier`
- `disqus_title`
- `disqus_url`
### Render Hugo's built-in Disqus partial template
@@ -67,7 +61,7 @@ Open-source commenting systems:
- [Talkyard](https://blog-comments.talkyard.io/)
- [Utterances](https://utteranc.es/)
[configuration]: /getting-started/configuration/
[configuration]: /configuration/
[disquspartial]: /templates/embedded/#disqus
[disqussetup]: https://disqus.com/profile/signup/
[forum]: https://discourse.gohugo.io

View File

@@ -1,14 +1,8 @@
---
title: Content adapters
description: Create content adapters to dynamically add content when building your site.
categories: [content management]
categories: []
keywords: []
menu:
docs:
parent: content-management
weight: 290
weight: 290
toc: true
---
{{< new-in 0.126.0 />}}
@@ -39,11 +33,11 @@ Each content adapter is named _content.gotmpl and uses the same [syntax] as temp
Use these methods within a content adapter.
###### AddPage
### AddPage
Adds a page to the site.
{{< code file=content/books/_content.gotmpl >}}
```go-html-template {file="content/books/_content.gotmpl"}
{{ $content := dict
"mediaType" "text/markdown"
"value" "The _Hunchback of Notre Dame_ was written by Victor Hugo."
@@ -55,13 +49,13 @@ Adds a page to the site.
"title" "The Hunchback of Notre Dame"
}}
{{ .AddPage $page }}
{{< /code >}}
```
###### AddResource
### AddResource
Adds a page resource to the site.
{{< code file=content/books/_content.gotmpl >}}
```go-html-template {file="content/books/_content.gotmpl"}
{{ with resources.Get "images/a.jpg" }}
{{ $content := dict
"mediaType" .MediaType.Type
@@ -73,42 +67,41 @@ Adds a page resource to the site.
}}
{{ $.AddResource $resource }}
{{ end }}
{{< /code >}}
```
Then retrieve the new page resource with something like:
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ with .Resources.Get "cover.jpg" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{< /code >}}
```
###### Site
### Site
Returns the `Site` to which the pages will be added.
{{< code file=content/books/_content.gotmpl >}}
```go-html-template {file="content/books/_content.gotmpl"}
{{ .Site.Title }}
{{< /code >}}
```
{{% note %}}
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".
{{% /note %}}
> [!note]
> 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
### 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](#enablealllanguages) is set. See [examples](/methods/page/store/).
{{< code file=content/books/_content.gotmpl >}}
```go-html-template {file="content/books/_content.gotmpl"}
{{ .Store.Set "key" "value" }}
{{ .Store.Get "key" }}
{{< /code >}}
```
###### EnableAllLanguages
### 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.
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.
{{< code file=content/books/_content.gotmpl >}}
```go-html-template {file="content/books/_content.gotmpl"}
{{ .EnableAllLanguages }}
{{ $content := dict
"mediaType" "text/markdown"
@@ -121,7 +114,7 @@ By default, Hugo executes the content adapter for the language defined by the _c
"title" "The Hunchback of Notre Dame"
}}
{{ .AddPage $page }}
{{< /code >}}
```
## Page map
@@ -141,11 +134,10 @@ Key|Description|Required
`path`|The page's [logical path](g) relative to the content adapter. Do not include a leading slash or file extension.|:heavy_check_mark:
`title`|The page title.|&nbsp;
{{% note %}}
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`.
{{% /note %}}
> [!note]
> 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
@@ -160,18 +152,18 @@ Key|Description|Required
`path`|The resources's [logical path](g) relative to the content adapter. Do not include a leading slash.|:heavy_check_mark:
`title`|The resource title.|&nbsp;
{{% note %}}
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`.
{{% /note %}}
> [!note]
> 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.
### Step 1
Create the content structure.
```text
content/
@@ -180,15 +172,15 @@ content/
└── _index.md
```
Step 2
: Inspect the remote data to determine how to map key-value pairs to front matter fields.
### 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>
: <https://gohugo.io/shared/examples/data/books.json>
### Step 3
Step 3
: Create the content adapter.
Create the content adapter.
{{< code file=content/books/_content.gotmpl copy=true >}}
```go-html-template {file="content/books/_content.gotmpl" copy=true}
{{/* Get remote data. */}}
{{ $data := dict }}
{{ $url := "https://gohugo.io/shared/examples/data/books.json" }}
@@ -241,12 +233,13 @@ Step 3
{{ end }}
{{ end }}
{{< /code >}}
```
Step 4
: Create a single template to render each book review.
### Step 4
{{< code file=layouts/books/single.html copy=true >}}
Create a single template to render each book review.
```go-html-template {file="layouts/books/single.html" copy=true}
{{ define "main" }}
<h1>{{ .Title }}</h1>
@@ -273,7 +266,7 @@ Step 4
{{ .Content }}
{{ end }}
{{< /code >}}
```
## Multilingual sites

View File

@@ -1,148 +0,0 @@
---
title: Links and cross references
description: Shortcodes for creating links to documents.
categories: [content management]
keywords: [cross references,references,anchors,urls]
menu:
docs:
parent: content-management
weight: 170
weight: 170
toc: true
aliases: [/extras/crossreferences/]
---
The `ref` and `relref` shortcodes display the absolute and relative permalinks to a document, respectively.
## Use of `ref` and `relref`
The `ref` and `relref` shortcodes require a single argument: the path to a content document, with or without a file extension, with or without an anchor. Paths without a leading `/` are first resolved relative to the current page, then to the remainder of the site.
```text
.
└── content
├── about
| ├── _index.md
| └── credits.md
├── pages
| ├── document1.md
| └── document2.md // has anchor #anchor
├── products
| └── index.md
└── blog
└── my-post.md
```
The pages can be referenced as follows:
```text
{{</* ref "document2" */>}} <-- From pages/document1.md, relative path
{{</* ref "document2#anchor" */>}}
{{</* ref "document2.md" */>}}
{{</* ref "document2.md#anchor" */>}}
{{</* ref "#anchor" */>}} <-- From pages/document2.md
{{</* ref "/blog/my-post" */>}} <-- From anywhere, absolute path
{{</* ref "/blog/my-post.md" */>}}
{{</* relref "document" */>}}
{{</* relref "document.md" */>}}
{{</* relref "#anchor" */>}}
{{</* relref "/blog/my-post.md" */>}}
```
`index.md` can be reference either by its path or by its containing directory without the ending `/`. `_index.md` can be referenced only by its containing directory:
```text
{{</* ref "/about" */>}} <-- References /about/_index.md
{{</* ref "/about/_index" */>}} <-- Raises REF_NOT_FOUND error
{{</* ref "/about/credits.md" */>}} <-- References /about/credits.md
{{</* ref "/products" */>}} <-- References /products/index.md
{{</* ref "/products/index" */>}} <-- References /products/index.md
```
To generate a hyperlink using `ref` or `relref` in Markdown:
```text
[About]({{</* ref "/about" */>}} "About Us")
```
Hugo emits an error or warning if a document cannot be uniquely resolved. The error behavior is configurable; see below.
### Link to another language version
Using `ref` or `relref` without specifying a language, will make the reference resolve to the language of the current content page.
To link to another language version of a document, use this syntax:
```text
{{</* relref path="document.md" lang="ja" */>}}
```
### Get another output format
To link to another Output Format of a document, use this syntax:
```text
{{</* relref path="document.md" outputFormat="rss" */>}}
```
### Heading IDs
When using Markdown document types, Hugo generates element IDs for every heading on a page. For example:
```text
## Reference
```
produces this HTML:
```html
<h2 id="reference">Reference</h2>
```
Get the permalink to a heading by appending the ID to the path when using the `ref` or `relref` shortcodes:
```text
{{</* ref "document.md#reference" */>}}
{{</* relref "document.md#reference" */>}}
```
Generate a custom heading ID by including an attribute. For example:
```text
## Reference A {#foo}
## Reference B {id="bar"}
```
produces this HTML:
```html
<h2 id="foo">Reference A</h2>
<h2 id="bar">Reference B</h2>
```
Hugo will generate unique element IDs if the same heading appears more than once on a page. For example:
```text
## Reference
## Reference
## Reference
```
produces this HTML:
```html
<h2 id="reference">Reference</h2>
<h2 id="reference-1">Reference</h2>
<h2 id="reference-2">Reference</h2>
```
## Ref and RelRef Configuration
The behavior can be configured in `hugo.toml`:
refLinksErrorLevel ("ERROR")
: When using `ref` or `relref` to resolve page links and a link cannot be resolved, it will be logged with this log level. Valid values are `ERROR` (default) or `WARNING`. Any `ERROR` will fail the build (`exit -1`).
refLinksNotFoundURL
: URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is.

View File

@@ -1,14 +1,8 @@
---
title: Data sources
description: Use local and remote data sources to augment or create content.
categories: [content management]
keywords: [data,json,toml,yaml,xml]
menu:
docs:
parent: content-management
weight: 280
weight: 280
toc: true
categories: []
keywords: []
aliases: [/extras/datafiles/,/extras/datadrivencontent/,/doc/datafiles/,/templates/data-templates/]
---
@@ -22,9 +16,8 @@ The `data` directory in the root of your project may contain one or more data fi
Hugo also merges data directories from themes and modules into this single data structure, where the `data` directory in the root of your project takes precedence.
{{% note %}}
Hugo reads the combined data structure into memory and keeps it there for the entire build. For data that is infrequently accessed, use global or page resources instead.
{{% /note %}}
> [!note]
> Hugo reads the combined data structure into memory and keeps it there for the entire build. For data that is infrequently accessed, use global or page resources instead.
Theme and module authors may wish to namespace their data files to prevent collisions. For example:
@@ -35,14 +28,11 @@ project/
└── foo.json
```
{{% note %}}
Do not place CSV files in the `data` directory. Access CSV files as page, global, or remote resources.
{{% /note %}}
> [!note]
> Do not place CSV files in the `data` directory. Access CSV files as page, global, or remote resources.
See the documentation for the [`Data`] method on a `Site` object for details and examples.
[`Data`]: /methods/site/data/
## Global resources
Use the `resources.Get` and `transform.Unmarshal` functions to access data files that exist as global resources.
@@ -65,17 +55,17 @@ See the [`transform.Unmarshal`](/functions/transform/unmarshal/#remote-resource)
Use data sources to augment existing content. For example, create a shortcode to render an HTML table from a global CSV resource.
{{< code file=assets/pets.csv >}}
```csv {file="assets/pets.csv"}
"name","type","breed","age"
"Spot","dog","Collie","3"
"Felix","cat","Malicious","7"
{{< /code >}}
```
{{< code file=content/example.md lang=text >}}
```text {file="content/example.md"}
{{</* csv-to-table "pets.csv" */>}}
{{< /code >}}
```
{{< code file=layouts/shortcodes/csv-to-table.html >}}
```go-html-template {file="layouts/shortcodes/csv-to-table.html"}
{{ with $file := .Get 0 }}
{{ with resources.Get $file }}
{{ with . | transform.Unmarshal }}
@@ -104,7 +94,7 @@ Use data sources to augment existing content. For example, create a shortcode to
{{ 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 }}
{{< /code >}}
```
Hugo renders this to:
@@ -117,4 +107,5 @@ Felix|cat|Malicious|7
Use [content adapters] to create new content.
[`Data`]: /methods/site/data/
[content adapters]: /content-management/content-adapters/

View File

@@ -1,23 +1,14 @@
---
title: Diagrams
description: Use fenced code blocks and Markdown render hooks to include diagrams in your content.
categories: [content management]
keywords: [diagrams,drawing]
menu:
docs:
parent: content-management
weight: 260
weight: 260
toc: true
categories: []
keywords: []
---
## GoAT diagrams (ASCII)
Hugo natively supports [GoAT] diagrams with an [embedded code block render hook]. This means that this code block:
[GoAT]: https://github.com/bep/goat
[embedded code block render hook]: {{% eturl render-codeblock-goat %}}
````txt
```goat
. . . .--- 1 .-- 1 / 1
@@ -48,18 +39,16 @@ Will be rendered as:
Hugo does not provide a built-in template for Mermaid diagrams. Create your own using a [code block render hook]:
[code block render hook]: /render-hooks/code-blocks/
{{< code file=layouts/_default/_markup/render-codeblock-mermaid.html >}}
```go-html-template {file="layouts/_default/_markup/render-codeblock-mermaid.html" copy=true}
<pre class="mermaid">
{{- .Inner | htmlEscape | safeHTML }}
{{ .Inner | htmlEscape | safeHTML }}
</pre>
{{ .Page.Store.Set "hasMermaid" true }}
{{< /code >}}
```
And then include this snippet at the bottom of the content template:
Then include this snippet at the _bottom_ of your base template, before the closing `body` tag:
```go-html-template
```go-html-template {file="layouts/_default/baseof.html" copy=true}
{{ if .Store.Get "hasMermaid" }}
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
@@ -70,7 +59,7 @@ And then include this snippet at the bottom of the content template:
With that you can use the `mermaid` language in Markdown code blocks:
````text
````text {copy=true}
```mermaid
sequenceDiagram
participant Alice
@@ -158,7 +147,7 @@ sequenceDiagram
Created from <https://arthursonzogni.com/Diagon/#Tree>
```goat { width=300 color="orange" }
```goat {width=300 color="orange"}
───Linux─┬─Android
├─Debian─┬─Ubuntu─┬─Lubuntu
│ │ ├─Kubuntu
@@ -173,7 +162,7 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
<https://arthursonzogni.com/Diagon/#Sequence>
```goat { class="w-40" }
```goat {class="w-40"}
┌─────┐ ┌───┐
│Alice│ │Bob│
└──┬──┘ └─┬─┘
@@ -238,7 +227,7 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
<https://arthursonzogni.com/Diagon/#Table>
```goat { class="w-80 dark-blue" }
```goat {class="w-80 dark-blue"}
┌────────────────────────────────────────────────┐
│ │
├────────────────────────────────────────────────┤
@@ -265,3 +254,7 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
│LITERAL = """" character { character } """" .│
└────────────────────────────────────────────────┘
```
[code block render hook]: /render-hooks/code-blocks/
[embedded code block render hook]: {{% eturl render-codeblock-goat %}}
[GoAT]: https://github.com/bep/goat

View File

@@ -1,14 +1,8 @@
---
title: Content formats
description: Create your content using Markdown, HTML, Emacs Org Mode, AsciiDoc, Pandoc, or reStructuredText.
categories: [content management]
keywords: [markdown,asciidoc,pandoc,content format]
menu:
docs:
parent: content-management
weight: 40
weight: 40
toc: true
categories: []
keywords: []
aliases: [/content/markdown-extras/,/content/supported-formats/,/doc/supported-formats/]
---
@@ -58,13 +52,13 @@ Hugo provides custom Markdown features including:
[Attributes]: /content-management/markdown-attributes/
[CommonMark]: https://spec.commonmark.org/current/
[Extensions]: /getting-started/configuration-markup/#goldmark-extensions
[Extensions]: /configuration/markup/#extensions
[GitHub Flavored Markdown]: https://github.github.com/gfm/
[Goldmark]: https://github.com/yuin/goldmark
[Markdown]: https://daringfireball.net/projects/markdown/
[Mathematics]: /content-management/mathematics/
[Render hooks]: /render-hooks/introduction/
[configure goldmark]: /getting-started/configuration-markup/#goldmark
[configure goldmark]: /configuration/markup/#goldmark
### HTML
@@ -98,8 +92,8 @@ hugo --logLevel info
```
[AsciiDoc]: https://asciidoc.org/
[configure the AsciiDoc renderer]: /getting-started/configuration-markup/#asciidoc
[configure asciidoc]: /getting-started/configuration-markup/#asciidoc
[configure the AsciiDoc renderer]: /configuration/markup/#asciidoc
[configure asciidoc]: /configuration/markup/#asciidoc
### Pandoc
@@ -128,14 +122,7 @@ Hugo passes these CLI flags when calling the rst2html executable:
## Classification
Content format|Media type|Identifier|File extensions
:--|:--|:--|:--
Markdown|`text/markdown`|`markdown`|`markdown`,`md`, `mdown`
HTML|`text/html`|`html`|`htm`, `html`
Emacs Org Mode|`text/org`|`org`|`org`
AsciiDoc|`text/asciidoc`|`asciidoc`|`ad`, `adoc`, `asciidoc`
Pandoc|`text/pandoc`|`pandoc`|`pandoc`, `pdc`
reStructuredText|`text/rst`|`rst`|`rst`
{{% include "/_common/content-format-table.md" %}}
When converting content to HTML, Hugo uses:

View File

@@ -1,14 +1,8 @@
---
title: Front matter
description: Use front matter to add metadata to your content.
categories: [content management]
keywords: [front matter,yaml,toml,json,metadata,archetypes]
menu:
docs:
parent: content-management
weight: 60
weight: 60
toc: true
categories: []
keywords: []
aliases: [/content/front-matter/]
---
@@ -45,216 +39,140 @@ Front matter fields may be [boolean](g), [integer](g), [float](g), [string](g),
The most common front matter fields are `date`, `draft`, `title`, and `weight`, but you can specify metadata using any of fields below.
{{% note %}}
The field names below are reserved. For example, you cannot create a custom field named `type`. Create custom fields under the `params` key. See the [parameters] section for details.
> [!note]
> The field names below are reserved. For example, you cannot create a custom field named `type`. Create custom fields under the `params` key. See the [parameters] section for details.
[parameters]: #parameters
{{% /note %}}
###### aliases
aliases
: (`string array`) An array of one or more aliases, where each alias is a relative URL that will redirect the browser to the current location. Access these values from a template using the [`Aliases`] method on a `Page` object. See the [aliases] section for details.
(`string array`) An array of one or more aliases, where each alias is a relative URL that will redirect the browser to the current location. Access these values from a template using the [`Aliases`] method on a `Page` object. See the [aliases] section for details.
build
: (`map`) A map of [build options].
[`aliases`]: /methods/page/aliases/
[aliases]: /content-management/urls/#aliases
cascade
: (`map`) A map of front matter keys whose values are passed down to the page's descendants unless overwritten by self or a closer ancestor's cascade. See the [cascade] section for details.
###### build
date
: (`string`) The date associated with the page, typically the creation date. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Date`] method on a `Page` object.
(`map`) A map of [build options].
description
: (`string`) Conceptually different than the page `summary`, the description is typically rendered within a `meta` element within the `head` element of the published HTML file. Access this value from a template using the [`Description`] method on a `Page` object.
[build options]: /content-management/build-options/
draft
: (`bool`) Whether to disable rendering unless you pass the `--buildDrafts` flag to the `hugo` command. Access this value from a template using the [`Draft`] method on a `Page` object.
###### cascade {#cascade-field}
expiryDate
: (`string`) The page expiration date. On or after the expiration date, the page will not be rendered unless you pass the `--buildExpired` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`ExpiryDate`] method on a `Page` object.
(`map`) A map of front matter keys whose values are passed down to the pages descendants unless overwritten by self or a closer ancestors cascade. See the [cascade] section for details.
headless
: (`bool`) Applicable to [leaf bundles], whether to set the `render` and `list` [build options] to `never`, creating a headless bundle of [page resources].
[cascade]: #cascade
isCJKLanguage
: (`bool`) Whether the content language is in the [CJK](g) family. This value determines how Hugo calculates word count, and affects the values returned by the [`WordCount`], [`FuzzyWordCount`], [`ReadingTime`], and [`Summary`] methods on a `Page` object.
###### date
keywords
: (`string array`) An array of keywords, typically rendered within a `meta` element within the `head` element of the published HTML file, or used as a [taxonomy](g) to classify content. Access these values from a template using the [`Keywords`] method on a `Page` object.
(`string`) The date associated with the page, typically the creation date. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Date`] method on a `Page` object.
lastmod
: (`string`) The date that the page was last modified. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Lastmod`] method on a `Page` object.
[`date`]: /methods/page/date/
layout
: (`string`) Provide a template name to [target a specific template], overriding the default [template lookup order]. Set the value to the base file name of the template, excluding its extension. Access this value from a template using the [`Layout`] method on a `Page` object.
###### description
linkTitle
: (`string`) Typically a shorter version of the `title`. Access this value from a template using the [`LinkTitle`] method on a `Page` object.
(`string`) Conceptually different than the page `summary`, the description is typically rendered within a `meta` element within the `head` element of the published HTML file. Access this value from a template using the [`Description`] method on a `Page` object.
markup
: (`string`) An identifier corresponding to one of the supported [content formats]. If not provided, Hugo determines the content renderer based on the file extension.
[`description`]: /methods/page/description/
menus
: (`string`, `string array`, or `map`) If set, Hugo adds the page to the given menu or menus. See the [menus] page for details.
###### draft
modified
: Alias to [lastmod](#lastmod).
(`bool`)
If `true`, the page will not be rendered unless you pass the `--buildDrafts` flag to the `hugo` command. Access this value from a template using the [`Draft`] method on a `Page` object.
outputs
: (`string array`) The [output formats] to render. See [configure outputs] for more information.
[`draft`]: /methods/page/draft/
params
: {{< new-in 0.123.0 />}}
: (`map`) A map of custom [page parameters].
###### expiryDate
pubdate
: Alias to [publishDate](#publishdate).
(`string`) The page expiration date. On or after the expiration date, the page will not be rendered unless you pass the `--buildExpired` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`ExpiryDate`] method on a `Page` object.
publishDate
: (`string`) The page publication date. Before the publication date, the page will not be rendered unless you pass the `--buildFuture` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`PublishDate`] method on a `Page` object.
[`expirydate`]: /methods/page/expirydate/
published
: Alias to [publishDate](#publishdate).
###### headless
resources
: (`map array`) An array of maps to provide metadata for [page resources].
(`bool`) Applicable to [leaf bundles], if `true` this value sets the `render` and `list` [build options] to `never`, creating a headless bundle of [page resources].
sitemap
: (`map`) A map of sitemap options. See the [sitemap templates] page for details. Access these values from a template using the [`Sitemap`] method on a `Page` object.
[leaf bundles]: /content-management/page-bundles/#leaf-bundles
[page resources]: /content-management/page-resources/
slug
: (`string`) Overrides the last segment of the URL path. Not applicable to section pages. See the [URL management] page for details. Access this value from a template using the [`Slug`] method on a `Page` object.
###### isCJKLanguage
summary
: (`string`) Conceptually different than the page `description`, the summary either summarizes the content or serves as a teaser to encourage readers to visit the page. Access this value from a template using the [`Summary`] method on a `Page` object.
(`bool`) Set to `true` if the content language is in the [CJK](g) family. This value determines how Hugo calculates word count, and affects the values returned by the [`WordCount`], [`FuzzyWordCount`], [`ReadingTime`], and [`Summary`] methods on a `Page` object.
title
: (`string`) The page title. Access this value from a template using the [`Title`] method on a `Page` object.
[`fuzzywordcount`]: /methods/page/wordcount/
[`readingtime`]: /methods/page/readingtime/
[`summary`]: /methods/page/summary/
[`wordcount`]: /methods/page/wordcount/
translationKey
: (`string`) An arbitrary value used to relate two or more translations of the same page, useful when the translated pages do not share a common path. Access this value from a template using the [`TranslationKey`] method on a `Page` object.
###### keywords
type
: (`string`) The [content type](g), overriding the value derived from the top-level section in which the page resides. Access this value from a template using the [`Type`] method on a `Page` object.
(`string array`) An array of keywords, typically rendered within a `meta` element within the `head` element of the published HTML file, or used as a [taxonomy](g) to classify content. Access these values from a template using the [`Keywords`] method on a `Page` object.
unpublishdate
: Alias to [expirydate](#expirydate).
[`keywords`]: /methods/page/keywords/
url
: (`string`) Overrides the entire URL path. Applicable to regular pages and section pages. See the [URL management] page for details.
<!-- Added in v0.123.0 but purposefully omitted from documentation. -->
<!--
kind
: The kind of page, e.g. "page", "section", "home" etc. This is usually derived from the content path.
-->
weight
: (`int`) The page [weight](g), used to order the page within a [page collection](g). Access this value from a template using the [`Weight`] method on a `Page` object.
<!-- Added in v0.123.0 but purposefully omitted from documentation. -->
<!--
lang
: The language code for this page. This is usually derived from the module mount or filename.
-->
###### lastmod
(`string`) The date that the page was last modified. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Lastmod`] method on a `Page` object.
[`lastmod`]: /methods/page/date/
###### layout
(`string`) Provide a template name to [target a specific template], overriding the default [template lookup order]. Set the value to the base file name of the template, excluding its extension. Access this value from a template using the [`Layout`] method on a `Page` object.
[`layout`]: /methods/page/layout/
[template lookup order]: /templates/lookup-order/
[target a specific template]: /templates/lookup-order/#target-a-template
###### linkTitle
(`string`) Typically a shorter version of the `title`. Access this value from a template using the [`LinkTitle`] method on a `Page` object.
[`linktitle`]: /methods/page/linktitle/
###### markup
(`string`) An identifier corresponding to one of the supported [content formats]. If not provided, Hugo determines the content renderer based on the file extension.
[content formats]: /content-management/formats/#classification
###### menus
(`string`, `string array`, or `map`) If set, Hugo adds the page to the given menu or menus. See the [menus] page for details.
[menus]: /content-management/menus/#define-in-front-matter
###### modified
Alias to [lastmod](#lastmod).
###### outputs
(`string array`) The [output formats] to render.
[output formats]: /templates/output-formats/
<!-- Added in v0.123.0 but purposefully omitted from documentation. -->
<!--
path
: The canonical page path.
-->
###### params
{{< new-in 0.123.0 />}}
(`map`) A map of custom [page parameters].
[page parameters]: #parameters
###### pubdate
Alias to [publishDate](#publishdate).
###### publishDate
(`string`) The page publication date. Before the publication date, the page will not be rendered unless you pass the `--buildFuture` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`PublishDate`] method on a `Page` object.
[`publishdate`]: /methods/page/publishdate/
###### published
Alias to [publishDate](#publishdate).
###### resources
(`map array`) An array of maps to provide metadata for [page resources].
[page-resources]: /content-management/page-resources/#page-resources-metadata
###### sitemap
(`map`) A map of sitemap options. See the [sitemap templates] page for details. Access these values from a template using the [`Sitemap`] method on a `Page` object.
[sitemap templates]: /templates/sitemap/
[`sitemap`]: /methods/page/sitemap/
###### slug
(`string`) Overrides the last segment of the URL path. Not applicable to section pages. See the [URL management] page for details. Access this value from a template using the [`Slug`] method on a `Page` object.
[`slug`]: /methods/page/slug/
[URL management]: /content-management/urls/#slug
###### summary
(`string`) Conceptually different than the page `description`, the summary either summarizes the content or serves as a teaser to encourage readers to visit the page. Access this value from a template using the [`Summary`] method on a `Page` object.
[`Summary`]: /methods/page/summary/
###### title
(`string`) The page title. Access this value from a template using the [`Title`] method on a `Page` object.
[`aliases`]: /methods/page/aliases/
[`date`]: /methods/page/date/
[`description`]: /methods/page/description/
[`draft`]: /methods/page/draft/
[`expirydate`]: /methods/page/expirydate/
[`fuzzywordcount`]: /methods/page/wordcount/
[`keywords`]: /methods/page/keywords/
[`lastmod`]: /methods/page/date/
[`layout`]: /methods/page/layout/
[`linktitle`]: /methods/page/linktitle/
[`publishdate`]: /methods/page/publishdate/
[`readingtime`]: /methods/page/readingtime/
[`sitemap`]: /methods/page/sitemap/
[`slug`]: /methods/page/slug/
[`summary`]: /methods/page/summary/
[`title`]: /methods/page/title/
###### translationKey
(`string`) An arbitrary value used to relate two or more translations of the same page, useful when the translated pages do not share a common path. Access this value from a template using the [`TranslationKey`] method on a `Page` object.
[`translationkey`]: /methods/page/translationkey/
###### type
(`string`) The [content type](g), overriding the value derived from the top level section in which the page resides. Access this value from a template using the [`Type`] method on a `Page` object.
[`type`]: /methods/page/type/
###### unpublishdate
Alias to [expirydate](#expirydate).
###### url
(`string`) Overrides the entire URL path. Applicable to regular pages and section pages. See the [URL management] page for details.
###### weight
(`int`) The page [weight](g), used to order the page within a [page collection](g). Access this value from a template using the [`Weight`] method on a `Page` object.
[`weight`]: /methods/page/weight/
[`wordcount`]: /methods/page/wordcount/
[aliases]: /content-management/urls/#aliases
[build options]: /content-management/build-options/
[cascade]: #cascade-1
[configure outputs]: /configuration/outputs/#outputs-per-page
[content formats]: /content-management/formats/#classification
[leaf bundles]: /content-management/page-bundles/#leaf-bundles
[menus]: /content-management/menus/#define-in-front-matter
[output formats]: /configuration/output-formats/
[page parameters]: #parameters
[page resources]: /content-management/page-resources/#metadata
[sitemap templates]: /templates/sitemap/
[target a specific template]: /templates/lookup-order/#target-a-template
[template lookup order]: /templates/lookup-order/
## Parameters
@@ -286,11 +204,6 @@ Parameter|Data type|Used by these embedded templates
The embedded templates will skip a parameter if not provided in front matter, but will throw an error if the data type is unexpected.
[`opengraph.html`]: {{% eturl opengraph %}}
[`schema.html`]: {{% eturl schema %}}
[`twitter_cards.html`]: {{% eturl twitter_cards %}}
[embedded templates]: /templates/embedded/
## Taxonomies
Classify content by adding taxonomy terms to front matter. For example, with this site configuration:
@@ -324,7 +237,7 @@ You can add taxonomy terms to the front matter of any these [page kinds](g):
Access taxonomy terms from a template using the [`Params`] or [`GetTerms`] method on a `Page` object. For example:
{{< code file=layouts/_default/single.html >}}
```go-html-template {file="layouts/_default/single.html"}
{{ with .GetTerms "tags" }}
<p>Tags</p>
<ul>
@@ -333,81 +246,84 @@ Access taxonomy terms from a template using the [`Params`] or [`GetTerms`] metho
{{ end }}
</ul>
{{ end }}
{{< /code >}}
```
[`Params`]: /methods/page/params/
[`GetTerms`]: /methods/page/getterms/
## Cascade
Any [node](g) can pass down to its descendants a set of front matter values.
A [node](g) can cascade front matter values to its descendants. However, this cascading will be prevented if the descendant already defines the field, or if a closer ancestor node has already cascaded a value for that same field.
### Target specific pages
The `cascade` block can be an array with an optional `_target` keyword, allowing you to target different page sets while cascading values.
For example, to cascade a "color" parameter from the home page to all its descendants:
{{< code-toggle file=content/_index.md fm=true >}}
title ="Home"
title = 'Home'
[cascade.params]
color = 'red'
{{< /code-toggle >}}
### Target
<!-- TODO
Update the <version> and <date> below when we actually get around to deprecating _target.
We deprecated the `_target` front matter key in favor of `target` in <version> on <date>. Remove footnote #1 on or after 2026-03-10 (15 months after deprecation).
-->
The `target`[^1] keyword allows you to target specific pages or [environments](g). For example, to cascade a "color" parameter from the home page only to pages within the "articles" section, including the "articles" section page itself:
[^1]: The `_target` alias for `target` is deprecated and will be removed in a future release.
{{< code-toggle file=content/_index.md fm=true >}}
title = 'Home'
[cascade.params]
color = 'red'
[cascade.target]
path = '{/articles,/articles/**}'
{{< /code-toggle >}}
Use any combination of these keywords to target pages and/or environments:
environment
: (`string`) A [glob](g) pattern matching the build [environment](g). For example: `{staging,production}`.
kind
: (`string`) A [glob](g) pattern matching the [page kind](g). For example: ` {taxonomy,term}`.
path
: (`string`) A [glob](g) pattern matching the page's [logical path](g). For example: `{/books,/books/**}`.
### Array
Define an array of cascade parameters to apply different values to different targets. For example:
{{< code-toggle file=content/_index.md fm=true >}}
title = 'Home'
[[cascade]]
[cascade.params]
background = "yosemite.jpg"
[cascade._target]
path="/articles/**"
lang="en"
kind="page"
color = 'red'
[cascade.target]
path = '{/books/**}'
kind = 'page'
[[cascade]]
[cascade.params]
background = "goldenbridge.jpg"
[cascade._target]
kind="section"
{{</ code-toggle >}}
color = 'blue'
[cascade.target]
path = '{/films/**}'
kind = 'page'
{{< /code-toggle >}}
Use any combination of these keywords to target a set of pages:
###### path {#cascade-path}
(`string`) A [Glob](https://github.com/gobwas/glob) pattern matching the content path below /content. Expects Unix-styled slashes. Note that this is the virtual path, so it starts at the mount root. The matching supports double-asterisks so you can match for patterns like `/blog/*/**` to match anything from the third level and down.
###### kind {#cascade-kind}
(`string`) A Glob pattern matching the Page's Kind(s), e.g. "{home,section}".
###### lang {#cascade-lang}
(`string`) A Glob pattern matching the Page's language, e.g. "{en,sv}".
###### environment {#cascade-environment}
(`string`) A Glob pattern matching the build environment, e.g. "{production,development}"
Any of the above can be omitted.
{{% note %}}
With a multilingual site it may be more efficient to define the `cascade` values in your site configuration to avoid duplicating the `cascade` values on the section, taxonomy, or term page for each language.
With a multilingual site, if you choose to define the `cascade` values in front matter, you must create a section, taxonomy, or term page for each language; the `lang` keyword is ignored.
{{% /note %}}
### Example
{{< code-toggle file=content/posts/_index.md fm=true >}}
date = 2024-02-01T21:25:36-08:00
title = 'Posts'
[cascade]
[cascade.params]
banner = 'images/typewriter.jpg'
{{</ code-toggle >}}
With the above example the posts section page and its descendants will return `images/typewriter.jpg` when `.Params.banner` is invoked unless:
- Said descendant has its own `banner` value set
- Or a closer ancestor node has its own `cascade.banner` value set.
> [!note]
> For multilingual sites, defining cascade values in your site configuration is often more efficient. This avoids repeating the same cascade values on the home, section, taxonomy, or term page for each language. See&nbsp;[details](/configuration/cascade/).
>
> If you choose to define cascade values in front matter for a multilingual site, you must create a corresponding home, section, taxonomy, or term page for every language.
## Emacs Org Mode
If your [content format] is [Emacs Org Mode], you may provide front matter using Org Mode keywords. For example:
{{< code file=content/example.org lang=text >}}
```text {file="content/example.org"}
#+TITLE: Example
#+DATE: 2024-02-02T04:14:54-08:00
#+DRAFT: false
@@ -417,13 +333,13 @@ If your [content format] is [Emacs Org Mode], you may provide front matter using
#+TAGS: red
#+TAGS: blue
#+WEIGHT: 10
{{< /code >}}
```
Note that you can also specify array elements on a single line:
{{< code file=content/example.org lang=text >}}
```text {file="content/example.org"}
#+TAGS[]: red blue
{{< /code >}}
```
[content format]: /content-management/formats/
[emacs org mode]: https://orgmode.org/
@@ -432,10 +348,15 @@ Note that you can also specify array elements on a single line:
When populating a date field, whether a [custom page parameter](#parameters) or one of the four predefined fields ([`date`](#date), [`expiryDate`](#expirydate), [`lastmod`](#lastmod), [`publishDate`](#publishdate)), use one of these parsable formats:
{{% include "functions/time/_common/parsable-date-time-strings.md" %}}
{{% include "/_common/parsable-date-time-strings.md" %}}
To override the default time zone, set the [`timeZone`](https://gohugo.io/getting-started/configuration/#timezone) in your site configuration. The order of precedence for determining the time zone is:
To override the default time zone, set the [`timeZone`](/configuration/all/#timezone) in your site configuration. The order of precedence for determining the time zone is:
1. The time zone offset in the date/time string
1. The time zone specified in your site configuration
1. The `Etc/UTC` time zone
[`opengraph.html`]: {{% eturl opengraph %}}
[`schema.html`]: {{% eturl schema %}}
[`twitter_cards.html`]: {{% eturl twitter_cards %}}
[embedded templates]: /templates/embedded/

View File

@@ -1,14 +1,8 @@
---
title: Image processing
description: Resize, crop, rotate, filter, and convert images.
categories: [content management,fundamentals]
keywords: [resources,images]
menu:
docs:
parent: content-management
weight: 90
toc: true
weight: 90
categories: []
keywords: []
---
## Image resources
@@ -17,7 +11,7 @@ To process an image you must access the file as a page resource, global resource
### Page resource
A page resource is a file within a [page bundle]. A page bundle is a directory with an `index.md` or `_index.md`&nbsp;file at its root.
{{% glossary-term "page resource" %}}
```text
content/
@@ -35,7 +29,7 @@ To access an image as a page resource:
### Global resource
A global resource is a file within the `assets` directory, or within any directory [mounted] to the `assets` directory.
{{% glossary-term "global resource" %}}
```text
assets/
@@ -51,7 +45,9 @@ To access an image as a global resource:
### Remote resource
A remote resource is a file on a remote server, accessible via HTTP or HTTPS. To access an image as a remote resource:
{{% glossary-term "remote resource" %}}
To access an image as a remote resource:
```go-html-template
{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}
@@ -104,17 +100,15 @@ Example 4: Skips rendering if there's problem accessing a remote resource.
The `image` resource implements the [`Process`], [`Resize`], [`Fit`], [`Fill`], [`Crop`], [`Filter`], [`Colors`] and [`Exif`] methods.
{{% note %}}
Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the `Exif` method with the _original_ image to extract EXIF metadata from JPEG, PNG, TIFF, and WebP images.
{{% /note %}}
> [!note]
> Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the `Exif` method with the _original_ image to extract EXIF metadata from JPEG, PNG, TIFF, and WebP images.
### Process
{{< new-in 0.119.0 />}}
{{% note %}}
The `Process` method is also available as a filter, which is more effective if you need to apply multiple filters to an image. See [Process filter](/functions/images/process).
{{% /note %}}
> [!note]
> The `Process` method is also available as a filter, which is more effective if you need to apply multiple filters to an image. See [Process filter](/functions/images/process).
Process processes the image with the given specification. The specification can contain an optional action, one of `resize`, `crop`, `fit` or `fill`. This means that you can use this method instead of [`Resize`], [`Fit`], [`Fill`], or [`Crop`].
@@ -252,8 +246,6 @@ You may also access EXIF fields individually, using the [`lang.FormatNumber`] fu
Date
: (`time.Time`) Returns the image creation date/time. Format with the [`time.Format`]function.
[time.Format]: /functions/time/format/
Lat
: (`float64`) Returns the GPS latitude in degrees.
@@ -348,8 +340,6 @@ The default value is 75. You may override the default value in the [site configu
Applicable to WebP images, this option corresponds to a set of predefined encoding parameters, and is equivalent to the `-preset` flag for the [`cwebp`] encoder.
[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp
Value|Example
:--|:--
`drawing`|Hand or line drawing with high-contrast details
@@ -399,86 +389,23 @@ See [github.com/disintegration/imaging] for the complete list of resampling filt
## Image processing examples
_The photo of the sunset used in the examples below is Copyright [Bjørn Erik Pedersen](https://commons.wikimedia.org/wiki/User:Bep) (Creative Commons Attribution-Share Alike 4.0 International license)_
_The photo of the sunset used in the examples below is Copyright [Bjørn Erik Pedersen](https://bep.is) (Creative Commons Attribution-Share Alike 4.0 International license)_
{{< imgproc "sunset.jpg" "resize 300x" />}}
{{< imgproc path="sunset.jpg" spec="resize 480x" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "fill 90x120 left" />}}
{{< imgproc path="sunset.jpg" spec="fill 120x150 left" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "fill 90x120 right" />}}
{{< imgproc path="sunset.jpg" spec="fill 120x150 right" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "fit 90x90" />}}
{{< imgproc path="sunset.jpg" spec="fit 120x120" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "crop 250x250 center" />}}
{{< imgproc path="sunset.jpg" spec="crop 240x240 center" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "resize 300x q10" />}}
{{< imgproc path="sunset.jpg" spec="resize 360x q10" alt="A sunset" />}}
This is the shortcode used to generate the examples above:
## Configuration
{{< readfile file=layouts/shortcodes/imgproc.html highlight=go-html-template >}}
Call the shortcode from your Markdown like this:
```go-html-template
{{</* imgproc "sunset.jpg" "resize 300x" /*/>}}
```
{{% note %}}
Note the self-closing shortcode syntax above. You may call the `imgproc` shortcode with or without **inner content**.
{{% /note %}}
## Imaging configuration
### Processing options
Define an `imaging` section in your site configuration to set the default [image processing options](#image-processing-options).
{{< code-toggle config=imaging />}}
anchor
: See image processing options: [anchor](#anchor).
bgColor
: See image processing options: [background color](#background-color).
hint
: See image processing options: [hint](#hint).
quality
: See image processing options: [quality](#quality).
resampleFilter
: See image processing options: [resampling filter](#resampling-filter).
### EXIF data
Define an `imaging.exif` section in your site configuration to control the availability of EXIF data.
{{< code-toggle file=hugo >}}
[imaging.exif]
includeFields = ""
excludeFields = ""
disableDate = false
disableLatLong = false
{{< /code-toggle >}}
disableDate
: Hugo extracts the image creation date/time into `.Date`. Set this to `true` to disable. Default is `false`.
disableLatLong
: Hugo extracts the GPS latitude and longitude into `.Lat` and `.Long`. Set this to `true` to disable. Default is `false`.
excludeFields
: Regular expression matching the EXIF tags to exclude from the `.Tags` collection. Default is&nbsp;`""`.
includeFields
: Regular expression matching the EXIF tags to include in the `.Tags` collection. Default is&nbsp;`""`. To include all available tags, set this value to&nbsp;`".*"`.
{{% note %}}
To improve performance and decrease cache size, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`.
To control tag availability, change the `excludeFields` or `includeFields` settings as described above.
{{% /note %}}
See [configure imaging](/configuration/imaging).
## Smart cropping of images
@@ -486,13 +413,13 @@ By default, Hugo uses the [Smartcrop] library when cropping images with the `Cro
Examples using the sunset image from above:
{{< imgproc "sunset.jpg" "fill 200x200 smart" />}}
{{< imgproc path="sunset.jpg" spec="fill 200x200 smart" alt="A sunset" />}}
{{< imgproc "sunset.jpg" "crop 200x200 smart" />}}
{{< imgproc path="sunset.jpg" spec="crop 200x200 smart" alt="A sunset" />}}
## Image processing performance consideration
Hugo caches processed images in the `resources` directory. If you include this directory in source control, Hugo will not have to regenerate the images in a CI/CD workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds.
Hugo caches processed images in the `resources` directory. If you include this directory in source control, Hugo will not have to regenerate the images in a [CI/CD](g) workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds.
If you change image processing methods or options, or if you rename or remove images, the `resources` directory will contain unused images. To remove the unused images, perform garbage collection with:
@@ -501,20 +428,20 @@ hugo --gc
```
[`anchor`]: /content-management/image-processing#anchor
[mounted]: /hugo-modules/configuration#module-configuration-mounts
[page bundle]: /content-management/page-bundles/
[`lang.FormatNumber`]: /functions/lang/formatnumber/
[filters]: /functions/images/filter/#image-filters
[github.com/disintegration/imaging]: https://github.com/disintegration/imaging#image-resizing
[Smartcrop]: https://github.com/muesli/smartcrop#smartcrop
[Exif]: https://en.wikipedia.org/wiki/Exif
[`Process`]: #process
[`Colors`]: #colors
[`Crop`]: #crop
[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp
[`Exif`]: #exif
[`Fill`]: #fill
[`Filter`]: #filter
[`Fit`]: #fit
[`lang.FormatNumber`]: /functions/lang/formatnumber/
[`Process`]: #process
[`Resize`]: #resize
[site configuration]: #processing-options
[`time.Format`]: /functions/time/format/
[`with`]: /functions/go-template/with/
[EXIF]: https://en.wikipedia.org/wiki/Exif
[filters]: /functions/images/filter/#image-filters
[github.com/disintegration/imaging]: https://github.com/disintegration/imaging#image-resizing
[site configuration]: /configuration/imaging/
[Smartcrop]: https://github.com/muesli/smartcrop#smartcrop

View File

@@ -1,14 +1,8 @@
---
title: Markdown attributes
description: Use Markdown attributes to add HTML attributes when rendering Markdown to HTML.
categories: [content management]
keywords: [goldmark,markdown]
menu:
docs:
parent: content-management
weight: 240
weight: 240
toc: true
categories: []
keywords: []
---
## Overview

View File

@@ -2,15 +2,8 @@
title: Mathematics in Markdown
linkTitle: Mathematics
description: Include mathematical equations and expressions in Markdown using LaTeX markup.
categories: [content management]
keywords: [katex,latex,math,mathjax,typesetting]
menu:
docs:
parent: content-management
weight: 270
weight: 270
toc: true
math: true
categories: []
keywords: []
---
{{< new-in 0.122.0 />}}
@@ -43,19 +36,16 @@ Equations and expressions can be displayed inline with other text, or as standal
Whether an equation or expression appears inline, or as a block, depends on the delimiters that surround the mathematical markup. Delimiters are defined in pairs, where each pair consists of an opening and closing delimiter. The opening and closing delimiters may be the same, or different.
{{% note %}}
You can configure Hugo to render mathematical markup on the client side using the MathJax or KaTeX display engine, or you can render the markup with the [`transform.ToMath`] function while building your site.
The first approach is described below.
[`transform.ToMath`]: /functions/transform/tomath/
{{% /note %}}
> [!note]
> You can configure Hugo to render mathematical markup on the client side using the MathJax or KaTeX display engine, or you can render the markup with the [`transform.ToMath`] function while building your site.
>
> The first approach is described below.
## Setup
Follow these instructions to include mathematical equations and expressions in your Markdown using LaTeX markup.
###### Step 1
### Step 1
Enable and configure the Goldmark [passthrough extension] in your site configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves.
@@ -73,11 +63,10 @@ math = true
The configuration above enables mathematical rendering on every page unless you set the `math` parameter to `false` in front matter. To enable mathematical rendering as needed, set the `math` parameter to `false` in your site configuration, and set the `math` parameter to `true` in front matter. Use this parameter in your base template as shown in [Step 3].
{{% note %}}
The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration and JavaScript, you will need to double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting.
See the [inline delimiters](#inline-delimiters) section for details.
{{% /note %}}
> [!note]
> The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration and JavaScript, you will need to double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting.
>
> See the [inline delimiters](#inline-delimiters) section for details.
To disable passthrough of inline snippets, omit the `inline` key from the configuration:
@@ -94,11 +83,11 @@ block = [['@@', '@@']]
inline = [['@', '@']]
{{< /code-toggle >}}
###### Step 2
### Step 2
Create a partial template to load MathJax or KaTeX. The example below loads MathJax, or you can use KaTeX as described in the [engines](#engines) section.
{{< code file=layouts/partials/math.html copy=true >}}
```go-html-template {file="layouts/partials/math.html" copy=true}
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<script>
MathJax = {
@@ -111,15 +100,15 @@ Create a partial template to load MathJax or KaTeX. The example below loads Math
},
};
</script>
{{< /code >}}
```
The delimiters above must match the delimiters in your site configuration.
###### Step 3
### Step 3
Conditionally call the partial template from the base template.
{{< code file=layouts/_default/baseof.html >}}
```go-html-template {file="layouts/_default/baseof.html"}
<head>
...
{{ if .Param "math" }}
@@ -127,15 +116,15 @@ Conditionally call the partial template from the base template.
{{ end }}
...
</head>
{{< /code >}}
```
The example above loads the partial template if you have set the `math` parameter in front matter to `true`. If you have not set the `math` parameter in front matter, the conditional statement falls back to the `math` parameter in your site configuration.
###### Step 4
### Step 4
Include mathematical equations and expressions in Markdown using LaTeX markup.
{{< code file=content/math-examples.md copy=true >}}
```text {file="content/math-examples.md" copy=true}
This is an inline \(a^*=x-b^*\) equation.
These are block equations:
@@ -157,7 +146,7 @@ $$ a^*=x-b^* $$
$$
a^*=x-b^*
$$
{{< /code >}}
```
If you set the `math` parameter to `false` in your site configuration, you must set the `math` parameter to `true` in front matter. For example:
@@ -178,23 +167,21 @@ If you add the `$...$` delimiter pair to your configuration and JavaScript, you
A \\$5 bill _saved_ is a \\$5 bill _earned_.
```
{{% note %}}
If you use the `$...$` delimiter pair for inline equations, and occasionally use the&nbsp;`$`&nbsp;symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation](https://github.com/KaTeX/KaTeX/issues/437).
{{% /note %}}
> [!note]
> If you use the `$...$` delimiter pair for inline equations, and occasionally use the&nbsp;`$`&nbsp;symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation](https://github.com/KaTeX/KaTeX/issues/437).
## Engines
MathJax and KaTeX are open-source JavaScript display engines. Both engines are fast, but at the time of this writing MathJax v3.2.2 is slightly faster than KaTeX v0.16.11.
{{% note %}}
If you use the `$...$` delimiter pair for inline equations, and occasionally use the&nbsp;`$`&nbsp;symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation](https://github.com/KaTeX/KaTeX/issues/437).
See the [inline delimiters](#inline-delimiters) section for details.
{{% /note %}}
> [!note]
> If you use the `$...$` delimiter pair for inline equations, and occasionally use the&nbsp;`$`&nbsp;symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation](https://github.com/KaTeX/KaTeX/issues/437).
>
>See the [inline delimiters](#inline-delimiters) section for details.
To use KaTeX instead of MathJax, replace the partial template from [Step 2] with this:
{{< code file=layouts/partials/math.html copy=true >}}
```go-html-template {file="layouts/partials/math.html" copy=true}
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css"
@@ -226,7 +213,7 @@ To use KaTeX instead of MathJax, replace the partial template from [Step 2] with
});
});
</script>
{{< /code >}}
```
The delimiters above must match the delimiters in your site configuration.
@@ -242,10 +229,10 @@ $$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
As shown in [Step 2] above, MathJax supports chemical equations without additional configuration. To add chemistry support to KaTeX, enable the mhchem extension as described in the KaTeX [documentation](https://katex.org/docs/libs).
[`transform.ToMath`]: /functions/transform/tomath/
[KaTeX]: https://katex.org/
[LaTeX]: https://www.latex-project.org/
[MathJax]: https://www.mathjax.org/
[Step 1]: #step-1
[passthrough extension]: /configuration/markup/#passthrough
[Step 2]: #step-2
[Step 3]: #step-3
[passthrough extension]: /getting-started/configuration-markup/#passthrough

View File

@@ -1,14 +1,8 @@
---
title: Menus
description: Create menus by defining entries, localizing each entry, and rendering the resulting data structure.
categories: [content management]
keywords: [menus]
menu:
docs:
parent: content-management
weight: 190
weight: 190
toc: true
description: Create menus by defining entries, localizing each entry, and rendering the resulting data structure.
categories: []
keywords: []
aliases: [/extras/menus/]
---
@@ -28,9 +22,8 @@ There are three ways to define menu entries:
1. In front matter
1. In site configuration
{{% note %}}
Although you can use these methods in combination when defining a menu, the menu will be easier to conceptualize and maintain if you use one method throughout the site.
{{% /note %}}
> [!note]
> Although you can use these methods in combination when defining a menu, the menu will be easier to conceptualize and maintain if you use one method throughout the site.
## Define automatically
@@ -62,39 +55,16 @@ menus = ['main','footer']
Access the entry with `site.Menus.main` and `site.Menus.footer` in your templates. See [menu templates] for details.
{{% note %}}
The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`.
{{% /note %}}
> [!note]
> The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`.
### Properties {#properties-front-matter}
### Properties
Use these properties when defining menu entries in front matter:
identifier
: (`string`) Required when two or more menu entries have the same `name`, or when localizing the `name` using translation tables. Must start with a letter, followed by letters, digits, or underscores.
{{% include "/_common/menu-entry-properties.md" %}}
name
: (`string`) The text to display when rendering the menu entry.
params
: (`map`) User-defined properties for the menu entry.
parent
: (`string`) The `identifier` of the parent menu entry. If `identifier` is not defined, use `name`. Required for child entries in a nested menu.
post
: (`string`) The HTML to append when rendering the menu entry.
pre
: (`string`) The HTML to prepend when rendering the menu entry.
title
: (`string`) The HTML `title` attribute of the rendered menu entry.
weight
: (`int`) A non-zero integer indicating the entry's position relative the root of the menu, or to its parent for a child entry. Lighter entries float to the top, while heavier entries sink to the bottom.
### Example {#example-front-matter}
### Example
This front matter menu entry demonstrates some of the available properties:
@@ -112,111 +82,7 @@ Access the entry with `site.Menus.main` in your templates. See [menu templates]
## Define in site configuration
To define entries for the "main" menu:
{{< code-toggle file=hugo >}}
[[menus.main]]
name = 'Home'
pageRef = '/'
weight = 10
[[menus.main]]
name = 'Products'
pageRef = '/products'
weight = 20
[[menus.main]]
name = 'Services'
pageRef = '/services'
weight = 30
{{< /code-toggle >}}
This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details.
To define entries for the "footer" menu:
{{< code-toggle file=hugo >}}
[[menus.footer]]
name = 'Terms'
pageRef = '/terms'
weight = 10
[[menus.footer]]
name = 'Privacy'
pageRef = '/privacy'
weight = 20
{{< /code-toggle >}}
This creates a menu structure that you can access with `site.Menus.footer` in your templates. See [menu templates] for details.
{{% note %}}
The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`.
{{% /note %}}
### Properties {#properties-site-configuration}
{{% note %}}
The [properties available to entries defined in front matter] are also available to entries defined in site configuration.
[properties available to entries defined in front matter]: /content-management/menus/#properties-front-matter
{{% /note %}}
Each menu entry defined in site configuration requires two or more properties:
- Specify `name` and `pageRef` for internal links
- Specify `name` and `url` for external links
pageRef
: (`string`) The logical path of the target page, relative to the `content` directory. Omit language code and file extension. Required for *internal* links.
Kind|pageRef
:--|:--
home|`/`
page|`/books/book-1`
section|`/books`
taxonomy|`/tags`
term|`/tags/foo`
url
: (`string`) Required for *external* links.
### Example {#example-site-configuration}
This nested menu demonstrates some of the available properties:
{{< code-toggle file=hugo >}}
[[menus.main]]
name = 'Products'
pageRef = '/products'
weight = 10
[[menus.main]]
name = 'Hardware'
pageRef = '/products/hardware'
parent = 'Products'
weight = 1
[[menus.main]]
name = 'Software'
pageRef = '/products/software'
parent = 'Products'
weight = 2
[[menus.main]]
name = 'Services'
pageRef = '/services'
weight = 20
[[menus.main]]
name = 'Hugo'
pre = '<i class="fa fa-heart"></i>'
url = 'https://gohugo.io/'
weight = 30
[menus.main.params]
rel = 'external'
{{< /code-toggle >}}
This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details.
See [configure menus](/configuration/menus/).
## Localize
@@ -226,7 +92,6 @@ Hugo provides two methods to localize your menu entries. See [multilingual].
See [menu templates].
[localize]: /content-management/multilingual/#menus
[menu templates]: /templates/menu/
[multilingual]: /content-management/multilingual/#menus
[template]: /templates/menu/

View File

@@ -2,217 +2,14 @@
title: Multilingual mode
linkTitle: Multilingual
description: Localize your project for each language and region, including translations, images, dates, currencies, numbers, percentages, and collation sequence. Hugo's multilingual framework supports single-host and multihost configurations.
categories: [content management]
keywords: [multilingual,i18n,internationalization]
menu:
docs:
parent: content-management
weight: 230
weight: 230
toc: true
categories: []
keywords: []
aliases: [/content/multilingual/,/tutorials/create-a-multilingual-site/]
---
## Configure languages
## Configuration
This is the default language configuration:
{{< code-toggle config=languages />}}
In the above, `en` is the language key.
Language keys must conform to the syntax described in [RFC 5646]. For example:
- `en`
- `en-US`
Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7] are also supported. Omit the `art-x-` prefix from the language key. For example:
- `hugolang`
{{% note %}}
Private use subtags must not exceed 8 alphanumeric characters.
{{% /note %}}
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7
This is an example of a site configuration for a multilingual project. Any key not defined in a `languages` object will fall back to the global value in the root of your site configuration.
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true
[languages.de]
contentDir = 'content/de'
disabled = false
languageCode = 'de-DE'
languageDirection = 'ltr'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.de.params]
subtitle = 'Referenz, Tutorials und Erklärungen'
[languages.en]
contentDir = 'content/en'
disabled = false
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
title = 'Project Documentation'
weight = 2
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
{{< /code-toggle >}}
defaultContentLanguage
: (`string`) The project's default language key, conforming to the syntax described in [RFC 5646]. This value must match one of the defined language keys. Examples:
- `en`
- `en-GB`
- `pt-BR`
defaultContentLanguageInSubdir
: (`bool`) If `true`, Hugo renders the default language site in a subdirectory matching the `defaultContentLanguage`. Default is `false`.
contentDir
: (`string`) The `content` directory for this language. Omit if [translating by file name].
disabled
: (`bool`) If `true`, Hugo will not render content for this language. Default is `false`.
languageCode
: (`string`) The language tag as described in [RFC 5646]. This value does not affect localization or URLs. Hugo uses this value to populate the `language` element in the [built-in RSS template], and the `lang` attribute of the `html` element in the [built-in alias template]. Examples:
- `en`
- `en-GB`
- `pt-BR`
languageDirection
: (`string`) The language direction, either left-to-right (`ltr`) or right-to-left (`rtl`). Use this value in your templates with the global [`dir`] HTML attribute.
languageName
: (`string`) The language name, typically used when rendering a language switcher.
title
: (`string`) The site title for this language (optional).
weight
: (`int`) The language weight. When set to a non-zero value, this is the primary sort criteria for this language.
[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir
[built-in RSS template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml
[built-in alias template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/alias.html
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
[translating by file name]: #translation-by-file-name
### Site parameters
Set language-specific site parameters under each language's `params` key:
{{< code-toggle file=hugo >}}
[params]
color = "red"
[languages]
[languages.de]
languageCode = 'de-DE'
title = 'Projekt Dokumentation'
weight = 1
[languages.de.params]
color = 'blue'
subtitle = 'Referenz, Tutorials und Erklärungen'
[languages.en]
languageCode = 'en-US'
title = 'Project Documentation'
weight = 2
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
{{< /code-toggle >}}
When building the English site:
```go-html-template
{{ site.Params.color }} --> red
{{ site.Params.subtitle }} --> Reference, Tutorials, and Explanations
```
When building the German site:
```go-html-template
{{ site.Params.color }} --> blue
{{ site.Params.subtitle }} --> 'Referenz, Tutorials und Erklärungen'
```
### Disable a language
To disable a language within a `languages` object in your site configuration:
{{< code-toggle file=hugo >}}
[languages.es]
disabled = true
{{< /code-toggle >}}
To disable one or more languages in the root of your site configuration:
{{< code-toggle file=hugo >}}
disableLanguages = ["es", "fr"]
{{< /code-toggle >}}
To disable one or more languages using an environment variable:
```sh
HUGO_DISABLELANGUAGES="es fr" hugo
```
Note that you cannot disable the default content language.
### Configure multilingual multihost
Hugo supports multiple languages in a multihost configuration. This means you can configure a `baseURL` per `language`.
{{% note %}}
If a `baseURL` is set on the `language` level, then all languages must have one and they must all be different.
{{% /note %}}
Example:
{{< code-toggle file=hugo >}}
[languages]
[languages.en]
baseURL = 'https://en.example.org/'
languageName = 'English'
title = 'In English'
weight = 2
[languages.fr]
baseURL = 'https://fr.example.org'
languageName = 'Français'
title = 'En Français'
weight = 1
{{</ code-toggle >}}
With the above, the two sites will be generated into `public` with their own root:
```text
public
├── en
└── fr
```
**All URLs (i.e `.Permalink` etc.) will be generated from that root. So the English home page above will have its `.Permalink` set to `https://example.org/`.**
When you run `hugo server` we will start multiple HTTP servers. You will typically see something like this in the console:
```text
Web Server is available at 127.0.0.1:1313 (bind address 127.0.0.1) fr
Web Server is available at 127.0.0.1:1314 (bind address 127.0.0.1) en
Press Ctrl+C to stop
```
Live reload and `--navigateToChanged` between the servers work as expected.
See [configure languages](/configuration/languages/).
## Translate your content
@@ -232,9 +29,8 @@ Their language is __assigned__ according to the language code added as a __suffi
By having the same **path and base file name**, the content pieces are __linked__ together as translated pages.
{{% note %}}
If a file has no language code, it will be assigned the default language.
{{% /note %}}
> [!note]
> If a file has no language code, it will be assigned the default language.
### Translation by content directory
@@ -276,7 +72,7 @@ Considering the following example:
1. `/content/om.nn.md`
1. `/content/presentation/a-propos.fr.md`
{{< code-toggle >}}
{{< code-toggle file=hugo >}}
translationKey: "about"
{{< /code-toggle >}}
@@ -291,9 +87,6 @@ To localize URLs:
- For a regular page, set either [`slug`] or [`url`] in front matter
- For a section page, set [`url`] in front matter
[`slug`]: /content-management/urls/#slug
[`url`]: /content-management/urls/#url
For example, a French translation can have its own localized slug.
{{< code-toggle file=content/about.fr.md fm=true >}}
@@ -305,24 +98,23 @@ At render, Hugo will build both `/about/` and `/fr/a-propos/` without affecting
### Page bundles
To avoid the burden of having to duplicate files, each Page Bundle inherits the resources of its linked translated pages' bundles except for the content files (Markdown files, HTML files etc...).
To avoid the burden of having to duplicate files, each Page Bundle inherits the resources of its linked translated pages' bundles except for the content files (Markdown files, HTML files etc.).
Therefore, from within a template, the page will have access to the files from all linked pages' bundles.
If, across the linked bundles, two or more files share the same basename, only one will be included and chosen as follows:
* File from current language bundle, if present.
* First file found across bundles by order of language `Weight`.
- File from current language bundle, if present.
- First file found across bundles by order of language `Weight`.
{{% note %}}
Page Bundle resources follow the same language assignment logic as content files, both by file name (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`).
{{%/ note %}}
> [!note]
> Page Bundle resources follow the same language assignment logic as content files, both by file name (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`).
## Reference translated content
To create a list of links to translated content, use a template similar to the following:
{{< code file=layouts/partials/i18nlist.html >}}
```go-html-template {file="layouts/partials/i18nlist.html"}
{{ if .IsTranslated }}
<h4>{{ i18n "translations" }}</h4>
<ul>
@@ -333,7 +125,7 @@ To create a list of links to translated content, use a template similar to the f
{{ end }}
</ul>
{{ end }}
{{< /code >}}
```
The above can be put in a `partial` (i.e., inside `layouts/partials/`) and included in any template. It will not print anything if there are no translations for a given page.
@@ -343,20 +135,18 @@ The above also uses the [`i18n` function][i18func] described in the next section
`.AllTranslations` on a `Page` can be used to list all translations, including the page itself. On the home page it can be used to build a language navigator:
{{< code file=layouts/partials/allLanguages.html >}}
```go-html-template {file="layouts/partials/allLanguages.html"}
<ul>
{{ range $.Site.Home.AllTranslations }}
<li><a href="{{ .RelPermalink }}">{{ .Language.LanguageName }}</a></li>
{{ end }}
</ul>
{{< /code >}}
```
## Translation of strings
See the [`lang.Translate`] template function.
[`lang.Translate`]: /functions/lang/translate
## Localization
The following localization examples assume your site's primary language is English, with translations to French and German.
@@ -384,7 +174,7 @@ weight = 3
With this front matter:
{{< code-toggle >}}
{{< code-toggle file=hugo >}}
date = 2021-11-03T12:34:56+01:00
{{< /code-toggle >}}
@@ -538,8 +328,6 @@ pageRef = '/services'
weight = 20
{{< /code-toggle >}}
[configuration directory]: /getting-started/configuration/#configuration-directory
### Use translation tables
When rendering the text that appears in menu each entry, the [example menu template] does this:
@@ -577,20 +365,14 @@ products = 'Produkte'
services = 'Leistungen'
{{< / code-toggle >}}
[example menu template]: /templates/menu/#example
[automatically]: /content-management/menus/#define-automatically
[in front matter]: /content-management/menus/#define-in-front-matter
[in site configuration]: /content-management/menus/#define-in-site-configuration
## Missing translations
If a string does not have a translation for the current language, Hugo will use the value from the default language. If no default value is set, an empty string will be shown.
While translating a Hugo website, it can be handy to have a visual indicator of missing translations. The [`enableMissingTranslationPlaceholders` configuration option][config] will flag all untranslated strings with the placeholder `[i18n] identifier`, where `identifier` is the id of the missing translation.
{{% note %}}
Hugo will generate your website with these missing translation placeholders. It might not be suitable for production environments.
{{% /note %}}
> [!note]
> Hugo will generate your website with these missing translation placeholders. It might not be suitable for production environments.
For merging of content from other languages (i.e. missing content translations), see [lang.Merge].
@@ -605,8 +387,8 @@ i18n|MISSING_TRANSLATION|en|wordCount
To support Multilingual mode in your themes, some considerations must be taken for the URLs in the templates. If there is more than one language, URLs must meet the following criteria:
* Come from the built-in `.Permalink` or `.RelPermalink`
* Be constructed with the [`relLangURL`] or [`absLangURL`] template function, or be prefixed with `{{ .LanguagePrefix }}`
- Come from the built-in `.Permalink` or `.RelPermalink`
- Be constructed with the [`relLangURL`] or [`absLangURL`] template function, or be prefixed with `{{ .LanguagePrefix }}`
If there is more than one language defined, the `LanguagePrefix` method will return `/en` (or whatever the current language is). If not enabled, it will be an empty string (and is therefore harmless for single-language Hugo websites).
@@ -626,19 +408,22 @@ hugo new content content/en/post/test.md
hugo new content content/de/post/test.md
```
[`abslangurl`]: /functions/urls/abslangurl/
[config]: /getting-started/configuration/
[go-i18n-source]: https://github.com/nicksnyder/go-i18n
[go-i18n]: https://github.com/nicksnyder/go-i18n
[Hugo Multilingual Part 1: Content translation]: https://regisphilibert.com/blog/2018/08/hugo-multilingual-part-1-managing-content-translation/
[`absLangURL`]: /functions/urls/abslangurl/
[`lang.Translate`]: /functions/lang/translate
[`relLangURL`]: /functions/urls/rellangurl/
[`slug`]: /content-management/urls/#slug
[`time.Format`]: /functions/time/format/
[`url`]: /content-management/urls/#url
[automatically]: /content-management/menus/#define-automatically
[config]: /configuration/
[configuration directory]: /configuration/introduction/#configuration-directory
[example menu template]: /templates/menu/#example
[i18func]: /functions/lang/translate/
[in front matter]: /content-management/menus/#define-in-front-matter
[in site configuration]: /content-management/menus/#define-in-site-configuration
[lang.FormatAccounting]: /functions/lang/formataccounting/
[lang.FormatCurrency]: /functions/lang/formatcurrency/
[lang.FormatNumber]: /functions/lang/formatnumber/
[lang.FormatNumberCustom]: /functions/lang/formatnumbercustom/
[lang.FormatPercent]: /functions/lang/formatpercent/
[lang.Merge]: /functions/lang/merge/
[menus]: /content-management/menus/
[OS environment]: /getting-started/configuration/#configure-with-environment-variables
[`rellangurl`]: /functions/urls/rellangurl/
[`time.Format`]: /functions/time/format/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

View File

@@ -2,14 +2,8 @@
title: Content organization
linkTitle: Organization
description: Hugo assumes that the same structure that works to organize your source content is used to organize the rendered site.
categories: [content management,fundamentals]
keywords: [sections,content,organization,bundle,resources]
menu:
docs:
parent: content-management
weight: 20
weight: 20
toc: true
categories: []
keywords: []
aliases: [/content/sections/]
---
@@ -71,11 +65,10 @@ The following demonstrates the relationships between your content organization a
### Index pages: `_index.md`
`_index.md` has a special role in Hugo. It allows you to add front matter and content to `home`, `section`, `taxonomy`, and `term` pages.
`_index.md` has a special role in Hugo. It allows you to add front matter and content to `home`, `section`, `taxonomy`, and `term` pages.
{{% note %}}
**Tip:** You can get a reference to the content and metadata in `_index.md` using the [`.Site.GetPage` function](/methods/page/getpage).
{{% /note %}}
> [!note]
> Access the content and metadata within an `_index.md` file by invoking the `GetPage` method on a `Site` or `Page` object.
You can create one `_index.md` for your home page and one in each of your content sections, taxonomies, and terms. The following shows typical placement of an `_index.md` that would contain content and front matter for a `posts` section list page on a Hugo website:
@@ -143,20 +136,16 @@ The `slug` is the last segment of the URL path, defined by the file name and opt
### `path`
A content's `path` is determined by the section's path to the file. The file `path`
A content's `path` is determined by the section's path to the file. The file `path`:
* is based on the path to the content's location AND
* does not include the slug
- Is based on the path to the content's location AND
- Does not include the slug
### `url`
The `url` is the entire URL path, defined by the file path and optionally overridden by a `url` value in front matter. See [URL Management](/content-management/urls/#slug) for details.
[config]: /getting-started/configuration/
[formats]: /content-management/formats/
[front matter]: /content-management/front-matter/
[getpage]: /methods/page/getpage/
[config]: /configuration/
[pretty]: /content-management/urls/#appearance
[sections]: /content-management/sections/
[single template]: /templates/types/#single
[urls]: /content-management/urls/

View File

@@ -1,14 +1,8 @@
---
title: Page bundles
description: Use page bundles to logically associate one or more resources with content.
categories: [content management]
keywords: [page,bundle,leaf,branch]
menu :
docs:
parent: content-management
weight: 30
weight: 30
toc: true
categories: []
keywords: []
---
## Introduction
@@ -33,11 +27,10 @@ leaf bundle
: A _leaf bundle_ is a directory that contains an&nbsp;`index.md`&nbsp;file and zero or more resources. Analogous to a physical leaf, a leaf bundle is at the end of a branch. It has no descendants.
branch bundle
: A _branch bundle_ is a directory that contains an&nbsp;`_index.md`&nbsp;file and zero or more resources. Analogous to a physical branch, a branch bundle may have descendants including leaf bundles and other branch bundles. Top level directories with or without `_index.md`&nbsp;files are also branch bundles. This includes the home page.
: A _branch bundle_ is a directory that contains an&nbsp;`_index.md`&nbsp;file and zero or more resources. Analogous to a physical branch, a branch bundle may have descendants including leaf bundles and other branch bundles. Top-level directories with or without `_index.md`&nbsp;files are also branch bundles. This includes the home page.
{{% note %}}
In the definitions above and the examples below, the extension of the index file depends on the [content format](g). For example, use `index.md` for Markdown content, `index.html` for HTML content, `index.adoc` for AsciiDoc content, etc.
{{% /note %}}
> [!note]
> In the definitions above and the examples below, the extension of the index file depends on the [content format](g). For example, use `index.md` for Markdown content, `index.html` for HTML content, `index.adoc` for AsciiDoc content, etc.
## Comparison
@@ -53,12 +46,6 @@ Page bundle characteristics vary by bundle type.
| Resource location | Adjacent to the index file or in a nested subdirectory | Same as a leaf bundles, but excludes descendant bundles |
| [Resource types](g) | `page`, `image`, `video`, etc. | all but `page` |
[single]: /templates/types/#single
[home]: /templates/types/#home
[section]: /templates/types/#section
[taxonomy]: /templates/types/#taxonomy
[term]: /templates/types/#term
Files with [resource type](g) `page` include content written in Markdown, HTML, AsciiDoc, Pandoc, reStructuredText, and Emacs Org Mode. In a leaf bundle, excluding the index file, these files are only accessible as page resources. In a branch bundle, these files are only accessible as content pages.
## Leaf bundles
@@ -94,13 +81,13 @@ about
my-post
: This leaf bundle contains an index file, two resources of [resource type](g) `page`, and two resources of resource type `image`.
- content-1, content-2
- content-1, content-2
These are resources of resource type `page`, accessible via the [`Resources`] method on the `Page` object. Hugo will not render these as individual pages.
These are resources of resource type `page`, accessible via the [`Resources`] method on the `Page` object. Hugo will not render these as individual pages.
- image-1, image-2
- image-1, image-2
These are resources of resource type `image`, accessible via the `Resources` method on the `Page` object
These are resources of resource type `image`, accessible via the `Resources` method on the `Page` object
my-other-post
: This leaf bundle does not contain any page resources.
@@ -108,13 +95,12 @@ my-other-post
another-leaf-bundle
: This leaf bundle does not contain any page resources.
{{% note %}}
Create leaf bundles at any depth within the `content` directory, but a leaf bundle may not contain another bundle. Leaf bundles do not have descendants.
{{% /note %}}
> [!note]
> Create leaf bundles at any depth within the `content` directory, but a leaf bundle may not contain another bundle. Leaf bundles do not have descendants.
## Branch bundles
A _branch bundle_ is a directory that contains an&nbsp;`_index.md`&nbsp;file and zero or more resources. Analogous to a physical branch, a branch bundle may have descendants including leaf bundles and other branch bundles. Top level directories with or without `_index.md`&nbsp;files are also branch bundles. This includes the home page.
A _branch bundle_ is a directory that contains an&nbsp;`_index.md`&nbsp;file and zero or more resources. Analogous to a physical branch, a branch bundle may have descendants including leaf bundles and other branch bundles. Top-level directories with or without `_index.md`&nbsp;files are also branch bundles. This includes the home page.
```text
content/
@@ -142,9 +128,8 @@ branch-bundle-1
branch-bundle-2
: This branch bundle contains an index file and a leaf bundle.
{{% note %}}
Create branch bundles at any depth within the `content` directory. Branch bundles may have descendants.
{{% /note %}}
> [!note]
> Create branch bundles at any depth within the `content` directory. Branch bundles may have descendants.
## Headless bundles
@@ -152,4 +137,9 @@ Use [build options] in front matter to create an unpublished leaf or branch bund
[`Resources`]: /methods/page/resources/
[build options]: /content-management/build-options/
[home]: /templates/types/#home
[page resources]: /content-management/page-resources/
[section]: /templates/types/#section
[single]: /templates/types/#single
[taxonomy]: /templates/types/#taxonomy
[term]: /templates/types/#term

View File

@@ -1,14 +1,8 @@
---
title: Page resources
description: Use page resources to logically associate assets with a page.
categories: [content management]
keywords: [bundle,content,resources]
menu:
docs:
parent: content-management
weight: 80
weight: 80
toc: true
categories: []
keywords: []
---
Page resources are only accessible from [page bundles](/content-management/page-bundles), those directories with `index.md` or
@@ -46,13 +40,7 @@ Use any of these methods on a `Page` object to capture page resources:
- [`Resources.GetMatch`]
- [`Resources.Match`]
Once you have captured a resource, use any of the applicable [`Resource`] methods to return a value or perform an action.
[`Resource`]: /methods/resource
[`Resources.ByType`]: /methods/page/resources#bytype
[`Resources.GetMatch`]: /methods/page/resources#getmatch
[`Resources.Get`]: /methods/page/resources#get
[`Resources.Match`]: /methods/page/resources#match
Once you have captured a resource, use any of the applicable [`Resource`] methods to return a value or perform an action.
The following examples assume this content structure:
@@ -120,16 +108,14 @@ List the titles in the data file, and throw an error if the file does not exist.
The page resources' metadata is managed from the corresponding page's front matter with an array/table parameter named `resources`. You can batch assign values using [wildcards](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm).
{{% note %}}
Resources of type `page` get `Title` etc. from their own front matter.
{{% /note %}}
> [!note]
> Resources of type `page` get `Title` etc. from their own front matter.
name
: (`string`) Sets the value returned in `Name`.
{{% note %}}
The methods `Match`, `Get` and `GetMatch` use `Name` to match the resources.
{{% /note %}}
> [!note]
> The methods `Match`, `Get` and `GetMatch` use `Name` to match the resources.
title
: (`string`) Sets the value returned in `Title`
@@ -173,9 +159,8 @@ From the example above:
- All `PDF` files will get a new `Name`. The `name` parameter contains a special placeholder [`:counter`](#the-counter-placeholder-in-name-and-title), so the `Name` will be `pdf-file-1`, `pdf-file-2`, `pdf-file-3`.
- Every docx in the bundle will receive the `word` icon.
{{% note %}}
The order matters; only the first set values of the `title`, `name` and `params` keys will be used. Consecutive parameters will be set only for the ones not already set. In the above example, `.Params.icon` is first set to `"photo"` in `src = "documents/photo_specs.pdf"`. So that would not get overridden to `"pdf"` by the later set `src = "**.pdf"` rule.
{{% /note %}}
> [!note]
> The order matters; only the first set values of the `title`, `name` and `params` keys will be used. Consecutive parameters will be set only for the ones not already set. In the above example, `.Params.icon` is first set to `"photo"` in `src = "documents/photo_specs.pdf"`. So that would not get overridden to `"pdf"` by the later set `src = "**.pdf"` rule.
### The `:counter` placeholder in `name` and `title`
@@ -210,11 +195,8 @@ the `Name` and `Title` will be assigned to the resource files as follows:
By default, with a multilingual single-host site, Hugo does not duplicate shared page resources when building the site.
{{% note %}}
This behavior is limited to Markdown content. Shared page resources for other [content formats] are copied into each language bundle.
[content formats]: /content-management/formats/
{{% /note %}}
> [!note]
> This behavior is limited to Markdown content. Shared page resources for other [content formats] are copied into each language bundle.
Consider this site configuration:
@@ -289,18 +271,12 @@ public/
This approach reduces build times, storage requirements, bandwidth consumption, and deployment times, ultimately reducing cost.
{{% note %}}
To resolve Markdown link and image destinations to the correct location, you must use link and image render hooks that capture the page resource with the [`Resources.Get`] method, and then invoke its [`RelPermalink`] method.
By default, with multilingual single-host sites, Hugo enables its [embedded link render hook] and [embedded image render hook] to resolve Markdown link and image destinations.
You may override the embedded render hooks as needed, provided they capture the resource as described above.
[embedded link render hook]: /render-hooks/links/#default
[embedded image render hook]: /render-hooks/images/#default
[`Resources.Get`]: /methods/page/resources/#get
[`RelPermalink`]: /methods/resource/relpermalink/
{{% /note %}}
> [!note]
> To resolve Markdown link and image destinations to the correct location, you must use link and image render hooks that capture the page resource with the [`Resources.Get`] method, and then invoke its [`RelPermalink`] method.
>
> By default, with multilingual single-host sites, Hugo enables its [embedded link render hook] and [embedded image render hook] to resolve Markdown link and image destinations.
>
> You may override the embedded render hooks as needed, provided they capture the resource as described above.
Although duplicating shared page resources is inefficient, you can enable this feature in your site configuration if desired:
@@ -308,3 +284,14 @@ Although duplicating shared page resources is inefficient, you can enable this f
[markup.goldmark]
duplicateResourceFiles = true
{{< /code-toggle >}}
[`RelPermalink`]: /methods/resource/relpermalink/
[`Resource`]: /methods/resource
[`Resources.ByType`]: /methods/page/resources#bytype
[`Resources.Get`]: /methods/page/resources#get
[`Resources.Get`]: /methods/page/resources/#get
[`Resources.GetMatch`]: /methods/page/resources#getmatch
[`Resources.Match`]: /methods/page/resources#match
[content formats]: /content-management/formats/
[embedded image render hook]: /render-hooks/images/#default
[embedded link render hook]: /render-hooks/links/#default

View File

@@ -0,0 +1,102 @@
---
title: Related content
description: List related content in "See Also" sections.
categories: []
keywords: []
aliases: [/content/related/,/related/,/content-management/related/]
---
Hugo uses a set of factors to identify a page's related content based on front matter parameters. This can be tuned to the desired set of indices and parameters or left to Hugo's default [related content configuration](/configuration/related-content/).
## List related content
To list up to 5 related pages (which share the same _date_ or _keyword_ parameters) is as simple as including something similar to this partial in your template:
```go-html-template {file="layouts/partials/related.html" copy=true}
{{ with site.RegularPages.Related . | first 5 }}
<p>Related content:</p>
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
```
The `Related` method takes one argument which may be a `Page` or an options map. The options map has these options:
indices
: (`slice`) The indices to search within.
document
: (`page`) The page for which to find related content. Required when specifying an options map.
namedSlices
: (`slice`) The keywords to search for, expressed as a slice of `KeyValues` using the [`keyVals`] function.
fragments
: (`slice`) A list of special keywords that is used for indices configured as type "fragments". This will match the [fragment](g) identifiers of the documents.
A fictional example using all of the above options:
```go-html-template
{{ $page := . }}
{{ $opts := dict
"indices" (slice "tags" "keywords")
"document" $page
"namedSlices" (slice (keyVals "tags" "hugo" "rocks") (keyVals "date" $page.Date))
"fragments" (slice "heading-1" "heading-2")
}}
```
> [!note]
> We improved and simplified this feature in Hugo 0.111.0. Before this we had 3 different methods: `Related`, `RelatedTo` and `RelatedIndices`. Now we have only one method: `Related`. The old methods are still available but deprecated. Also see [this blog article](https://regisphilibert.com/blog/2018/04/hugo-optmized-relashionships-with-related-content/) for a great explanation of more advanced usage of this feature.
## Index content headings
Hugo can index the headings in your content and use this to find related content. You can enable this by adding a index of type `fragments` to your `related` configuration:
{{< code-toggle file=hugo >}}
[related]
threshold = 20
includeNewer = true
toLower = false
[[related.indices]]
name = "fragmentrefs"
type = "fragments"
applyFilter = true
weight = 80
{{< /code-toggle >}}
- The `name` maps to a optional front matter slice attribute that can be used to link from the page level down to the fragment/heading level.
- If `applyFilter` is enabled, the `.HeadingsFiltered` on each page in the result will reflect the filtered headings. This is useful if you want to show the headings in the related content listing:
```go-html-template
{{ $related := .Site.RegularPages.Related . | first 5 }}
{{ with $related }}
<h2>See Also</h2>
<ul>
{{ range $i, $p := . }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ with .HeadingsFiltered }}
<ul>
{{ range . }}
{{ $link := printf "%s#%s" $p.RelPermalink .ID | safeURL }}
<li>
<a href="{{ $link }}">{{ .Title }}</a>
</li>
{{ end }}
</ul>
{{ end }}
</li>
{{ end }}
</ul>
{{ end }}
```
## Configuration
See [configure related content](/configuration/related-content/).
[`keyVals`]: /functions/collections/keyvals/

Some files were not shown because too many files have changed in this diff Show More