@@ -19,12+19,11 @@ Spelling fixes are most welcomed, and if you want to contribute longer sections
* For example, try to find short snippets that teaches people about the concept. If the example is also useful as-is (copy and paste), then great. Don't list long and similar examples just so people can use them on their sites.
* Hugo has users from all over the world, so easy to understand and [simple English](https://simple.wikipedia.org/wiki/Basic_English) is good.
-
## Edit the theme
If you want to do docs-related theme changes, the simplest way is to have both `hugoDocs` and `gohugoioTheme` cloned as sibling directories, and then run:
-```
+```sh
HUGO_MODULE_WORKSPACE=hugo.work hugo server --ignoreVendorPaths "**"
```
@@ -37,7+36,7 @@ HUGO_MODULE_WORKSPACE=hugo.work hugo server --ignoreVendorPaths "**"
To view the documentation site locally, you need to clone this repository:
+Most of the commands for **Hugo Modules** require a newer version of Go installed (see https://golang.org/dl/) and the relevant VCS client (e.g. Git, see https://git-scm.com/downloads/ ). If you have an "older" site running on Netlify, you may have to set GO_VERSION to 1.12 in your Environment settings.
+ {{- errorf "The filter passed to the %q shortcode is invalid. The filter must be one of %s. See %s" $.Name (delimit $validFilters ", " ", or ") $.Position }}
+ {{- errorf "The %q shortcode requires a positional parameter (1) containing the image processing specification. See %s" $.Name $.Position }}
+ {{- end }}
+ {{- else }}
+ {{- errorf "The %q shortcode was unable to find %q. See %s" $.Name . $.Position }}
+ {{- end }}
+{{- else }}
+ {{- errorf "The %q shortcode requires a positional parameter (0) indicating the image path, relative to the current page. See %s" $.Name $.Position }}
+Also see [Module Mounts Config](/hugo-modules/configuration/#module-configuration-mounts) for an alternative way to configure this directory (from Hugo 0.56).
description: Hugo boasts blistering speed, robust content management, and a powerful templating language making it a great fit for all kinds of static websites.
title: Hugo and the General Data Protection Regulation
linkTitle: Hugo and the GDPR
description: About how to configure your Hugo site to meet the new regulations.
-layout: single
+categories: [about]
keywords: ["GDPR", "Privacy", "Data Protection"]
menu:
docs:
parent: about
weight: 60
weight: 60
-aliases: [/privacy/,/gdpr/]
toc: true
+aliases: [/privacy/,/gdpr/]
---
General Data Protection Regulation ([GDPR](https://en.wikipedia.org/wiki/General_Data_Protection_Regulation)) is a regulation in EU law on data protection and privacy for all individuals within the European Union and the European Economic Area. It became enforceable on 25 May 2018.
-description: Hugo v0.15 and later are released under the Apache 2.0 license.
-categories: ["about hugo"]
-keywords: ["License","apache"]
+description: Hugo is released under the Apache 2.0 license.
+categories: [about]
+keywords: [license,apache]
menu:
docs:
parent: about
weight: 70
weight: 70
-aliases: [/meta/license]
-toc: true
---
-{{% note %}}
-Hugo v0.15 and later are released under the Apache 2.0 license.
-Earlier versions of Hugo were released under the [Simple Public License](https://opensource.org/license/simpl-2-0-html/).
-{{% /note %}}
-
-_Version 2.0, January 2004_ <br>
-<https://www.apache.org/licenses/LICENSE-2.0>
-
-*Terms and Conditions for use, reproduction, and distribution*
-
-## 1. Definitions
-
-“License” shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
-
-“Licensor” shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-“Legal Entity” shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, “control” means **(i)** the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
-outstanding shares, or **(iii)** beneficial ownership of such entity.
-
-“You” (or “Your”) shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-“Source” form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-“Object” form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-“Work” shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-“Derivative Works” shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-“Contribution” shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-“submitted” means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as “Not a Contribution.”
-
-“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-## 2. Grant of Copyright License
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable copyright license to reproduce, prepare Derivative Works of,
-publicly display, publicly perform, sublicense, and distribute the Work and such
-Derivative Works in Source or Object form.
-
-## 3. Grant of Patent License
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable (except as stated in this section) patent license to make, have
-made, use, offer to sell, sell, import, and otherwise transfer the Work, where
-such license applies only to those patent claims licensable by such Contributor
-that are necessarily infringed by their Contribution(s) alone or by combination
-of their Contribution(s) with the Work to which such Contribution(s) was
-submitted. If You institute patent litigation against any entity (including a
-cross-claim or counterclaim in a lawsuit) alleging that the Work or a
-Contribution incorporated within the Work constitutes direct or contributory
-patent infringement, then any patent licenses granted to You under this License
-for that Work shall terminate as of the date such litigation is filed.
-
-## 4. Redistribution
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof
-in any medium, with or without modifications, and in Source or Object form,
-provided that You meet the following conditions:
-
-* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-* **(b)** You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-* **\(c)** You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+## Apache License
-You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-## 5. Submission of Contributions
+_Version 2.0, January 2004_
+_<http://www.apache.org/licenses/>_
-Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+### Terms and Conditions for use, reproduction, and distribution
-## 6. Trademarks
+#### 1. Definitions
-This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-## 7. Disclaimer of Warranty
+“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means **(i)** the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the outstanding shares, or **(iii)** beneficial ownership of such entity.
-## 8. Limitation of Liability
+“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
-In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-## 9. Accepting Warranty or Additional Liability
+“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
+
+“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+#### 2. Grant of Copyright License
+
+Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+#### 3. Grant of Patent License
+
+Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-_END OF TERMS AND CONDITIONS_
+#### 4. Redistribution
-## APPENDIX: How to apply the Apache License to your work
+You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets `[]` replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same “printed page” as the copyright notice for easier identification within third-party archives.
+* **(a)** You must give any other recipients of the Work or Derivative Works a copy of this License; and
+* **(b)** You must cause any modified files to carry prominent notices stating that You changed the files; and
+* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+#### 5. Submission of Contributions
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+#### 6. Trademarks
-{{< code file="apache-notice.txt" >}}
-Copyright [yyyy] [name of copyright owner]
+This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+#### 7. Disclaimer of Warranty
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
- https://www.apache.org/licenses/LICENSE-2.0
+#### 8. Limitation of Liability
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-{{< /code >}}
+In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+#### 9. Accepting Warranty or Additional Liability
+
+While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
@@ -31,7+31,7 @@ Hugo has a built-in security policy that restricts access to [os/exec](https://p
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" />}}
+{{< code-toggle config=security />}}
Note that these and other configuration settings in Hugo can be overridden by the OS environment. If you want to block all remote HTTP fetching of data:
Hugo is a general-purpose website framework. Technically speaking, Hugo is a [static site generator]. Unlike systems that dynamically build a page with each visitor request, Hugo builds pages when you create or update your content. Since websites are viewed far more often than they are edited, Hugo is designed to provide an optimal viewing experience for your website's end users and an ideal writing experience for website authors.
+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.
+| `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:
@@ -53,7+53,7 @@ Hugo looks for archetypes in the `archetypes` directory in the root of your proj
For example, with this command:
-```text
+```sh
hugo new content posts/my-first-post.md
```
@@ -75,7+75,7 @@ Archetypes receive the following objects and values in [context]:
- `.Date`
- `.Type`
- `.Site` (see [details](/variables/site/))
-- `.File` (see [details](/variables/files/))
+- `.File` (see [details](/variables/file/))
As shown above, the default archetype passes `.File.ContentBaseName` as the argument to the `replace` function when populating the title in front matter.
@@ -85,8+85,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.
Subdirectories within an archetype must contain at least one file. Without a file, Hugo will not create the subdirectory when you create new content. The name and size of the file are irrelevant. The example above includes a `.gitkeep` file, an empty file commonly used to preserve otherwise empty directories in a Git repository.
-If `always`, the page will be treated as a published page, holding its dedicated output files (`index.html`, etc...) and permalink.
+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.
-Valid values are:
+ - `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`
- : The page will not be included in any page collection.
- - `always (default)`
- : The page will be rendered to disk and get a `RelPermalink` etc.
- - `link`
- : The page will be not be rendered to disk, but will get a `RelPermalink`.
+ : Do not include the page in _any_ page collection.
-#### list
+publishResources
+: Applicable to [page bundles], determines whether to publish the associated [page resources]. Specify one of:
-Valid values are:
-
- - `never`
- : The page will not be included in any page collection.
- - `always (default)`
- : The page will be included in all page collections, e.g. `site.RegularPages`, `.Pages`.
- - `local`
- : The page will be included in any _local_ page collection, e.g. `.RegularPages`, `.Pages`. One use case for this would be to create fully navigable, but headless content sections.
+ - `true`
+ : Always publish resources. This is the default value.
-#### publishResources
+ - `false`
+ : Only publish a resource when invoking its [`Permalink`], [`RelPermalink`], or [`Publish`] method within a template.
-If set to `true` (default) the [Bundle's Resources](/content-management/page-bundles) will be published.
-Setting this to `false` will still publish Resources on demand (when a resource's `.Permalink` or `.RelPermalink` is invoked from the templates) but will skip the others.
+render
+: When to render the page. Specify one of:
+
+ - `always`
+ : Always render the page to disk. This is the default value.
+
+ - `link`
+ : Do not render the page to disk, but include it in all page collections.
+
+ - `never`
+ : Never render the page to disk, and exclude it from all page collections.
+1. Hugo did not publish an HTML file for the page.
+2. Despite setting `publishResources` to `false` in front matter, Hugo published the [page resources] because we invoked the [`RelPermalink`] method on each resource. This is the expected behavior.
+
+## Example -- headless section
-#### Not publishing a page
+Create a unpublished section whose content and resources can be included in other pages.
-Project needs a "Who We Are" content file for front matter and body to be used by the homepage but nowhere else.
+1. Hugo did not publish an HTML file for the page.
+2. Despite setting `publishResources` to `false` in front matter, Hugo correctly published the [page resources] because we invoked the [`RelPermalink`] method on each resource. This is the expected behavior.
+
+## Example -- list without publishing
-Website needs to showcase a few of the hundred "testimonials" available as content files without publishing any of them.
+Publish a section page without publishing the descendant pages. For example, to create a glossary:
-To avoid setting the build options on every testimonials, one can use [`cascade`](/content-management/front-matter#front-matter-cascade) on the testimonial section's content file.
+```text
+content/
+├── glossary/
+│ ├── _index.md
+│ ├── bar.md
+│ ├── baz.md
+│ └── foo.md
+└── _index.md
+```
-{{< code-toggle >}}
-title: Testimonials
-_build:
- render: true
-cascade:
- _build:
- render: false
- list: true # default
+Set the build options in front matter, using the `cascade` keyword to "cascade" the values down to descendant pages.
+Publish a section's descendant pages without publishing the section page itself.
+
+```text
+content/
+├── books/
+│ ├── _index.md
+│ ├── book-1.md
+│ └── book-2.md
+└── _index.md
+```
+
+Set the build options in front matter:
+
+{{< code-toggle file=content/books/_index.md >}}
+title = 'Books'
+[_build]
+render = 'never'
+list = 'never'
+{{< /code-toggle >}}
+
+The published site will have this structure:
+
+```html
+public/
+├── books/
+│ ├── book-1/
+│ │ └── index.html
+│ └── book-2/
+│ └── index.html
+└── index.html
+```
+
+## Example -- conditionally hide section
+
+Consider this example. A documentation site has a team of contributors with access to 20 custom shortcodes. Each shortcode takes several arguments, and requires documentation for the contributors to reference when using them.
+
+Instead of external documentation for the shortcodes, include an "internal" section that is hidden when building the production site.
+
+```text
+content/
+├── internal/
+│ ├── shortcodes/
+│ │ ├── _index.md
+│ │ ├── shortcode-1.md
+│ │ └── shortcode-2.md
+│ └── _index.md
+├── reference/
+│ ├── _index.md
+│ ├── reference-1.md
+│ └── reference-2.md
+├── tutorials/
+│ ├── _index.md
+│ ├── tutorial-1.md
+│ └── tutorial-2.md
+└── _index.md
+```
+
+Set the build options in front matter, using the `cascade` keyword to "cascade" the values down to descendant pages, and use the `target` keyword to target the production environment.
-The behavior can, since Hugo 0.45, be configured in `hugo.toml`:
+The behavior can be configured in `hugo.toml`:
refLinksErrorLevel ("ERROR")
: When using `ref` or `relref` to resolve page links and a link cannot resolved, it will be logged with this log level. Valid values are `ERROR` (default) or `WARNING`. Any `ERROR` will fail the build (`exit -1`).
@@ -24,12+24,12 @@ The current list of content formats in Hugo:
| Name | Markup identifiers | Comment |
| ------------- | ------------- |-------------|
-| Goldmark | md, markdown, goldmark |Note that you can set the default handler of `md` and `markdown` to something else, see [Configure Markup](/getting-started/configuration-markup/).|
-|HTML|html, htm|To be treated as a content file, with layout, shortcodes etc., it must have front matter. If not, it will be copied as-is.|
+| Goldmark | `markdown`, `goldmark` |Note that you can set the default handler of `md` and `markdown` to something else, see [Configure Markup](/getting-started/configuration-markup/).|
+|HTML|`html`, `htm`|To be treated as a content file, with layout, shortcodes etc., it must have front matter. If not, it will be copied as-is.|
The `markup identifier` is fetched from either the `markup` variable in front matter or from the file extension. For markup-related configuration, see [Configure Markup](/getting-started/configuration-markup/).
@@ -59,7+59,7 @@ optional extensions like `asciidoctor-diagram` or `asciidoctor-html5s` are insta
External `asciidoctor` command requires Hugo rendering to _disk_ to a specific destination directory. It is required to run Hugo with the command option `--destination`.
{{% /note %}}
-Some Asciidoctor parameters can be customized in Hugo. See[details].
+Some Asciidoctor parameters can be customized in Hugo. See [details].
: The datetime at which the content was last modified.
linkTitle
-: Used for creating links to content; if set, Hugo defaults to using the `linkTitle` before the `title`. Hugo can also [order lists of content by `linkTitle`][bylinktitle].
+: Used for creating links to content; if set, Hugo defaults to using the `linkTitle` before the `title`.
markup
: **experimental**; specify `"rst"` for reStructuredText (requires`rst2html`) or `"md"` (default) for Markdown.
: used for [ordering your content in lists][ordering]. Lower weight gets higher precedence. So content with lower weight will come first. If set, weights should be non-zero, as 0 is interpreted as an *unset* weight.
-\<taxonomies\>
+taxonomies
: Field name of the *plural* form of the index. See `tags` and `categories` in the above front matter examples. *Note that the plural form of user-defined taxonomies cannot be the same as any of the predefined front matter variables.*
{{% note %}}
@@ -144,7+144,7 @@ You can add fields to your front matter arbitrarily to meet your needs. These us
The following fields can be accessed via `.Params.include_toc` and `.Params.show_comments`, respectively. The [Variables] section provides more information on using Hugo's page- and site-level variables in your templates.
-{{< code-toggle copy=false >}}
+{{< code-toggle >}}
include_toc: true
show_comments: false
{{</ code-toggle >}}
@@ -157,7+157,7 @@ Any node or section can pass down to descendants a set of front matter values as
The `cascade` block can be a slice with a optional `_target` keyword, allowing for multiple `cascade` values targeting different page sets.
+When making a site that supports multiple languages, defining a `[[cascade]]` is recommended to be done in [Site Config](../../getting-started/configuration/#cascade) to prevent duplication.
+
+If you instea define a `[[cascade]]` in front matter for multiple languages, an `content/XX/foo/_index.md` file needs to be made on a per-language basis, with `XX` the glob pattern matching the Page's language. In this case, the **lang** keyword is ignored.
+{{% /note %}}
+
### Example
In `content/blog/_index.md`
-{{< code-toggle copy=false >}}
+{{< code-toggle >}}
title: Blog
cascade:
banner: images/typewriter.jpg
@@ -219,13+225,12 @@ It's possible to set some options for Markdown rendering in a content's front ma
@@ -104,15+105,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 or TIFF images.
+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 or TIFF images.
{{% /note %}}
### Process
-{{< new-in "0.119.0" >}}
+{{< new-in 0.119.0 >}}
{{% note %}}
-The `Process` method is also available as a filter, which is more effective if need to apply multiple filters to an image. See [Process filter](/functions/images/#process).
+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 %}}
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`].
-Resize an image to the specified width and/or height.
+Resize an image to the given width and/or height.
If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio.
@@ -205,7+205,7 @@ Sometimes it can be useful to create the filter chain once and then reuse it.
### Colors
-{{< new-in "0.104.0" >}}
+{{< new-in 0.104.0 >}}
`.Colors` returns a slice of hex strings with the dominant colors in the image using a simple histogram method.
@@ -215,7+215,6 @@ Sometimes it can be useful to create the filter chain once and then reuse it.
This method is fast, but if you also scale down your images, it would be good for performance to extract the colors from the scaled down image.
-
### EXIF
Provides an [EXIF] object containing image metadata.
@@ -266,7+265,7 @@ You may also access EXIF fields individually, using the [`lang.FormatNumber`] fu
## Image processing options
-The [`Resize`], [`Fit`], [`Fill`], and [`Crop`] methods accept a space-separated, case-insensitive list of options. The order of the options within the list is irrelevant.
+The [`Resize`], [`Fit`], [`Fill`], and [`Crop`] methods accept a space-delimited, case-insensitive list of options. The order of the options within the list is irrelevant.
### Dimensions
@@ -347,9+346,9 @@ The default value is 75. You may override the default value in the [site configu
### Hint
-<!-- Specifies a libwebp preset, not a libwebp image hint. -->
+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.
-Applicable to WebP images, this option corresponds to a set of predefined encoding parameters.
@@ -369,7+368,7 @@ The default value is `photo`. You may override the default value in the [site co
When converting an image from a format that supports transparency (e.g., PNG) to a format that does _not_ support transparency (e.g., JPEG), you may specify the background color of the resulting image.
-Use either a 3-digit or a 6-digit hexadecimal color code (e.g., `#00f` or `#0000ff`).
+Use either a 3-digit or 6-digit hexadecimal color code (e.g., `#00f` or `#0000ff`).
The default value is `#ffffff` (white). You may override the default value in the [site configuration].
@@ -402,28+401,26 @@ See [github.com/disintegration/imaging] for the complete list of resampling filt
_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)_
: Regular expression matching the EXIF tags to include in the `.Tags` collection. Default is `""`. To include all available tags, set this value to `".*"`.
{{% note %}}
-To improve performance and decrease cache size, if you set neither `excludeFields` nor `includeFields`, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`.
+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 %}}
## Smart cropping of images
@@ -487,9+486,9 @@ By default, Hugo uses the [Smartcrop] library when cropping images with the `Cro
@@ -497,7+496,7 @@ Hugo caches processed images in the `resources` directory. If you include this d
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:
@@ -21,11+21,11 @@ Also See [Hugo Multilingual Part 1: Content translation].
This is the default language configuration:
-{{< code-toggle config="languages" />}}
+{{< code-toggle config=languages />}}
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.
subtitle = 'Reference, Tutorials, and Explanations'
{{< /code-toggle >}}
-`defaultContentLanguage`
+defaultContentLanguage
: (`string`) The project's default language tag as defined by [RFC 5646]. Must be lower case, and must match one of the defined language keys. Default is `en`. Examples:
- `en`
- `en-gb`
- `pt-br`
-`defaultContentLanguageInSubdir`
+defaultContentLanguageInSubdir
: (`bool`) If `true`, Hugo renders the default language site in a subdirectory matching the `defaultContentLanguage`. Default is `false`.
-`contentDir`
+contentDir
: (`string`) The content directory for this language. Omit if [translating by file name].
-`disabled`
+disabled
: (`bool`) If `true`, Hugo will not render content for this language. Default is `false`.
-`languageCode`
+languageCode
: (`string`) The language tag as defined by [RFC 5646]. This value may include upper and lower case characters, hyphens or underscores, and 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`
+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`
+languageName
: (`string`) The language name, typically used when rendering a language switcher.
-`title`
+title
: (`string`) The language title. When set, this overrides the site title for this language.
-`weight`
+weight
: (`int`) The language weight. When set to a non-zero value, this is the primary sort criteria for this language.
@@ -97,14+97,14 @@ subtitle = 'Reference, Tutorials, and Explanations'
### Changes in Hugo 0.112.0
-{{< new-in "0.112.0" >}}
+{{< new-in 0.112.0 >}}
In Hugo `v0.112.0` we consolidated all configuration options, and improved how the languages and their parameters are merged with the main configuration. But while testing this on Hugo sites out there, we received some error reports and reverted some of the changes in favor of deprecation warnings:
1. `site.Language.Params` is deprecated. Use `site.Params` directly.
1. Adding custom parameters to the top level language configuration is deprecated. Define custom parameters within `languages.xx.params`. See `color` in the example below.
-{{< code-toggle file=hugo copy=false >}}
+{{< code-toggle file=hugo >}}
title = "My blog"
languageCode = "en-us"
@@ -129,20+129,20 @@ In the example above, all settings except `color` below `params` map to predefin
To disable a language within a `languages` object in your site configuration:
-{{< code-toggle file="hugo" copy=false >}}
+{{< 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" copy=false >}}
+{{< code-toggle file=hugo >}}
disableLanguages = ["es", "fr"]
{{< /code-toggle >}}
To disable one or more languages using an environment variable:
-```bash
+```sh
HUGO_DISABLELANGUAGES="es fr" hugo
```
@@ -160,7+160,7 @@ If a `baseURL` is set on the `language` level, then all languages must have one
-**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.com/`.**
+**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)
-Web Server is available at 127.0.0.1:1314 (bind address 127.0.0.1)
+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
```
@@ -221,7+221,7 @@ If a file has no language code, it will be assigned the default language.
This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` parameter.
- <a href="{{ .Permalink }}">{{ .Lang }}: {{ .Title }}{{ if .IsPage }} ({{ i18n "wordCount" . }}){{ end }}</a>
+ <a href="{{ .RelPermalink }}">{{ .Lang }}: {{ .LinkTitle }}{{ if .IsPage }} ({{ i18n "wordCount" . }}){{ end }}</a>
</li>
{{ end }}
</ul>
@@ -324,10+324,10 @@ 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:
@@ -349,7+349,9 @@ Private use subtags must not exceed 8 alphanumeric characters.
### Query basic translation
-From within your templates, use the `i18n` function like this:
+From within your templates, use the [`i18n`] function like this:
+
+[`i18n`]: /functions/lang/translate
```go-html-template
{{ i18n "home" }}
@@ -357,7+359,7 @@ From within your templates, use the `i18n` function like this:
The function will search for the `"home"` id:
-{{< code-toggle file="i18n/en-US" >}}
+{{< code-toggle file=i18n/en-US >}}
[home]
other = "Home"
{{< /code-toggle >}}
@@ -378,7+380,7 @@ Often you will want to use the page variables in the translation strings. To do
The function will pass the `.` context to the `"wordCount"` id:
-{{< code-toggle file="i18n/en-US" >}}
+{{< code-toggle file=i18n/en-US >}}
[wordCount]
other = "This article has {{ .WordCount }} words."
{{< /code-toggle >}}
@@ -399,7+401,7 @@ To enable pluralization when translating, pass a map with a numeric `.Count` pro
The function will read `.Count` from `.ReadingTime` and evaluate whether the number is singular (`one`) or plural (`other`). After that, it will pass to `readingTime` id in `i18n/en-US.toml` file:
-{{< code-toggle file="i18n/en-US" >}}
+{{< code-toggle file=i18n/en-US >}}
[readingTime]
one = "One minute to read"
other = "{{ .Count }} minutes to read"
@@ -427,7+429,7 @@ In case you need to pass a custom data: (`(dict "Count" numeric_value_only)` is
The following localization examples assume your site's primary language is English, with translations to French and German.
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
defaultContentLanguage = 'en'
[languages]
@@ -530,7+532,7 @@ Localization of menu entries depends on how you define them:
- When you define menu entries [automatically] using the section pages menu, you must use translation tables to localize each entry.
- When you define menu entries [in front matter], they are already localized based on the front matter itself. If the front matter values are insufficient, use translation tables to localize each entry.
-- When you define menu entries [in site configuration], you must create language-specific menu entries under each language key. If the names of the menu entries are insufficent, use translation tables to localize each entry.
+- When you define menu entries [in site configuration], you must create language-specific menu entries under each language key. If the names of the menu entries are insufficient, use translation tables to localize each entry.
### Create language-specific menu entries
@@ -538,7+540,7 @@ Localization of menu entries depends on how you define them:
For a simple menu with a small number of entries, use a single configuration file. For example:
@@ -624,7+626,7 @@ The `identifier` depends on how you define menu entries:
For example, if you define menu entries in site configuration:
-{{< code-toggle file="hugo" copy=false >}}
+{{< code-toggle file=hugo >}}
[[menu.main]]
identifier = 'products'
name = 'Products'
@@ -639,7+641,7 @@ For example, if you define menu entries in site configuration:
Create corresponding entries in the translation tables:
-{{< code-toggle file="i18n/de" copy=false >}}
+{{< code-toggle file=i18n/de >}}
products = 'Produkte'
services = 'Leistungen'
{{< / code-toggle >}}
@@ -663,7+665,7 @@ For merging of content from other languages (i.e. missing content translations),
To track down missing translation strings, run Hugo with the `--printI18nWarnings` flag:
-```bash
+```sh
hugo --printI18nWarnings | grep i18n
i18n|MISSING_TRANSLATION|en|wordCount
```
@@ -677,19+679,18 @@ To support Multilingual mode in your themes, some considerations must be taken f
If there is more than one language defined, the `LanguagePrefix` variable will equal `/en` (or whatever your `CurrentLanguage` is). If not enabled, it will be an empty string (and is therefore harmless for single-language Hugo websites).
-
## Generate multilingual content with `hugo new content`
If you organize content with translations in the same directory:
-```text
+```sh
hugo new content post/test.en.md
hugo new content post/test.de.md
```
If you organize content with translations in different directories:
@@ -19,16+19,14 @@ Hugo `0.32` announced page-relative images and other resources packaged into `Pa
These terms are connected, and you also need to read about [Page Resources](/content-management/page-resources) and [Image Processing](/content-management/image-processing) to get the full picture.
The illustration shows three bundles. Note that the home page bundle cannot contain other content pages, although other files (images etc.) are allowed.
{{< /imgproc >}}
-
{{% note %}}
The bundle documentation is a **work in progress**. We will publish more comprehensive docs about this soon.
{{% /note %}}
-
## Organization of content source
In Hugo, your content should be organized in a manner that reflects the rendered website.
@@ -41,33+39,31 @@ Without any additional configuration, the following will automatically work:
-The following demonstrates the relationships between your content organization and the output URL structure for your Hugo website when it renders. These examples assume you are [using pretty URLs][pretty], which is the default behavior for Hugo. The examples also assume a key-value of `baseURL = "https://example.com"` in your [site's configuration file][config].
+The following demonstrates the relationships between your content organization and the output URL structure for your Hugo website when it renders. These examples assume you are [using pretty URLs][pretty], which is the default behavior for Hugo. The examples also assume a key-value of `baseURL = "https://example.org"` in your [site's configuration file][config].
### Index pages: `_index.md`
`_index.md` has a special role in Hugo. It allows you to add front matter and content to your [list templates][lists]. These templates include those for [section templates], [taxonomy templates], [taxonomy terms templates], and your [homepage template].
{{% note %}}
-**Tip:** You can get a reference to the content and metadata in `_index.md` using the [`.Site.GetPage` function](/functions/getpage/).
+**Tip:** You can get a reference to the content and metadata in `_index.md` using the [`.Site.GetPage` function](/methods/page/getpage).
{{% /note %}}
You can create one `_index.md` for your homepage and one in each of your content sections, taxonomies, and taxonomy 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:
-
```txt
. url
. ⊢--^-⊣
@@ -88,17+84,15 @@ At build, this will output to the following destination with the associated valu
⊢--------^---------⊣⊢-^-⊣
permalink
⊢----------^-------------⊣
-https://example.com/posts/index.html
+https://example.org/posts/index.html
```
The [sections] can be nested as deeply as you want. The important thing to understand is that to make the section tree fully navigational, at least the lower-most section must include a content file. (i.e. `_index.md`).
-
### Single pages in sections
Single content files in each of your sections will be rendered as [single page templates][singles]. Here is an example of a single `post` within `posts`:
-
```txt
path ("posts/my-first-hugo-post.md")
. ⊢-----------^------------⊣
@@ -117,10+111,9 @@ When Hugo builds your site, the content will be output to the following destinat
The following concepts provide more insight into the relationship between your project's organization and the default Hugo behavior when building output for the website.
@@ -147,7+140,7 @@ The `url` is the entire URL path, defined by the file path and optionally overri
@@ -184,7+183,8 @@ The counter starts at 1 the first time they are used in either `name` or `title`
For example, if a bundle has the resources `photo_specs.pdf`, `other_specs.pdf`, `guide.pdf` and `checklist.pdf`, and the front matter has specified the `resources` as:
@@ -18,13+18,13 @@ Hugo uses a set of factors to identify a page's related content based on front m
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 single page template:
@@ -33,22+33,25 @@ To list up to 5 related pages (which share the same _date_ or _keyword_ paramete
The `Related` method takes one argument which may be a `Page` or a options map. The options map have these options:
indices
-: The indices to search in.
+: (`slice`) The indices to search within.
document
-: The document to search for related content for.
+: (`page`) The page for which to find related content. Required when specifying an options map.
namedSlices
-: The keywords to search for.
+: (`slice`) The keywords to search for, expressed as a slice of `KeyValues` using the [`keyVals`] function.
fragments
-: Fragments holds a a list of special keywords that is used for indices configured as type "fragments". This will match the fragment identifiers of the documents.
+: (`slice`) A list of special keywords that is used for indices configured as type "fragments". This will match the [fragment] identifiers of the documents.
+
+[fragment]: /getting-started/glossary/#fragment
+[`keyVals`]: /functions/collections/keyvals/
A fictional example using all of the above options:
@@ -57,16+60,16 @@ A fictional example using all of the above options:
```
{{% note %}}
-We improved and simplified this feature in Hugo 0.111.0. Before this we had 3 different methods: `Related`, `RelatedTo` and `RelatedIndicies`. 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.
+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.
{{% /note %}}
## Index content headings in related content
-{{< new-in "0.111.0" >}}
+{{< new-in 0.111.0 >}}
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:
@@ -113,7+116,7 @@ Hugo provides a sensible default configuration of Related Content, but you can f
Without any `related` configuration set on the project, Hugo's Related Content methods will use the following.
-{{< code-toggle config="related" />}}
+{{< code-toggle config=related />}}
Custom configuration should be set using the same syntax.
@@ -124,37+127,36 @@ If you add a `related` configuration section, you need to add a complete configu
### Top level configuration options
threshold
-: A value between 0-100. Lower value will give more, but maybe not so relevant, matches.
+: (`int`) A value between 0-100. Lower value will give more, but maybe not so relevant, matches.
includeNewer
-: Set to true 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.
+: (`bool`) Set to `true` 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.
toLower
-: Set to true to lower case keywords in both the indexes and the queries. This may give more accurate results at a slight performance penalty. Note that this can also be set per index.
+: (`bool`) Set to `true` to lower case keywords in both the indexes and the queries. This may give more accurate results at a slight performance penalty. Note that this can also be set per index.
### Configuration options per index
name
-: 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.
+: (`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
-: {{< new-in "0.111.0" >}}. One of `basic`(default) or `fragments`.
+type {{< new-in 0.111.0 >}}
+: (`string`) One of `basic`(default) or `fragments`.
-applyFilter
-: {{< new-in "0.111.0" >}}. Apply a `type` specific filter to the result of a search. This is currently only used for the `fragments` type.
+applyFilter {{< new-in 0.111.0 >}}
+: (`string`) Apply a `type` specific filter to the result of a search. This is currently only used for the `fragments` type.
weight
-: 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.
-
+: (`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.
-cardinalityThreshold (default 0)
-: {{< new-in "0.111.0" >}}. A percentage (0-100) used to remove common keywords from the index. As an example, setting this to 50 will remove all keywords that are used in more than 50% of the documents in the index.
+cardinalityThreshold {{< new-in 0.111.0 >}}
+: (`int`) A percentage (0-100) used to remove common keywords from the index. As an example, setting this to `50` will remove all keywords that are used in more than 50% of the documents in the index. Default is `0`.
pattern
-: 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.
+: (`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.
@@ -77,7+77,7 @@ With the file structure from the [example above](#overview):
1. The articles/2022 and articles/2023 directories do not have list pages; they are not sections.
-1. The list page for the products section, by default, includes product-1 and product-2, but not their descendant pages. To include descendant pages, use the `.RegularPagesRecursive` collection instead of the `.Pages` collection in the list template. See[details](/variables/page/#page-collections).
+1. The list page for the products section, by default, includes product-1 and product-2, but not their descendant pages. To include descendant pages, use the `.RegularPagesRecursive` collection instead of the `.Pages` collection in the list template. See [details](/variables/page/#page-collections).
1. All directories in the products section have list pages; each directory is a section.
@@ -106,8+106,7 @@ If you need to use a different template for a subsection, specify `type` and/or
## Ancestors and descendants
-A section has one or more ancestors (including the home page), and zero or more descendants. With the file structure from the [example above](#overview):
-
+A section has one or more ancestors (including the home page), and zero or more descendants. With the file structure from the [example above](#overview):
```text
content/products/product-1/benefits/benefit-1.md
@@ -117,16+116,16 @@ The content file (benefit-1.md) has four ancestors: benefits, product-1, product
For example, use the `.Ancestors` method to render breadcrumb navigation.
@@ -58,7+58,6 @@ and a new line with a "quoted string".` */>}}
Shortcodes using the `%` as the outer-most delimiter will be fully rendered when sent to the content renderer. This means that the rendered output from a shortcode can be part of the page's table of contents, footnotes, etc.
-
### Shortcodes without markdown
The `<` character indicates that the shortcode's inner content does *not* need further rendering. Often shortcodes without Markdown include internal HTML:
Gets a value from the current `Page's` parameters set in front matter, with a fallback to the site parameter value. It will log an `ERROR` if the parameter with the given key could not be found in either.
-```bash
+```sh
{{</* param testparam */>}}
```
@@ -261,7+260,7 @@ Since `testparam` is a parameter defined in front matter of this page with the v
To access deeply nested parameters, use "dot syntax", e.g:
-```bash
+```sh
{{</* param "my.nested.param" */>}}
```
@@ -289,7+288,7 @@ Read a more extensive description of `ref` and `relref` in the [cross references
Assuming that standard Hugo pretty URLs are turned on.
Copy the YouTube video ID that follows `v=` in the video's URL and pass it to the `youtube` shortcode:
-{{< code file="example-youtube-input.md" >}}
+{{< code file=example-youtube-input.md >}}
{{</* youtube w7Ft2ymGmfc */>}}
{{< /code >}}
Furthermore, you can automatically start playback of the embedded video by setting the `autoplay` parameter to `true`. Remember that you can't mix named and unnamed parameters, so you'll need to assign the yet unnamed video ID to the parameter `id`:
-For [accessibility reasons](https://dequeuniversity.com/tips/provide-iframe-titles), it's best to provide a title for your YouTube video. You can do this using the shortcode by providing a `title` parameter. If no title is provided, a default of "YouTube Video" will be used.
+For [accessibility reasons](https://dequeuniversity.com/tips/provide-iframe-titles), it's best to provide a title for your YouTube video. You can do this using the shortcode by providing a `title` parameter. If no title is provided, a default of "YouTube Video" will be used.
With the use of the `.Summary` [page variable][pagevariables], Hugo generates summaries of content to use as a short version in summary views.
## Summary splitting options
@@ -37,7+39,7 @@ The Hugo-defined summaries are set to use word count calculated by splitting the
### Manual summary splitting
-Alternatively, you may add the <code><!--more--></code> summary divider where you want to split the article.
+Alternatively, you may add the `<!--more-->` summary divider where you want to split the article.
For [Org mode content][org], use `# more` where you want to split the article.
@@ -48,42+50,42 @@ The concept of a *summary divider* is not unique to Hugo. It is also called the
{{% /note %}}
Pros
-: Freedom, precision, and improved rendering. All HTML tags and formatting are preserved.
+: Freedom, precision, and improved rendering. All HTML tags and formatting are preserved.
Cons
-: Extra work for content authors, since they need to remember to type <code><!--more--></code> (or `# more` for [org content][org]) in each content file. This can be automated by adding the summary divider below the front matter of an [archetype](/content-management/archetypes/).
+: Extra work for content authors, since they need to remember to type `<!--more-->` (or `# more` for [org content][org]) in each content file. This can be automated by adding the summary divider below the front matter of an [archetype](/content-management/archetypes/).
-{{% warning "Be Precise with the Summary Divider" %}}
-Be careful to enter <code><!--more--></code> exactly; i.e., all lowercase and with no whitespace.
+{{% note %}}
+Be careful to enter `<!--more-->` exactly; i.e., all lowercase and with no whitespace.
{{% /note %}}
### Front matter summary
-You might want your summary to be something other than the text that starts the article. In this case you can provide a separate summary in the `summary` variable of the article front matter.
+You might want your summary to be something other than the text that starts the article. In this case you can provide a separate summary in the `summary` variable of the article front matter.
Pros
-: Complete freedom of text independent of the content of the article. Markup can be used within the summary.
+: Complete freedom of text independent of the content of the article. Markup can be used within the summary.
Cons
: Extra work for content authors as they need to write an entirely separate piece of text as the summary of the article.
## Summary selection order
-Because there are multiple ways in which a summary can be specified it is useful to understand the order of selection Hugo follows when deciding on the text to be returned by `.Summary`. It is as follows:
+Because there are multiple ways in which a summary can be specified it is useful to understand the order of selection Hugo follows when deciding on the text to be returned by `.Summary`. It is as follows:
-1. If there is a <code><!--more--></code> summary divider present in the article the text up to the divider will be provided as per the manual summary split method
+1. If there is a `<!--more-->`> summary divider present in the article the text up to the divider will be provided as per the manual summary split method
2. If there is a `summary` variable in the article front matter the value of the variable will be provided as per the front matter summary method
3. The text at the start of the article will be provided as per the automatic summary split method
-{{% warning "Competing selections" %}}
-Hugo uses the _first_ of the above steps that returns text. So if, for example, your article has both `summary` variable in its front matter and a <code><!--more--></code> summary divider Hugo will use the manual summary split method.
+{{% note %}}
+Hugo uses the _first_ of the above steps that returns text. So if, for example, your article has both `summary` variable in its front matter and a `<!--more-->` summary divider Hugo will use the manual summary split method.
{{% /note %}}
## Example: first 10 articles with summaries
You can show content summaries with the following code. You could use the following snippet, for example, in a [section template].
* `linenostart=199`: starts the line number count from 199.
* `anchorlinenos`: Configure anchors on line numbers. Valid values are `true` or `false`;
* `lineanchors`: Configure a prefix for the anchors on line numbers. Will be suffixed with `-`, so linking to the line number 1 with the option `lineanchors=prefix` adds the anchor `prefix-1` to the page.
-* `hl_inline` Highlight inside a `<code>` (inline HTML element) tag. Valid values are `true` or `false`. The `code` tag will get a class with name `code-inline`. {{< new-in "0.101.0" >}}
+* `hl_inline` Highlight inside a `<code>` (inline HTML element) tag. Valid values are `true` or `false`. The `code` tag will get a class with name `code-inline`. {{< new-in 0.101.0 >}}
### Example: highlight shortcode
@@ -104,7+104,6 @@ Highlighting in code fences is enabled by default.
Let's assume you are making a website about movies. You may want to include the following taxonomies:
@@ -82,15+81,15 @@ Hugo natively supports taxonomies.
Without adding a single line to your [site configuration] file, Hugo will automatically create taxonomies for `tags` and `categories`. That would be the same as manually [configuring your taxonomies](#configure-taxonomies) as below:
-{{< code-toggle config="taxonomies" />}}
+{{< code-toggle config=taxonomies />}}
If you do not want Hugo to create any taxonomies, set `disableKinds` in your [site configuration] to the following:
-{{< code-toggle file="hugo" copy=false >}}
+{{< code-toggle file=hugo >}}
disableKinds = ["taxonomy","term"]
{{</ code-toggle >}}
-{{% page-kinds %}}
+{{% include "content-management/_common/page-kinds.md" %}}
### Default destinations
@@ -109,7+108,7 @@ Custom taxonomies other than the [defaults](#default-taxonomies) must be defined
While adding custom taxonomies, you need to put in the default taxonomies too, _if you want to keep them_.
{{% /note %}}
-{{< code-toggle file="hugo" copy=false >}}
+{{< code-toggle file=hugo >}}
[taxonomies]
tag = "tags"
category = "categories"
@@ -120,7+119,7 @@ While adding custom taxonomies, you need to put in the default taxonomies too, _
If you want to have just the default `tags` taxonomy, and remove the `categories` taxonomy for your site, you can do so by modifying the `taxonomies` value in your [site configuration].
-{{< code-toggle file="hugo" copy=false >}}
+{{< code-toggle file=hugo >}}
[taxonomies]
tag = "tags"
{{</ code-toggle >}}
@@ -129,14+128,6 @@ If you want to disable all taxonomies altogether, see the use of `disableKinds`
{{% note %}}
You can add content and front matter to your taxonomy list and taxonomy terms pages. See [Content Organization](/content-management/organization/) for more information on how to add an `_index.md` for this purpose.
-
-Much like regular pages, taxonomy list [permalinks](/content-management/urls/) are configurable, but taxonomy term page permalinks are not.
-{{% /note %}}
-
-{{% note %}}
-The configuration option `preserveTaxonomyNames` was removed in Hugo 0.55.
-
-You can now use `.Page.Title` on the relevant taxonomy node to get the original value.
{{% /note %}}
## Add taxonomies to content
@@ -151,7+142,7 @@ If you would like the ability to quickly generate content files with preconfigur
By using taxonomic weight, the same piece of content can appear in different positions in different taxonomies.
-{{% note %}}
-Currently taxonomies only support the [default `weight => date` ordering of list content](/templates/lists/#default-weight--date--linktitle--filepath). For more information, see the documentation on [taxonomy templates](/templates/taxonomy-templates/).
-{{% /note %}}
-
## Add custom metadata to a taxonomy or term
If you need to add custom metadata to your taxonomy terms, you will need to create a page for that term at `/content/<TAXONOMY>/<TERM>/_index.md` and add your metadata in its front matter. Continuing with our 'Actors' example, let's say you want to add a Wikipedia page link to each actor. Your terms pages would be something like this:
@@ -37,7+37,7 @@ He lay on his armour-like back, and if he lifted his head a little he could see
### My Subheading
-A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops
+A collection of textile samples lay spread out on the table - Samsa was a traveling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops
```
Hugo will take this Markdown and create a table of contents from `## Introduction`, `## My Heading`, and `### My Subheading` and then store it in the [page variable][pagevars]`.TableOfContents`.
@@ -48,7+48,7 @@ The built-in `.TableOfContents` variables outputs a `<nav id="TableOfContents">`
The following is an example of a very basic [single page template]:
-{{< code file="layout/_default/single.html" >}}
+{{< code file=layout/_default/single.html >}}
{{ define "main" }}
<main>
<article>
@@ -68,7+68,7 @@ The following is an example of a very basic [single page template]:
The following is a [partial template][partials] that adds slightly more logic for page-level control over your table of contents. It assumes you are using a `toc` field in your content's [front matter] that, unless specifically set to `false`, will add a TOC to any page with a `.WordCount` (see [Page Variables][pagevars]) greater than 400. This example also demonstrates how to use [conditionals] in your templating:
-{{< code file="layouts/partials/toc.html" >}}
+{{< code file=layouts/partials/toc.html >}}
{{ if and (gt .WordCount 400 ) (.Params.toc) }}
<aside>
<header>
@@ -105,8+105,9 @@ He lay on his armour-like back, and if he lifted his head a little he could see
=== My Subheading
-A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops
+A collection of textile samples lay spread out on the table - Samsa was a traveling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops
```
+
Hugo will take this AsciiDoc and create a table of contents store it in the page variable `.TableOfContents`, in the same as described for Markdown.
By default, Hugo produces pretty URLs. To generate ugly URLs, change your site configuration:
-{{< code-toggle file="hugo" copy=false >}}
+{{< code-toggle file=hugo >}}
uglyURLs = true
{{< /code-toggle >}}
@@ -314,7+314,7 @@ This is a legacy configuration option, superseded by template functions and mark
If enabled, Hugo performs a search and replace _after_ it renders the page. It searches for site-relative URLs (those with a leading slash) associated with `action`, `href`, `src`, `srcset`, and `url` attributes. It then prepends the `baseURL` to create absolute URLs.
-Hugo relies heavily on the enthusiasm and participation of the open-source community. We need your support in both its development and documentation.
-
-Hugo's contribution guidelines are [detailed in a `CONTRIBUTING.md`](https://github.com/gohugoio/hugo/blob/master/CONTRIBUTING.md) in the Hugo source repository on GitHub.
+Hugo relies heavily on the enthusiasm and participation of the open-source community. We need your support.
The `6` at the end of the command represents the number of commits that should be modified. An editor should open and present a list of last six commit messages:
```txt
-pick 80d02a1 tpl: Add hasPrefix to the template funcs' "smoke test"
+pick 80d02a1 tpl: Add hasPrefix to template function smoke test"
pick aaee038 tpl: Sort the smoke tests
pick f0dbf2c tpl: Add the other test case for hasPrefix
pick 911c35b Add "How to contribute to Hugo" tutorial
@@ -339,7+338,7 @@ In the case above we should merge the last two commits in the commit of this tut
All operations are written before the commit message. Replace "pick" with an operation. In this case `squash` or `s` for short:
```txt
-pick 80d02a1 tpl: Add hasPrefix to the template funcs' "smoke test"
+pick 80d02a1 tpl: Add hasPrefix to template function smoke test"
pick aaee038 tpl: Sort the smoke tests
pick f0dbf2c tpl: Add the other test case for hasPrefix
pick 911c35b Add "How to contribute to Hugo" tutorial
@@ -352,7+351,7 @@ We also want to rewrite the commits message of the third last commit. We forgot
You should end up with a similar setup:
```txt
-pick 80d02a1 tpl: Add hasPrefix to the template funcs' "smoke test"
+pick 80d02a1 tpl: Add hasPrefix to template function smoke test"
pick aaee038 tpl: Sort the smoke tests
pick f0dbf2c tpl: Add the other test case for hasPrefix
reword 911c35b Add "How to contribute to Hugo" tutorial
-description: Documentation is an integral part of any open source project. The Hugo documentation is as much a work in progress as the source it attempts to cover.
+title: Documentation
+description: Help us to improve the documentation by identifying issues and suggesting changes.
+We welcome corrections and improvements to the documentation. Please note that the documentation resides in its own repository, separate from the project repository.
-Step 2
-: Clone your fork.
+For corrections and improvements to the current documentation, please submit issues and pull requests to the [documentation repository].
-Step 3
-: Create a new branch with a descriptive name.
+For documentation related to a new feature, please include the documentation changes when you submit a pull request to the [project repository].
-```bash
-git checkout -b fix/typos-site-variables
-```
+## Guidelines
-Step 4
-: Make changes.
+### Markdown
-Step 5
-: Commit your changes with a descriptive commit message, typically 50 characters or less. Included the "Closes" keyword if your change addresses one or more open [issues].
+Please follow these markdown guidelines:
-```bash
-git commit -m "Fix typos on site variables page
+- Use [ATX] headings, not [setext] headings, levels 2 through 4
+- Use [fenced code blocks], not [indented code blocks]
+- Use hyphens, not asterisks, with unordered [list items]
+- Use the [note shortcode] instead of blockquotes
+- Do not mix [raw HTML] within markdown
+- Do not use bold text instead of a heading or description term (`dt`)
+- Remove consecutive blank lines (maximum of two)
+- Remove trailing spaces
-Closes #1234
-Closes #5678"
-```
+### Style
-Step 5
-: Push the new branch to your fork of the documentation repository.
+Although we do not strictly adhere to the [Microsoft Writing Style Guide], it is an excellent resource for questions related to style, grammar, and voice.
-Step 6
-: Visit the [documentation repository] and create a pull request (PR).
+Please link to the [glossary of terms] when necessary, and use the terms consistently throughout the documentation. Of special note:
-Step 7
-: A project maintainer will review your PR, and may request changes. You may delete your branch after the maintainer merges your PR.
+- The term "front matter" is two words unless you are referring to the configuration key
+- Use the word "map" instead of "dictionary"
+- Use the word "flag" instead of "option" when referring to a command line flag
-## Including sample code
+#### Page titles and headings
-{{% note %}}
-Use this syntax to include shortcodes calls within your code samples:
+Please follow these guidelines for page titles and headings:
+
+- Use sentence-style capitalization
+- Avoid markdown in headings and page titles
+- Shorter is better
+
+#### Use active voice with present tense
+
+In software documentation, passive voice is unavoidable in some cases. Please use active voice when possible.
+
+No → With Hugo you can build a static site.\
+Yes → Build a static site with Hugo.
+
+No → This will cause Hugo to generate HTML files in the public directory.\
+Yes → Hugo generates HTML files in the public directory.
+
+#### Use second person instead of third person
+
+No → Users should exercise caution when deleting files.\
+Better → You must be cautious when deleting files.\
+Best → Be cautious when deleting files.
+
+#### Avoid adverbs when possible
-`{{</*/* foo */*/>}}`\
-`{{%/*/* foo */*/%}}`
+No → Hugo is extremely fast.\
+Yes → Hugo is fast.
+
+{{% note %}}
+"It's an adverb, Sam. It's a lazy tool of a weak mind." (Outbreak, 1995).
{{% /note %}}
+#### Miscellaneous
+
+Other guidelines to consider:
+
+- Do not place list items directly under a heading; include an introductory sentence or phrase before the list.
+- Avoid use of **bold** text. Use the [note shortcode] to draw attention to important content.
+- Do not place description terms (`dt`) within backticks unless required for syntactic clarity.
+- Do not use Hugo's `ref` or `relref` shortcodes. We use a link render hook to resolve and validate link destinations, including fragments.
+- Shorter is better. If there is more than one way to do something, describe the current best practice. For example, avoid phrases such as "you can also do..." and "in older versions you had to..."
+- When including code samples, use short snippets that demonstrate the concept.
+- The Hugo user community is global; use [basic english](https://simple.wikipedia.org/wiki/Basic_English) when possible.
+
+#### Level 6 markdown headings
+
+Level 6 markdown headings are styled as `dt` elements. This was implemented to support a [glossary] with linkable terms.
+
+[glossary]: /getting-started/glossary
+
+## Code examples
+
+Indent code by two spaces. With examples of template code, include a space after opening action delimiters, and include a space before closing action delimeters.
+
### Fenced code blocks
-Include the language when using a fenced code block.
+Always include the language code when using a fenced code block:
+These shortcodes are commonly used throughout the documentation. Other shortcodes are available for specialized use.
+
+### deprecated-in
+
+Use the “deprecated-in” shortcode to indicate that a feature is deprecated:
+
+```text
+{{%/* deprecated-in 0.120.0 */%}}
+Use [`hugo.IsServer`] instead.
+
+[`hugo.IsServer`]: /functions/hugo/isserver
+{{%/* /deprecated-in */%}}
+```
+
+Rendered:
+
+{{% deprecated-in 0.120.0 %}}
+Use [`hugo.IsServer`] instead.
+
+[`hugo.IsServer`]: /functions/hugo/isserver
+{{% /deprecated-in %}}
+
+### code
+
+Use the "code" shortcode for other code examples that require a file name. See the [code examples] above. This shortcode takes these arguments:
+
+copy
+: (`bool`) Whether to display a copy-to-clipboard button. Default is `false`.
+
+file
+: (`string`) The file name to display.
+
+lang
+: (`string`) The code language. If you do not provide a `lang` argument, the code language is determined by the file extension. If the file extension is "html", sets the code language to `go-html-template`. Default is `text`.
+
+### code-toggle
-Use the `code-toggle` shortcode to display examples of site configuration, front matter, or data files. This shortcode accepts these optional parameters:
+Use the "code-toggle" shortcode to display examples of site configuration, front matter, or data files. See the [code examples] above. This shortcode takes these arguments:
copy
-: (`bool`) If `true`, displays a copy-to-clipboard button. Default is `true`.
+: (`bool`) Whether to display a copy-to-clipboard button. Default is `false`.
file
-: (`string`) The file name to display. Omit the file extension for site configuration and data file examples.
+: (`string`) The file name to display. Omit the file extension for site configuration examples.
fm
-: (`bool`) If `true`, displays the code as front matter. Default is `false`.
+: (`bool`) Whether the example is front matter. Default is `false`.
+
+### new-in
-#### Site configuration example
+Use the "new-in" shortcode to indicate a new feature:
```text
-{{</* code-toggle file="hugo" */>}}
-baseURL = 'https://example.org'
-languageCode = 'en-US'
-title = "Example Site"
-{{</* /code-toggle */>}}
+{{</* new-in 0.120.0 */>}}
```
Rendered:
-{{< code-toggle file="hugo" >}}
-baseURL = 'https://example.org'
-languageCode = 'en-US'
-title = "Example Site"
-{{< /code-toggle >}}
+{{< new-in 0.120.0 >}}
-#### Front matter example
+### note
+
+Use the "note" shortcode with `{{%/* */%}}` delimiters to call attention to important content:
+The "new in" label will be hidden if the specified version is older than a predefined threshold, based on differences in major and minor versions. See [details](https://github.com/gohugoio/hugoDocs/blob/master/layouts/shortcodes/new-in.html).
+
+## Deprecated features
+
+Use the "deprecated-in" shortcode to indicate that a feature is deprecated:
+
+{{< code file=content/something/foo.md >}}
+{{%/* deprecated-in 0.120.0 */%}}
+Use [`hugo.IsServer`] instead.
+
+[`hugo.IsServer`]: /functions/hugo/isserver
+{{%/* /deprecated-in */%}}
+{{< /code >}}
+
+When deprecating a function or method, add this to front matter:
+Set the `expiryDate` to one year from the date of deprecation, and add a brief front matter comment to explain the settings.
-Use the `note` shortcode to draw attention to content. Use the `{{%/* */%}}` notation when calling this shortcode.
+Users will be able to search for the page, but the page will not appear in any list views, including section menus.
-```text
-{{%/* note */%}}
-This is **bold** text.
-{{%/* /note */%}}
-```
+## GitHub workflow
{{% note %}}
-This is **bold** text.
+This section assumes that you have a working knowledge of Git and GitHub, and are comfortable working on the command line.
{{% /note %}}
+
+Use this workflow to create and submit pull requests.
+
+Step 1
+: Fork the [documentation repository].
+
+Step 2
+: Clone your fork.
+
+Step 3
+: Create a new branch with a descriptive name.
+
+```sh
+git checkout -b fix/typos-shortcode-templates
+```
+
+Step 4
+: Make changes.
+
+Step 5
+: Commit your changes with a descriptive commit message, typically 50 characters or less. Add the "Closes" keyword if your change addresses one or more open [issues].
+
+```sh
+git commit -m "Fix typos on the shortcode templates page
+
+Closes #1234
+Closes #5678"
+```
+
+Step 5
+: Push the new branch to your fork of the documentation repository.
+
+Step 6
+: Visit the [documentation repository] and create a pull request (PR).
+
+Step 7
+: A project maintainer will review your PR and may request changes. You may delete your branch after the maintainer merges your PR.
-description: If you've built a Hugo theme and want to contribute back to the Hugo Community, share it with us.
+title: Themes
+description: If you've built a Hugo theme and want to contribute back to the Hugo Community, please share it with us.
categories: [contribute]
-keywords: [contribute,themes,design]
+keywords: [themes]
menu:
docs:
parent: contribute
weight: 40
weight: 40
aliases: [/contribute/theme/]
-toc: true
---
-A collection of all themes created by the Hugo community, including screenshots and demos, can be found at [themes.gohugo.io]. Every theme in this list will automatically be added to the theme site.
+Visit [themes.gohugo.io] to browse a collection of themes created by the Hugo community.
-Another great site for Hugo themes is [jamstackthemes.dev/](https://jamstackthemes.dev/ssg/hugo/).
+To submit your theme:
-### Add your theme to the repository
+1. Read the [submission guidelines]
+2. Open a pull request in the [themes repository]
-In order to add your Hugo theme to [themes.gohugo.io] please [open a pull request in the theme repository](https://github.com/gohugoio/hugoThemesSiteBuilder). **Please make sure that you've read the theme submission guidelines in the [README](https://github.com/gohugoio/hugoThemesSiteBuilder/blob/main/README.md#hugo-themes) of the hugoThemesSiteBuilder repository.**
-Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors).
+A fast and flexible [static site generator] built with love by [bep], [spf13], and [friends] in [Go].
+
+Hugo is optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less.
-When adding months or years, Hugo normalizes the final `time.Time` value if the resulting day does not exist. For example, adding one month to 31 January produces 2 March or 3 March, depending on the year.
-
-See [this explanation](https://github.com/golang/go/issues/31145#issuecomment-479067967) from the Go team.
-description: Accesses positional and ordered parameters in shortcode declaration.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType: any
- signatures:
- - .Get INDEX
- - .Get KEY
-relatedFunctions: []
----
-
-`.Get` is specifically used when creating your own [shortcode template][sc], to access the [positional and named](/templates/shortcode-templates/#positional-vs-named-parameters) parameters passed to it. When used with a numeric INDEX, it queries positional parameters (starting with 0). With a string KEY, it queries named parameters.
-
-When accessing named or positional parameters that do not exist, `.Get` returns an empty string instead of interrupting the build. This allows you to chain `.Get` with `if`, `with`, `default` or `cond` to check for parameter existence. For example:
-`.GetPage` returns a page of a given `path`. Both `Site` and `Page` implements this method. The `Page` variant will, if given a relative path -- i.e. a path without a leading `/` -- try look for the page relative to the current page.
-
-{{% note %}}
-**Note:** We overhauled and simplified the `.GetPage` API in Hugo 0.45. Before that you needed to provide a `Kind` attribute in addition to the path, e.g. `{{ .Site.GetPage "section" "blog" }}`. This will still work, but is now superfluous.
-{{% /note %}}
-
-
-```go-html-template
-{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}
-```
-
-This method will return `nil` when no page could be found, so the above will not print anything if the blog section is not found.
-
-To find a regular page in the blog section::
-
-```go-html-template
-{{ with .Site.GetPage "/blog/my-post.md" }}{{ .Title }}{{ end }}
-```
-
-And since `Page` also provides a `.GetPage` method, the above is the same as:
-
-```go-html-template
-{{ with .Site.GetPage "/blog" }}
-{{ with .GetPage "my-post.md" }}{{ .Title }}{{ end }}
-{{ end }}
-```
-
-## .GetPage and multilingual sites
-
-The previous examples have used the full content file name to look up the post. Depending on how you have organized your content (whether you have the language code in the file name or not, e.g. `my-post.en.md`), you may want to do the lookup without extension. This will get you the current language's version of the page:
-
-```go-html-template
-{{ with .Site.GetPage "/blog/my-post" }}{{ .Title }}{{ end }}
-```
-
-## .GetPage example
-
-This code snippet---in the form of a [partial template][partials]---allows you to do the following:
-
-1. Grab the index object of your `tags` [taxonomy].
-2. Assign this object to a variable, `$t`
-3. Sort the terms associated with the taxonomy by popularity.
-4. Grab the top two most popular terms in the taxonomy (i.e., the two most popular tags assigned to content.
-
-{{< code file="grab-top-two-tags.html" >}}
-<ul class="most-popular-tags">
-{{ $t := .Site.GetPage "/tags" }}
-{{ range first 2 $t.Data.Terms.ByCount }}
- <li>{{ . }}</li>
-{{ end }}
-</ul>
-{{< /code >}}
-
-## `.GetPage` on page bundles
-
-If the page retrieved by `.GetPage` is a [Leaf Bundle][leaf_bundle], and you
-need to get the nested _**page** resources_ in that, you will need to use the
-methods in `.Resources` as explained in the [Page Resources][page_resources]
-section.
-
-See the [Headless Bundle][headless_bundle] documentation for an example.
-description: Reports whether the given page object matches the page object associated with one of the child menu entries under the given menu entry in the given menu.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType: bool
- signatures: [PAGE.HasMenuCurrent MENU MENUENTRY]
-relatedFunctions:
- - .HasMenuCurrent
- - .IsMenuCurrent
----
-
-If the page object associated with the menu entry is a section, this method also returns `true` for any descendant of that section.
-description: Returns a page parameter, falling back to a site parameter if present.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType: any
- signatures: [.Param KEY]
-relatedFunctions: []
----
-
-The `.Param` method on `.Page` looks for the given `KEY` in page parameters, and returns the corresponding value. If it cannot find the `KEY` in page parameters, it looks for the `KEY` in site parameters. If it cannot find the `KEY` in either location, the `.Param` method returns `nil`.
-
-Site and theme developers commonly set parameters at the site level, allowing content authors to override those parameters at the page level.
-
-For example, to show a table of contents on every page, but allow authors to hide the table of contents as needed:
-The `.Param` method returns the value associated with the given `KEY`, regardless of whether the value is truthy or falsy. If you need to ignore falsy values, use this construct instead:
-description: Takes a view to apply when rendering content.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType: template.HTML
- signatures: [.Render LAYOUT]
-relatedFunctions: []
----
-
-The view is an alternative layout and should be a file name that points to a template in one of the locations specified in the documentation for [Content Views](/templates/views).
-
-This function is only available when applied to a single piece of content within a [list context].
-
-This example could render a piece of content using the content view located at `/layouts/_default/summary.html`:
-{{< new-in "0.93.0" >}} **Note**: [markdownify](/functions/transform/markdownify) uses this function in order to support [Render Hooks](/getting-started/configuration-markup/#markdown-render-hooks).
-description: Acts as a "scratchpad" to store and manipulate data.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType:
- signatures: []
-relatedFunctions:
- - .Store
- - .Scratch
-aliases: [/extras/scratch/,/doc/scratch/]
----
-
-Scratch is a Hugo feature designed to conveniently manipulate data in a Go Template world. It is either a Page or Shortcode method for which the resulting data will be attached to the given context, or it can live as a unique instance stored in a variable.
-
-{{% note %}}
-Note that Scratch was initially created as a workaround for a [Go template scoping limitation](https://github.com/golang/go/issues/10608) that affected Hugo versions prior to 0.48. For a detailed analysis of `.Scratch` and contextual use cases, see [this blog post](https://regisphilibert.com/blog/2017/04/hugo-scratch-explained-variable/).
-{{% /note %}}
-
-### Contexted `.Scratch` vs. local `newScratch`
-
-Since Hugo 0.43, there are two different ways of using Scratch:
-
-#### The Page's `.Scratch`
-
-`.Scratch` is available as a Page method or a Shortcode method and attaches the "scratched" data to the given page. Either a Page or a Shortcode context is required to use `.Scratch`.
-A Scratch instance can also be assigned to any variable using the `newScratch` function. In this case, no Page or Shortcode context is required and the scope of the scratch is only local. The methods detailed below are available from the variable the Scratch instance was assigned to.
-
-```go-html-template
-{{ $data := newScratch }}
-{{ $data.Set "greeting" "hola" }}
-```
-
-### Methods
-
-A Scratch has the following methods:
-
-{{% note %}}
-Note that the following examples assume a [local Scratch instance](#the-local-newscratch) has been stored in `$scratch`.
-{{% /note %}}
-
-#### .Set
-
-Set the value of a given key.
-
-```go-html-template
-{{ $scratch.Set "greeting" "Hello" }}
-```
-
-#### .Get
-
-Get the value of a given key.
-
-```go-html-template
-{{ $scratch.Set "greeting" "Hello" }}
-----
-{{ $scratch.Get "greeting" }} > Hello
-```
-
-#### .Add
-
-Add a given value to existing value(s) of the given key.
-
-For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be [appended](/functions/collections/append/) to that list.
-Return the raw backing map. Note that you should only use this method on the locally scoped Scratch instances you obtain via [`newScratch`](#the-local-newscratch), not `.Page.Scratch` etc., as that will lead to concurrency issues.
-description: Returns a Scratch that is not reset on server rebuilds.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType:
- signatures: []
-relatedFunctions:
- - .Store
- - .Scratch
----
-
-The `.Store` method on `.Page` returns a [Scratch] to store and manipulate data. In contrast to the `.Scratch` method, this Scratch is not reset on server rebuilds.
-
-[Scratch]: /functions/scratch/
-
-### Methods
-
-#### .Set
-
-Sets the value of a given key.
-
-```go-html-template
-{{ .Store.Set "greeting" "Hello" }}
-```
-
-#### .Get
-
-Gets the value of a given key.
-
-```go-html-template
-{{ .Store.Set "greeting" "Hello" }}
-
-{{ .Store.Get "greeting" }} → Hello
-```
-
-#### .Add
-
-Adds a given value to existing value(s) of the given key.
-
-For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
-description: Converts a time.Time value to the number of seconds elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.
-categories: [functions]
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType: int64
- signatures:
- - .Unix
- - .UnixMilli
- - .UnixMicro
- - .UnixNano
-relatedFunctions: []
----
-
-The `Milli`, `Micro`, and `Nano` variants return the number of milliseconds, microseconds, and nanoseconds (respectively) elapsed since the Unix epoch.
+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.
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.
When specifying the regular expression, use a raw [string literal] (backticks) instead of an interpreted string literal (double quotes) to simplify the syntax. With an interpreted string literal you must escape backslashes.
Go's regular expression package implements the [RE2 syntax]. The RE2 syntax is a subset of that accepted by [PCRE], roughly speaking, and with various [caveats]. Note that the RE2 `\C` escape sequence is not supported.
-Go templates are lightweight but extensible. Go itself supplies built-in functions, including comparison operators and other basic tools. These are listed in the [Go template documentation][gofuncs]. Hugo has added additional functions to the basic template logic.
description: Returns a new collection with each element transformed by the given function.
-categories: [functions]
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [apply]
returnType: '[]any'
signatures: [collections.Apply COLLECTION FUNCTION PARAM...]
relatedFunctions:
- - collections.Apply
- collections.Delimit
- collections.In
- collections.Reverse
@@ -25,7+20,6 @@ The `apply` function takes three or more arguments, depending on the function be
The first argument is the collection itself, the second argument is the function name, and the remaining arguments are passed to the function, with the string `"."` representing the collection element.
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
-{{< /code >}}
+```
The page group you get from `group` is of the same type you get from the built-in [group methods](/templates/lists#group-content) in Hugo. The above example can be [paginated](/templates/pagination/#list-paginator-pages).
## Example: load data from a path based on front matter parameters
Assume you want to add a `location = ""` field to your front matter for every article written in `content/vacations/`. You want to use this field to populate information about the location at the bottom of the article in your `single.html` template. You also have a directory in `data/locations/` that looks like the following:
The example we will use will be an article on Oslo, whose front matter should be set to exactly the same name as the corresponding file name in `data/locations/`:
-The primary application for this function is the definition of the `namedSlices` parameter in the options map passed to the `.Related` method on the `Page` object.
+The primary application for this function is the definition of the `namedSlices` parameter in the options map passed to the [`Related`] method on the `Pages` object.
+
+[`Related`]: /methods/pages/related
See [related content](/content-management/related).
-description: Creates a new Scratch which can be used to store values in a thread safe way.
-categories: [functions]
+description: Returns a locally scoped "scratch pad" to store and manipulate data.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [newScratch]
- returnType: Scratch
+ related:
+ - methods/page/scratch
+ - methods/page/store
+ returnType: maps.Scratch
signatures: [collections.NewScratch ]
-relatedFunctions: []
---
+The `collections.NewScratch` function creates a locally scoped [scratch pad] to store and manipulate data. To create a scratch pad that is attached to a `Page` object, use the [`Scratch`] or [`Store`] method.
+: Adds a given value to existing value(s) of the given key.
+
+: For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
-Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both. The elements supported are strings, integers, and floats (only float64).
+Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both.
-`where` filters an array to only the elements containing a matching
-value for a given field.
+The `where` function returns the given collection, removing elements that do not satisfy the comparison condition. The comparison condition is comprised of the `KEY`, `OPERATOR`, and `VALUE` arguments:
-It works in a similar manner to the [`where` keyword in
-SQL][wherekeyword].
+```text
+collections.Where COLLECTION KEY [OPERATOR] VALUE
+ --------------------
+ comparison condition
+```
+
+Hugo will test for equality if you do not provide an `OPERATOR` argument. For example:
```go-html-template
-{{ range where .Pages "Section" "foo" }}
- {{ .Content }}
-{{ end }}
+{{ $pages := where .Site.RegularPages "Section" "books" }}
+{{ $books := where .Site.Data.books "genres" "suspense" }}
```
-It can be used by dot-chaining the second argument to refer to a nested element of a value.
+The where function takes three or four arguments. The `OPERATOR` argument is optional.
-```go-html-template
-{{ range where .Site.Pages "Params.series" "golang" }}
- {{ .Content }}
-{{ end }}
-```
+COLLECTION
+: (`any`) Typically a page collection or a [slice] of [maps].
-It can also be used with the logical operators `!=`, `>=`, `in`, etc. Without an operator, `where` compares a given field with a matching value equivalent to `=`.
+[maps]: /getting-started/glossary/#map
+[slice]: /getting-started/glossary/#slice
+
+KEY
+: (`string`) The key of the page or map value to compare with `VALUE`. With page collections, commonly used comparison keys are `Section`, `Type`, and `Params`. To compare with a member of the page `Params` map, [chain] the subkey as shown below:
```go-html-template
-{{ range where .Pages "Section" "!=" "foo" }}
- {{ .Content }}
-{{ end }}
+{{ $result := where .Site.RegularPages "Params.foo" "bar" }}
```
-The following logical operators are available with `where`:
+[chain]: /getting-started/glossary/#chain
+
+OPERATOR
+: (`string`) The logical comparison [operator](#operators).
+
+VALUE
+: (`any`) The value with which to compare. The values to compare must have comparable data types. For example:
+
+Comparison|Result
+:--|:--
+`"123" "eq" "123"`|`true`
+`"123" "eq" 123`|`false`
+`false "eq" "false"`|`false`
+`false "eq" false`|`true`
+
+When one or both of the values to compare is a slice, use the `in`, `not in` or `intersect` operators as described below.
+
+## Operators
+
+Use any of the following logical operators:
`=`, `==`, `eq`
-: `true` if a given field value equals a matching value
+: (`bool`) Reports whether the given field value is equal to `VALUE`.
`!=`, `<>`, `ne`
-: `true` if a given field value doesn't equal a matching value
+: (`bool`) Reports whether the given field value is not equal to `VALUE`.
`>=`, `ge`
-: `true` if a given field value is greater than or equal to a matching value
+: (`bool`) Reports whether the given field value is greater than or equal to `VALUE`.
`>`, `gt`
-: `true` if a given field value is greater than a matching value
+: `true` Reports whether the given field value is greater than `VALUE`.
`<=`, `le`
-: `true` if a given field value is lesser than or equal to a matching value
+: (`bool`) Reports whether the given field value is less than or equal to `VALUE`.
`<`, `lt`
-: `true` if a given field value is lesser than a matching value
+: (`bool`) Reports whether the given field value is less than `VALUE`.
`in`
-: `true` if a given field value is included in a matching value; a matching value must be an array or a slice
+: (`bool`) Reports whether the given field value is a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in).
`not in`
-: `true` if a given field value isn't included in a matching value; a matching value must be an array or a slice
+: (`bool`) Reports whether the given field value is not a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in).
`intersect`
-: `true` if a given field value that is a slice/array of strings or integers contains elements in common with the matching value; it follows the same rules as the [`intersect` function][intersect].
+: (`bool`) Reports whether the given field value (a slice) contains one or more elements in common with `VALUE`. See [details](/functions/collections/intersect).
+
+`like` {{< new-in 0.116.0 >}}
+: (`bool`) Reports whether the given field value matches the regular expression specified in `VALUE`. Use the `like` operator to compare `string` values. The `like` operator returns `false` when comparing other data types to the regular expression.
+
+{{% note %}}
+The examples below perform comparisons within a page collection, but the same comparisons are applicable to a slice of maps.
+{{% /note %}}
+
+## String comparison
-`like`
-: `true` if a given field value matches a regular expression. Use the `like` operator to compare `string` values. Returns `false` when comparing other data types to the regular expression.
+Compare the value of the given field to a [`string`]:
+
+[`string`]: /getting-started/glossary/#string
-## Use `where` with boolean values
-When using booleans you should not put quotation marks.
```go-html-template
-{{ range where .Pages "Draft" true }}
- <p>{{ .Title }}</p>
-{{ end }}
+{{ $pages := where .Site.RegularPages "Section" "eq" "books" }}
+{{ $pages := where .Site.RegularPages "Section" "ne" "books" }}
```
-## Use `where` with `intersect`
+## Numeric comparison
+
+Compare the value of the given field to an [`int`] or [`float`]:
+
+[`int`]: /getting-started/glossary/#int
+[`float`]: /getting-started/glossary/#float
```go-html-template
-{{ range where .Site.Pages "Params.tags" "intersect" .Params.tags }}
- {{ if ne .Permalink $.Permalink }}
- {{ .Render "summary" }}
- {{ end }}
-{{ end }}
+{{ $sectionPages := where site.RegularPages "Section" "eq" "books" }}
+
+{{ $pages := where $sectionPages "Params.price" "eq" 42 }}
+{{ $pages := where $sectionPages "Params.price" "ne" 42.67 }}
+{{ $pages := where $sectionPages "Params.price" "ge" 42 }}
+{{ $pages := where $sectionPages "Params.price" "gt" 42.67 }}
+{{ $pages := where $sectionPages "Params.price" "le" 42 }}
+{{ $pages := where $sectionPages "Params.price" "lt" 42.67 }}
```
-You can also put the returned value of the `where` clauses into a variable:
-{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections) }}
- {{ .Content }}
-{{ end }}
-{{< /code >}}
+## Intersection comparison
+
+Compare a [`slice`] to a [`slice`], returning collection elements with common values. This is frequently used when comparing taxonomy terms.
+
+For example, to return a collection of pages where any of the terms in the "genres" taxonomy are "suspense" or "romance":
+
+```go-html-template
+{{ $sectionPages := where site.RegularPages "Section" "eq" "books" }}
+
+{{ $genres := slice "suspense" "romance" }}
+{{ $pages := where $sectionPages "Params.genres" "intersect" $genres }}
+```
+
+## Regular expression comparison
-## Nest `where` clauses
+{{< new-in 0.116.0 >}}
-You can also nest `where` clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the "blog" section and then ranges through the result of the first `where` clause and finds all pages that are *not* featured:
+To return a collection of pages where the "author" page parameter begins with either "victor" or "Victor":
```go-html-template
-{{ range where (where .Pages "Section" "blog" ) "Params.featured" "!=" true }}
+{{ $pages := where .Site.RegularPages "Params.author" "like" `(?i)^victor` }}
```
-## Unset fields
+{{% include "functions/_common/regular-expressions.md" %}}
+
+{{% note %}}
+Use the `like` operator to compare string values. Comparing other data types will result in an empty collection.
+{{% /note %}}
-Filtering only works for set fields. To check whether a field is set or exists, you can use the operand `nil`.
+## Date comparison
-This can be useful to filter a small amount of pages from a large pool. Instead of setting a field on all pages, you can set that field on required pages only.
+### Predefined dates
-Only the following operators are available for `nil`
+There are four predefined front matter dates: [`date`], [`publishDate`], [`lastmod`], and [`expiryDate`]. Regardless of the front matter data format (TOML, YAML, or JSON) these are [`time.Time`] values, allowing precise comparisons.
-* `=`, `==`, `eq`: True if the given field is not set.
-* `!=`, `<>`, `ne`: True if the given field is set.
+[`date`]: /methods/page/date
+[`publishdate`]: /methods/page/publishdate
+[`lastmod`]: /methods/page/lastmod
+[`expirydate`]: /methods/page/expirydate
+[`time.Time`]: https://pkg.go.dev/time#Time
+
+For example, to return a collection of pages that were created before the current year:
```go-html-template
-{{ range where .Pages "Params.specialpost" "!=" nil }}
+{{ $pages := where .Site.RegularPages "Date" "lt" $startOfYear }}
+```
+
+### Custom dates
+
+With custom front matter dates, the comparison depends on the front matter data format (TOML, YAML, or JSON).
+
+{{% note %}}
+Using TOML for pages with custom front matter dates enables precise date comparisons.
+{{% /note %}}
+
+With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. If you quote a TOML date, it is a string. If you do not quote a TOML date value, it is [`time.Time`] value, enabling precise comparisons.
+
+In the TOML example below, note that the event date is not quoted.
+{{ $events := where .Site.RegularPages "Type" "events" }}
+{{ $futureEvents := where $events "Params.eventDate" "gt" now }}
+```
+
+When working with YAML or JSON, or quoted TOML values, custom dates are strings; you cannot compare them with `time.Time` values. String comparisons may be possible if the custom date layout is consistent from one page to the next. However, to be safe, filter the pages by ranging through the collection:
+
+```go-html-template
+{{ $events := where .Site.RegularPages "Type" "events" }}
+If `params.mainSections` is not defined in the site configuration, the `MainSections` method returns a slice with one element---the top level section with the most pages.
+
+## Boolean/undefined comparison
+
+Consider this site content:
+
+```text
+content/
+├── posts/
+│ ├── _index.md
+│ ├── post-1.md <-- front matter: exclude = false
+│ ├── post-2.md <-- front matter: exclude = true
+│ └── post-3.md <-- front matter: exclude not defined
+└── _index.md
+```
+
+The first two pages have an "exclude" field in front matter, but the last page does not. When testing for _equality_, the third page is _excluded_ from the result. When testing for _inequality_, the third page is _included_ in the result.
+
+### Equality test
+
+This template:
+
+```go-html-template
+<ul>
+ {{ range where .Site.RegularPages "Params.exclude" "eq" false }}
-description: Returns one of two arguments depending on the value of the control argument.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: [cond]
- returnType: any
- signatures: [compare.Conditional CONTROL ARG1 ARG2]
-relatedFunctions:
- - compare.Conditional
- - compare.Default
-aliases: [/functions/cond]
----
-
-The CONTROL argument is a boolean value that indicates whether the function should return ARG1 or ARG2. If CONTROL is `true`, the function returns ARG1. Otherwise, the function returns ARG2.
-
-```go-html-template
-{{ $qty := 42 }}
-{{ cond (le $qty 3) "few" "many" }} → "many"
-```
-
-The CONTROL argument must be either `true` or `false`. To cast a non-boolean value to boolean, pass it through the `not` operator twice.
-Unlike [ternary operators] in other languages, the `cond` function does not perform [short-circuit evaluation]. The function evaluates both ARG1 and ARG2, regardless of the CONTROL value.
+description: Returns one of two arguments depending on the value of the control argument.
+categories: []
+keywords: []
+action:
+ aliases: [cond]
+ related:
+ - functions/compare/Default
+ returnType: any
+ signatures: [compare.Conditional CONTROL ARG1 ARG2]
+aliases: [/functions/cond]
+---
+
+The CONTROL argument is a boolean value that indicates whether the function should return ARG1 or ARG2. If CONTROL is `true`, the function returns ARG1. Otherwise, the function returns ARG2.
+
+```go-html-template
+{{ $qty := 42 }}
+{{ cond (le $qty 3) "few" "many" }} → many
+```
+
+The CONTROL argument must be either `true` or `false`. To cast a non-boolean value to boolean, pass it through the `not` operator twice.
+Unlike [ternary operators] in other languages, the `cond` function does not perform [short-circuit evaluation]. The function evaluates both ARG1 and ARG2, regardless of the CONTROL value.
-description: Allows setting a default value that can be returned if a first value is not set.
-categories: [functions]
+description: Returns the second argument if set, else the first argument.
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [default]
+ related:
+ - functions/compare/Conditional
+ - functions/go-template/Or
returnType: any
signatures: [compare.Default DEFAULT INPUT]
-relatedFunctions:
- - compare.Conditional
- - compare.Default
aliases: [/functions/default]
---
-`default` checks whether a given value is set and returns a default value if it is not. *Set* in this context means different things depending on the data type:
+The `default` function returns the second argument if set, else the first argument.
-* non-zero for numeric types and times
-* non-zero length for strings, arrays, slices, and maps
-* any boolean or struct value
-* non-nil for any other types
+{{% note %}}
+When the second argument is the boolean `false` value, the `default` function returns `false`. All _other_ falsy values are considered unset.
-`default` function examples reference the following content page:
+{{% include "functions/go-template/_common/truthy-falsy.md" %}}
-oldparam: The default function helps make your templating DRYer.
-newparam:
----
-{{< /code >}}
-
-`default` can be written in more than one way:
-
-```go-html-template
-{{ .Params.font | default "Roboto" }}
-{{ default "Roboto" .Params.font }}
-```
-
-Both of the above `default` function calls return `Roboto`.
-
-A `default` value, however, does not need to be hard coded like the previous example. The `default` value can be a variable or pulled directly from the front matter using dot notation:
-
-```go-html-template
-{{ $old := .Params.oldparam }}
-<p>{{ .Params.newparam | default $old }}</p>
-```
-
-Which would return:
-
-```html
-<p>The default function helps make your templating DRYer.</p>
-Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved error handling when accessing a remote resource.
+Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`] when accessing a remote resource to improve error handling and cache control.
```go-html-template
{{ $data := "" }}
@@ -114,4+134,7 @@ Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved e
-Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved error handling when accessing a remote resource.
+Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`] when accessing a remote resource to improve error handling and cache control.
```go-html-template
{{ $data := "" }}
@@ -121,4+139,7 @@ Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved e
+description: Creates a named timer that reports elapsed time to the console.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related: []
+ returnType: debug.Timer
+ signatures: [debug.Timer NAME]
+---
+
+{{< new-in 0.120.0 >}}
+
+Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottle necks in templates.
+
+The timer starts when you instantiate it, and stops when you call its `Stop` method.
+
+```go-html-template
+{{ $t := debug.Timer "TestSqrt" }}
+{{ range seq 2000 }}
+ {{ $f := math.Sqrt . }}
+{{ end }}
+{{ $t.Stop }}
+```
+
+Use the `--logLevel info` command line flag when you build the site.
+
+```sh
+hugo --logLevel info
+```
+
+The results are displayed in the console at the end of the build. You can have as many timers as you want and if you don't stop them, they will be stopped at the end of build.
+description: Converts ASCII art to an SVG diagram, returning a GoAT diagram object.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related: []
+ returnType: diagrams.goatDiagram
+ signatures: ['diagrams.Goat INPUT']
+toc: true
+---
+
+Useful in a code block [render hook], the `diagram.Goat` function converts ASCII art to an SVG diagram, returning a [GoAT] diagram object with the following methods:
description: Returns the base64 decoding of the given content.
-categories: [functions]
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [base64Decode]
+ related:
+ - functions/encoding/Base64Encode
returnType: string
signatures: [encoding.Base64Decode INPUT]
-signatures:
- -
- - base64Decode INPUT
aliases: [/functions/base64Decode]
---
```go-html-template
-{{ "SHVnbw==" | base64Decode }} → "Hugo"
+{{ "SHVnbw==" | base64Decode }} → Hugo
```
Use the `base64Decode` function to decode responses from APIs. For example, the result of this call to GitHub's API contains the base64-encoded representation of the repository's README file:
@@ -34,15+27,11 @@ more copies of *indent* according to the indentation nesting.
## Options
-indent ("")
-: Indentation to use.
-
-prefix ("")
-: Indentation prefix.
-
-noHTMLEscape (false)
-: Disable escaping of problematic HTML characters inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.
+indent
+: (`string`) Indentation to use. Default is "".
-See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
+prefix
+: (`string`) Indentation prefix. Default is "".
-[pagevars]: /variables/page/
+noHTMLEscape
+: (`bool`) Disable escaping of problematic HTML characters inside JSON quoted strings. The default behavior is to escape `&`, `<`, and `>` to `\u0026`, `\u003c`, and `\u003e` to avoid certain safety problems that can arise when embedding JSON in HTML. Default is `false`.
-The documentation for [Go's fmt package] describes the structure and content of the format string.
+{{% include "functions/fmt/_common/fmt-layout.md" %}}
-Like the [`printf`] function, the `errorf` function evaluates the format string. It then prints the result to the ERROR log and fails the build. Hugo prints each unique message once to avoid flooding the log with duplicate errors.
+The `errorf` function evaluates the format string, then prints the result to the ERROR log and fails the build.
```go-html-template
{{ errorf "The %q shortcode requires a src parameter. See %s" .Name .Position }}
@@ -29,5+24,3 @@ Like the [`printf`] function, the `errorf` function evaluates the format string
Use the [`erroridf`] function to allow optional suppression of specific errors.
description: Log a suppressable ERROR from a template.
-categories: [functions]
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [erroridf]
+ related:
+ - functions/fmt/Errorf
+ - functions/fmt/Warnf
returnType: string
signatures: ['fmt.Erroridf ID FORMAT [INPUT]']
-relatedFunctions:
- - fmt.Errorf
- - fmt.Erroridf
- - fmt.Warnf
aliases: [/functions/erroridf]
---
-The documentation for [Go's fmt package] describes the structure and content of the format string.
+{{% include "functions/fmt/_common/fmt-layout.md" %}}
-Like the [`errorf`] function, the `erroridf` function evaluates the format string, prints the result to the ERROR log, then fails the build. Hugo prints each unique message once to avoid flooding the log with duplicate errors.
-
-Unlike the `errorf` function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreErrors` array in your site configuration.
+The `erroridf` function evaluates the format string, then prints the result to the ERROR log and fails the build. Unlike the [`errorf`] function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreErrors` array in your site configuration.
-The documentation for [Go's fmt package] describes the structure and content of the format string.
+{{% include "functions/fmt/_common/fmt-layout.md" %}}
-Like the [`printf`] function, the `warnf` function evaluates the format string. It then prints the result to the WARNING log. Hugo prints each unique message once to avoid flooding the log with duplicate warnings.
+The `warnf` function evaluates the format string, then prints the result to the WARNING log. Hugo prints each unique message once to avoid flooding the log with duplicate warnings.
```go-html-template
-{{ warnf "Copyright notice missing from site configuration" }}
+{{ warnf "The %q shortcode was unable to find %s. See %s" .Name $file .Position }}
+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.
+description: Provides global access to a Page object.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/global/site
+ returnType:
+ signatures: [page]
+toc: true
+aliases: [/functions/page]
+---
+
+{{< new-in 0.111.0 >}}
+
+At the top level of a template that receives a `Page` object in context, these are equivalent:
+
+```go-html-template
+{{ .Params.foo }}
+{{ .Page.Params.foo }}
+{{ page.Params.foo }}
+```
+
+When a `Page` object is not in context, you can use the global `page` function:
+
+```go-html-template
+{{ page.Params.foo }}
+```
+
+{{% note %}}
+Do not use the global `page` function in shortcodes, partials called by shortcodes, or cached partials. See [warnings](#warnings) below.
+{{% /note %}}
+
+## Explanation
+
+Hugo almost always passes a `Page` as the data context into the top level template (e.g., `single.html`). The one exception is the multihost sitemap template. This means that you can access the current page with the `.` variable in the template.
+
+But when you are deeply nested inside of a [content view], [partial], or [render hook], it is not always practical or possible to access the `Page` object.
+
+Use the global `page` function to access the `Page` object from anywhere in any template.
+
+## Warnings
+
+### Be aware of top-level context
+
+The global `page` function accesses the `Page` object passed into the top-level template.
+
+With this content structure:
+
+```text
+content/
+├── posts/
+│ ├── post-1.md
+│ ├── post-2.md
+│ └── post-3.md
+└── _index.md <-- title is "My Home Page"
+```
+
+And this code in the home page template:
+
+```go-html-template
+{{ range site.Sections }}
+ {{ range .Pages }}
+ {{ page.Title }}
+ {{ end }}
+{{ end }}
+```
+
+The rendered output will be:
+
+```text
+My Home Page
+My Home Page
+My Home Page
+```
+
+In the example above, the global `page` function accesses the `Page` object passed into the home page template; it does not access the `Page` object of the iterated pages.
+
+### Be aware of caching
+
+Do not use the global `page` function in:
+
+- Shortcodes
+- Partials called by shortcodes
+- Partials cached by the [`partialCached`] function
+
+Hugo caches rendered shortcodes. If you use the global `page` function within a shortcode, and the page content is rendered in two or more templates, the cached shortcodes may be incorrect.
+When you call the [`Summary`] method, Hugo renders the page content including shortcodes. In this case, within a shortcode, the global `page` function accesses the `Page` object of the section page, not the content page.
+
+If Hugo renders the section page before a content page, the cached rendered shortcode will be incorrect. You cannot control the rendering sequence due to concurrency.
+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.
+In Go templates, the falsy values are `false`, `0`, any nil pointer or interface value, and any array, slice, map, or string of length zero. Everything else is truthy.
+{{% include "functions/go-template/_common/truthy-falsy.md" %}}
-## Slices
+```go-html-template
+{{ $s := slice "foo" "bar" "baz" }}
+{{ range $var }}
+ {{ . }} → foo bar baz
+{{ end }}
+```
-Template:
+Use with the [`else`] statement:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
<p>{{ . }}</p>
+{{ else }}
+ <p>The collection is empty</p>
+{{ end }}
+```
+
+Within a range block:
+
+- Use the [`continue`] statement to stop the innermost iteration and continue to the next iteration
+- Use the [`break`] statement to stop the innermost iteration and bypass all remaining iterations
+
+## Understanding context
+
+At the top of a page template, the [context] (the dot) is a `Page` object. Within the `range` block, the context is bound to each successive element.
+
+With this contrived example that uses the [`seq`] function to generate a slice of integers:
+
+```go-html-template
+{{ range seq 3 }}
+ {{ .Title }}
+{{ end }}
+```
+
+Hugo will throw an error:
+
+ can't evaluate field Title in type int
+
+The error occurs because we are trying to use the `.Title` method on an integer instead of a `Page` object. Within the `range` block, if we want to render the page title, we need to get the context passed into the template.
+
+{{% note %}}
+Use the `$` to get the context passed into the template.
+{{% /note %}}
+
+This template will render the page title three times:
+
+```go-html-template
+{{ range seq 3 }}
+ {{ $.Title }}
{{ end }}
```
-Result:
+{{% note %}}
+Gaining a thorough understanding of context is critical for anyone writing template code.
+description: Used within partial templates, terminates template execution and returns the given value, if any.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/partials/Include
+ - functions/partials/IncludeCached
+ returnType: any
+ signatures: ['return [VALUE]']
+toc: true
+---
+
+The `return` statement is a custom addition to Go's [text/template] package. Used within partial templates, the `return` statement terminates template execution and returns the given value, if any.
+
+The returned value may be of any data type including, but not limited to, [`bool`], [`float`], [`int`], [`map`], [`resource`], [`slice`], and [`string`].
+
+A `return` statement without a value returns an empty string of type `template.HTML`.
+Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks. See [usage](#usage) notes below.
+{{% /note %}}
+
+## Example
+
+By way of example, let's create a partial template that _renders_ HTML, describing whether the given number is odd or even:
+Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks
+{{% /note %}}
+
+A partial that returns a value must contain only one `return` statement, placed at the end of the template.
+{{% include "functions/go-template/_common/truthy-falsy.md" %}}
-An alternative way of writing an `if` statement and then referencing the same value is to use `with` instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent, unset or empty.
+```go-html-template
+{{ $var := "foo" }}
+{{ with $var }}
+ {{ . }} → foo
+{{ end }}
+```
-The set of *empty* values is defined by [the Go templates package](https://golang.org/pkg/text/template/). Empty values include `false`, the number zero, and the empty string.
+Use with the [`else`] statement:
-If you want to render a block if an index or key is present in a slice, array, channel or map, regardless of whether the value is empty, you should use [`isset`](/functions/collections/isset) instead.
+```go-html-template
+{{ $var := "foo" }}
+{{ with $var }}
+ {{ . }} → foo
+{{ else }}
+ {{ print "var is falsy" }}
+{{ end }}
+```
-The following example checks for a [user-defined site variable](/variables/site/) called `twitteruser`. If the key-value is not set, the following will render nothing:
+Intialize a variable, scoped to the current block:
+At the top of a page template, the [context] (the dot) is a `Page` object. Inside of the `with` block, the context is bound to the value passed to the `with` statement.
+
+With this contrived example:
+
+```go-html-template
+{{ with 42 }}
+ {{ .Title }}
+{{ end }}
+```
+
+Hugo will throw an error:
+
+ can't evaluate field Title in type int
+
+The error occurs because we are trying to use the `.Title` method on an integer instead of a `Page` object. Inside of the `with` block, if we want to render the page title, we need to get the context passed into the template.
+
+{{% note %}}
+Use the `$` to get the context passed into the template.
+{{% /note %}}
+
+This template will render the page title as desired:
+
+```go-html-template
+{{ with 42 }}
+ {{ $.Title }}
+{{ end }}
+```
+
+{{% note %}}
+Gaining a thorough understanding of context is critical for anyone writing template code.
+{{% /note %}}
+
+[context]: /getting-started/glossary/#context
+
+{{% include "functions/go-template/_common/text-template.md" %}}
+description: Returns a slice of project dependencies, either Hugo Modules or local theme components.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related: []
+ returnType: '[]hugo.Dependency'
+ signatures: [hugo.Deps]
+---
+
+The `hugo.Deps` function returns a slice of project dependencies, either Hugo Modules or local theme components. Each dependency contains:
+
+Owner
+: (`hugo.Dependency`) In the dependency tree, this is the first module that defines this module as a dependency (e.g., `github.com/gohugoio/hugo-mod-bootstrap-scss/v5`).
+
+Path
+: (`string`) The module path or the path below your `themes` directory (e.g., `github.com/gohugoio/hugo-mod-jslibs-dist/popperjs/v2`).
+
+Replace
+: (`hugo.Dependency`) Replaced by this dependency.
+
+Time
+: (`time.Time`) The time that the version was created (e.g., `2022-02-13 15:11:28 +0000 UTC`).
+
+Vendor
+: (`bool`) Reports whether the dependency is vendored.
+
+Version
+: (`string`) The module version (e.g., `v2.21100.20000`).
+
+An example table listing the dependencies:
+
+```go-html-template
+<h2>Dependencies</h2>
+<table class="table table-dark">
+ <thead>
+ <tr>
+ <th scope="col">#</th>
+ <th scope="col">Owner</th>
+ <th scope="col">Path</th>
+ <th scope="col">Version</th>
+ <th scope="col">Time</th>
+ <th scope="col">Vendor</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{ range $index, $element := hugo.Deps }}
+ <tr>
+ <th scope="row">{{ add $index 1 }}</th>
+ <td>{{ with $element.Owner }}{{ .Path }}{{ end }}</td>
+ <td>
+ {{ $element.Path }}
+ {{ with $element.Replace }}
+ => {{ .Path }}
+ {{ end }}
+ </td>
+ <td>{{ $element.Version }}</td>
+ <td>{{ with $element.Time }}{{ . }}{{ end }}</td>
-description: Provides global access to Hugo-related data.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType:
- signatures: [hugo]
-relatedFunctions:
- - hugo
- - page
- - site
-aliases: [/functions/hugo]
----
-
-`hugo` returns an instance that contains the following functions:
-
-`hugo.BuildDate`
-: (`string`) The compile date of the current Hugo binary formatted per [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339) (e.g., `2023-05-23T08:14:20Z`).
-
-`hugo.CommitHash`
-: (`string`) The Git commit hash of the Hugo binary (e.g., `0a95d6704a8ac8d41cc5ca8fffaad8c5c7a3754a`).
-
-`hugo.Deps`
-: (`[]*hugo.Dependency`) See [hugo.Deps](#hugodeps).
-
-`hugo.Environment`
-: (`string`) The current running environment as defined through the `--environment` CLI flag (e.g., `development`, `production`).
-
-`hugo.Generator`
-: (`template.HTML`) Renders an HTML `meta` element identifying the software that generated the site (e.g., `<meta name="generator" content="Hugo 0.112.0">`).
-
-`hugo.GoVersion`
-: (`string`) The Go version used to compile the Hugo binary (e.g., `go1.20.4`). {{< new-in "0.101.0" >}}
-
-`hugo.IsExtended`
-: (`bool`) Returns `true` if the Hugo binary is the extended version.
-
-`hugo.IsProduction`
-: (`bool`) Returns `true` if `hugo.Environment` is set to the production environment.
-
-`hugo.Version`
-: (`hugo.VersionString`) The current version of the Hugo binary (e.g., `0.112.1`).
-
-`hugo.WorkingDir`
-: (`string`) The project working directory (e.g., `/home/user/projects/my-hugo-site`). {{< new-in "0.112.0" >}}
-
-## hugo.Deps
-
-{{< new-in "0.92.0" >}}
-
-`hugo.Deps` returns a list of dependencies for a project (either Hugo Modules or local theme components).
-
-Each dependency contains:
-
-Owner
-: (`*hugo.Dependency`) In the dependency tree, this is the first module that defines this module as a dependency (e.g., `github.com/gohugoio/hugo-mod-bootstrap-scss/v5`).
-
-Path
-: (`string`) The module path or the path below your `themes` directory (e.g., `github.com/gohugoio/hugo-mod-jslibs-dist/popperjs/v2`).
-
-Replace
-: (`*hugo.Dependency`) Replaced by this dependency.
-
-Time
-: (`time.Time`) The time that the version was created (e.g., `2022-02-13 15:11:28 +0000 UTC`).
-
-Vendor
-: (`bool`) Returns `true` if the dependency is vendored.
-
-Version
-: (`string`) The module version (e.g., `v2.21100.20000`).
-
-An example table listing the dependencies:
-
-```html
-<h2>Dependencies</h2>
-<table class="table table-dark">
- <thead>
- <tr>
- <th scope="col">#</th>
- <th scope="col">Owner</th>
- <th scope="col">Path</th>
- <th scope="col">Version</th>
- <th scope="col">Time</th>
- <th scope="col">Vendor</th>
- </tr>
- </thead>
- <tbody>
- {{ range $index, $element := hugo.Deps }}
- <tr>
- <th scope="row">{{ add $index 1 }}</th>
- <td>{{ with $element.Owner }}{{ .Path }}{{ end }}</td>
- <td>
- {{ $element.Path }}
- {{ with $element.Replace }}
- => {{ .Path }}
- {{ end }}
- </td>
- <td>{{ $element.Version }}</td>
- <td>{{ with $element.Time }}{{ . }}{{ end }}</td>
+description: Returns an image filter that changes the brightness of an image.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.Brightness PERCENTAGE]
+toc: true
+---
+
+The percentage must be in the range [-100, 100] where 0 has no effect. A value of `-100` produces a solid black image, and a value of `100` produces a solid white image.
+
+## Usage
+
+Create the image filter:
+
+```go-html-template
+{{ $filter := images.Brightness 12 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+Supported image formats include GIF, JPEG, PNG, TIFF, and WebP.
+
+{{% note %}}
+This is a legacy function, superseded by the [`Width`] and [`Height`] methods for [global], [page], and [remote] resources. See the [image processing] section for details.
+description: Returns an image filter that changes the contrast of an image.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.Contrast PERCENTAGE]
+toc: true
+---
+
+The percentage must be in the range [-100, 100] where 0 has no effect. A value of `-100` produces a solid grey image, and a value of `100` produces an over-contrasted image.
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.Contrast -20 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+description: Returns an image filter that performs gamma correction on an image.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.Gamma GAMMA]
+toc: true
+---
+
+The gamma value must be positive. A value greater than 1 lightens the image, while a value less than 1 darkens the image. The filter has no effect when the gamma value is 1.
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.Gamma 1.667 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+description: Returns an image filter that applies a gaussian blur to an image.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.GaussianBlur SIGMA]
+toc: true
+---
+
+The sigma value must be positive, and indicates how much the image will be blurred. The blur-affected radius is approximately 3 times the sigma value.
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.GaussianBlur 5 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+description: Returns an image filter that changes the opacity of an image.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.Opacity OPACITY]
+toc: true
+---
+
+{{< new-in 0.119.0 >}}
+
+The opacity value must be in the range [0, 1]. A value of `0` produces a transparent image, and a value of `1` produces an opaque image (no transparency).
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.Opacity 0.65 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+
+The `images.Opacity` filter is most useful for target formats such as PNG and WebP that support transparency. If the source image does not support transparency, combine this filter with the `images.Process` filter:
+The last argument is the canvas color, expressed as an RGB or RGBA [hexadecimal color]. The default value is `ffffffff` (opaque white). The preceding arguments are the padding values, in pixels, using the CSS [shorthand property] syntax. Negative padding values will crop the image.
+This example resizes an image to 300px wide, converts it to the WebP format, adds 20px vertical padding and 50px horizontal padding, then sets the canvas color to dark green with 33% opacity.
+
+Conversion to WebP is required to support transparency. PNG and WebP images have an alpha channel; JPEG and GIF do not.
+description: Returns an image filter that processes the given image using the given specification.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ - methods/resource/Process
+ returnType: images.filter
+ signatures: [images.Process SPEC]
+toc: true
+---
+
+{{< new-in 0.119.0 >}}
+
+This filter has the same options as the [`Process`] method on a `Resource` object, but using it as a filter may be more effective if you need to apply multiple filters to an image.
+
+[`Process`]: /methods/resource/process
+
+The process specification is a space-delimited, case-insensitive list of one or more of the following in any sequence:
+
+action
+: Specify zero or one of `crop`, `fill`, `fit`, or `resize`. If you specify an action you must also provide dimensions. See [details](content-management/image-processing/#image-processing-methods).
+
+```go-html-template
+{{ $filter := images.Process "resize 300x" }}
+```
+
+dimensions
+: Required if you specify an action. Provide width _or_ height when using `resize`, else provide both width _and_ height. See [details](/content-management/image-processing/#dimensions).
+
+```go-html-template
+{{ $filter := images.Process "crop 200x200" }}
+```
+
+anchor
+: Use with the `crop` or `fill` action. Specify zero or one of `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. Default is `Smart`. See [details](/content-management/image-processing/#anchor).
+: Typically specify zero or one of `r90`, `r180`, or `r270`. Also supports arbitrary rotation angles. See [details](/content-management/image-processing/#rotation).
+
+```go-html-template
+{{ $filter := images.Process "r90" }}
+{{ $filter := images.Process "crop 200x200 center r90" }}
+```
+
+target format
+: Specify zero or one of `gif`, `jpeg`, `png`, `tiff`, or `webp`. See [details](/content-management/image-processing/#target-format).
+
+```go-html-template
+{{ $filter := images.Process "webp" }}
+{{ $filter := images.Process "crop 200x200 center r90 webp" }}
+```
+
+quality
+: Applicable to JPEG and WebP images. Optionally specify `qN` where `N` is an integer in the range [0, 100]. Default is `75`. See [details](/content-management/image-processing/#quality).
+: Applicable to WebP images and equivalent to the `-preset` flag for the [`cwebp`] encoder. Specify zero or one of `drawing`, `icon`, `photo`, `picture`, or `text`. Default is `photo`. See [details](/content-management/image-processing/#hint).
+: When converting a PNG or WebP with transparency to a format that does not support transparency, optionally specify a background color using a 3-digit or a 6-digit hexadecimal color code. Default is `#ffffff` (white). See [details](/content-management/image-processing/#background-color).
+: Typically specify zero or one of `Box`, `Lanczos`, `CatmullRom`, `MitchellNetravali`, `Linear`, or `NearestNeighbor`. Other resampling filters are available. See [details](/content-management/image-processing/#resampling-filter).
+description: Returns an image filter that changes the contrast of an image using a sigmoidal function.
+categories: []
+keywords: []
+action:
+ aliases: []
+ related:
+ - functions/images/Filter
+ - methods/resource/Filter
+ returnType: images.filter
+ signatures: [images.Sigmoid MIDPOINT FACTOR]
+toc: true
+---
+
+This is a non-linear contrast change useful for photo adjustments; it preserves highlight and shadow detail.
+
+The midpoint is the midpoint of contrast. It must be in the range [0, 1], typically 0.5.
+
+The factor indicates how much to increase or decrease the contrast, typically in the range [-10, 10] where 0 has no effect. A positive value increases contrast, while a negative value decrease contrast.
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.Sigmoid 0.6 -4 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. The sharpen radius is approximately 3 times the sigma value.
+
+The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
+
+The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
+
+## Usage
+
+Create the filter:
+
+```go-html-template
+{{ $filter := images.UnsharpMask 10 0.4 0.03 }}
+```
+
+{{% include "functions/images/_common/apply-image-filter.md" %}}
+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.
-description: The images namespace provides a list of filters and other image related functions.
-categories: [functions]
-keywords: []
-aliases: [/functions/imageconfig/]
-menu:
- docs:
- parent: functions
-keywords: [images]
-toc: true
----
-
-See [images.Filter](#filter) for how to apply these filters to an image.
-
-## Process
-
-{{< new-in "0.119.0" >}}
-
-{{< funcsig >}}
-images.Process SRC SPEC
-{{< /funcsig >}}
-
-A general purpose image processing function.
-
-This filter has all the same options as the [Process](/content-management/image-processing/#process) method, but using it as a filter may be more effective if you need to apply multiple filters to an image:
-
-```go-html-template
-{{ $filters := slice
- images.Grayscale
- (images.GaussianBlur 8)
- (images.Process "resize 200x jpg q30")
-}}
-{{ $img = $img | images.Filter $filters }}
-```
-
-## Overlay
-
-{{< funcsig >}}
-images.Overlay SRC X Y
-{{< /funcsig >}}
-
-Overlay creates a filter that overlays the source image at position x y, e.g:
-The above will overlay `$logo` in the upper left corner of `$img` (at position `x=50, y=50`).
-
-## Opacity
-
-{{< new-in "0.119.0" >}}
-
-{{< funcsig >}}
-images.Opacity SRC OPACITY
-{{< /funcsig >}}
-
-Opacity creates a filter that changes the opacity of an image.
-The OPACITY parameter must be in range (0, 1).
-
-```go-html-template
-{{ $img := $img.Filter (images.Opacity 0.5 )}}
-```
-
-This filter is most useful for target formats that support transparency, e.g. PNG. If the source image is e.g. JPG, the most effective way would be to combine it with the [`Process`] filter:
-
-```go-html-template
-{{ $png := $jpg.Filter
- (images.Opacity 0.5)
- (images.Process "png")
-}}
-```
-
-## Text
-
-Using the `Text` filter, you can add text to an image.
-
-{{< funcsig >}}
-images.Text TEXT MAP)
-{{< /funcsig >}}
-
-The following example will add the text `Hugo rocks!` to the image with the specified color, size and position.
-Also see the [Filter Method](/content-management/image-processing/#filter).
-
-### ImageConfig
-
-Parses the image and returns the height, width, and color model.
-
-The `imageConfig` function takes a single parameter, a file path (_string_) relative to the _project's root directory_, with or without a leading slash.
+Note that this is meant for small data sets, e.g. configuration settings. For larger data, please put/mount the files into `/assets` and import them directly.
+
+minify
+: (`bool`)Let `js.Build` handle the minification.
+
+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:
+: (`string`) The output format. One of: `iife`, `cjs`, `esm`. Default is `iife`, a self-executing function, suitable for inclusion as a `<script>` tag.
+
+sourceMap
+: (`string`) Whether to generate `inline` or `external` source maps from esbuild. External source maps will be written to the target with the output file name + ".map". Input source maps can be read from js.Build and node modules and combined into the output source maps. By default, source maps are not created.
+
+### Import JS code from /assets
+
+`js.Build` has full support for the virtual union file system in [Hugo Modules](/hugo-modules/). You can see some simple examples in this [test project](https://github.com/gohugoio/hugoTestProjectJSModImports), but in short this means that you can do this:
+
+```js
+import { hello } from 'my/module';
+```
+
+And it will resolve to the top-most `index.{js,ts,tsx,jsx}` inside `assets/my/module` in the layered file system.
+
+```js
+import { hello3 } from 'my/module/hello3';
+```
+
+Will resolve to `hello3.{js,ts,tsx,jsx}` inside `assets/my/module`.
+
+Any imports starting with `.` is resolved relative to the current file:
+
+```js
+import { hello4 } from './lib';
+```
+
+For other files (e.g. `JSON`, `CSS`) you need to use the relative path including any extension, e.g:
+
+```js
+import * as data from 'my/module/data.json';
+```
+
+Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
+
+Also note the new `params` option that can be passed from template to your JS files, e.g.:
+Hugo will, by default, generate a `assets/jsconfig.json` file that maps the imports. This is useful for navigation/intellisense help inside code editors, but if you don't need/want it, you can [turn it off](/getting-started/configuration/#configure-build).
+
+## Node.js dependencies
+
+Use the `js.Build` function to include Node.js dependencies.
+
+Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [esbuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
+
+The start directory for resolving npm packages (aka. packages that live inside a `node_modules` folder) is always the main project folder.
+
+{{% note %}}
+If you're developing a theme/component that is supposed to be imported and depends on dependencies inside `package.json`, we recommend reading about [hugo mod npm pack](/commands/hugo_mod_npm_pack/), a tool to consolidate all the npm dependencies in a project.
-description: Returns a currency representation of a number for the given currency and precision for the current language in accounting notation.
-categories: [functions]
+description: Returns a currency representation of a number for the given currency and precision for the current language and region in accounting notation.
description: Returns a numeric representation of a number with the given precision using negative, decimal, and grouping options.
-categories: [functions]
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: []
+ related:
+ - functions/lang/FormatAccounting
+ - functions/lang/FormatCurrency
+ - functions/lang/FormatNumber
+ - functions/lang/FormatPercent
returnType: string
signatures: ['lang.FormatNumberCustom PRECISION NUMBER [OPTIONS...]']
-relatedFunctions:
- - lang.FormatAccounting
- - lang.FormatCurrency
- - lang.FormatNumber
- - lang.FormatNumberCustom
- - lang.FormatPercent
aliases: ['/functions/numfmt/']
---
This function formats a number with the given precision. The first options parameter is a space-delimited string of characters to represent negativity, the decimal point, and grouping. The default value is `- . ,`. The second options parameter defines an alternate delimiting character.
-Note that numbers are rounded up at 5 or greater. So, with precision set to 0, 1.5 becomes 2, and 1.4 becomes1.
+Note that numbers are rounded up at 5 or greater. So, with precision set to 0, 1.5 becomes 2, and 1.4 becomes 1.
For a simpler function that adapts to the current language, see [`lang.FormatNumber`].
@@ -108,17+100,17 @@ When viewing the Polish language site:
{{ T "day_with_count" 5 }} → 5 miesięcy
```
-In the pluralization examples above, we passed an integer in context (the second argument). You can also pass a map in context, creating a `count` key to control pluralization.
+In the pluralization examples above, we passed an integer in context (the second argument). You can also pass a map in context, providing a `count` key to control pluralization.
Translation table:
-{{< code-toggle file=i18n/en copy=false >}}
+{{< code-toggle file=i18n/en >}}
[age]
one = '{{ .name }} is {{ .count }} year old.'
other = '{{ .name }} is {{ .count }} years old.'
{{< /code-toggle >}}
-Template:
+Template code:
```go-html-template
{{ T "age" (dict "name" "Will" "count" 1) }} → Will is 1 year old.
+Due to concurrency, the value returned in a given template for a given page will vary from one build to the next. You cannot use this function to assign a static id to each page.
-With Hugo v0.91.0 and later, you must explicitly allow access to environment variables. For details, review [Hugo's Security Policy](/about/security-model/#security-policy). By default, environment variables beginning with `HUGO_` are allowed when using the `os.Getenv` function.
-description: Provides global access to the .Page object.
-categories: [functions]
-keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: []
- returnType:
- signatures: [page]
-relatedFunctions:
- - hugo
- - page
- - site
-aliases: [/functions/page]
----
-
-At the top level of a template that receives the `Page` object in context, these are equivalent:
-
-```go-html-template
-{{ .Params.foo }}
-{{ .Page.Params.foo }}
-{{ page.Params.foo }}
-```
-
-When the `Page` object is not in context, you can use the global `page` function:
-
-```go-html-template
-{{ page.Params.foo }}
-```
-
-{{% note %}}
-Do not use the global `page` function in shortcodes, partials called by shortcodes, or cached partials. See [warnings](#warnings) below.
-{{% /note %}}
-
-## Explanation
-
-Hugo almost always passes a `Page` as the data context into the top level template (e.g., `single.html`). The one exception is the multihost sitemap template. This means that you can access the current page with the `.` variable in the template.
-
-But when you are deeply nested inside of a [content view], [partial], or [render hook], it isn't always practical or possible to access the `Page` object.
-
-Use the global `page` function to access the `Page` object from anywhere in any template.
-
-## Warnings
-
-### Be aware of top-level context
-
-The global `page` function accesses the `Page` object passed into the top-level template.
-
-With this content structure:
-
-```text
-content/
-├── posts/
-│ ├── post-1.md
-│ ├── post-2.md
-│ └── post-3.md
-└── _index.md <-- title is "My Home Page"
-```
-
-And this code in the home page template:
-
-```go-html-template
-{{ range site.Sections }}
- {{ range .Pages }}
- {{ page.Title }}
- {{ end }}
-{{ end }}
-```
-
-The rendered output will be:
-
-```text
-My Home Page
-My Home Page
-My Home Page
-```
-
-In the example above, the global `page` function accesses the `Page` object passed into the home page template; it does not access the `Page` object of the iterated pages.
-
-### Be aware of caching
-
-Do not use the global `page` function in:
-
-- Shortcodes
-- Partials called by shortcodes
-- Partials cached by the `partialCached` function
-
-Hugo caches rendered shortcodes. If you use the `global` page function within a shortcode, and the page content is rendered in two or more templates, the cached shortcodes may be incorrect.
-When you call the `.Summary` method, Hugo renders the page `.Content` including shortcodes. In this case, within a shortcode, the global `page` function accesses the `Page` object of the section page, not the content page.
-
-If Hugo renders the section page before a content page, the cached rendered shortcode will be incorrect. You cannot control the rendering sequence due to concurrency.
-description: Executes the named partial template. If the partial contains a return statement, returns that value, else returns the rendered output.
-categories: [functions]
+description: Executes the given partial template, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output.
+Without a [`return`] statement, the `partial` function returns a string of type `template.HTML`. With a `return` statement, the `partial` function can return any data type.
+
+[`return`]: /functions/go-template/return
+
In this example we have three partial templates:
```text
@@ -63,5+65,21 @@ Then, within the partial template:
<p>{{ .name }} is majoring in {{ .major }}. Their grade point average is {{ .gpa }}.</p>
```
+To return a value from a partial template, it must contain only one `return` statement, placed at the end of the template:
-description: Allows for caching of partials that do not need to be re-rendered on every invocation.
-categories: [functions]
+description: Executes the given template and caches the result, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output.
+ - partials.IncludeCached NAME CONTEXT [VARIANT...]
+ - partialCached NAME CONTEXT [VARIANT...]
aliases: [/functions/partialcached]
---
-The `partialCached` template function can offer significant performance gains for complex templates that don't need to be re-rendered on every invocation.
+Without a [`return`] statement, the `partialCached` function returns a string of type `template.HTML`. With a `return` statement, the `partialCached` function can return any data type.
-**Note:** Each Site (or language) has its own `partialCached` cache, so each site will execute a partial once.
+The `partialCached` function can offer significant performance gains for complex templates that don't need to be re-rendered on every invocation.
-**Note**: Hugo renders pages in parallel, and will render the partial more than once with concurrent calls to the `partialCached` function. After Hugo caches the rendered partial, new pages entering the build pipeline will use the cached result.
+{{% note %}}
+Each Site (or language) has its own `partialCached` cache, so each site will execute a partial once.
+
+Hugo renders pages in parallel, and will render the partial more than once with concurrent calls to the `partialCached` function. After Hugo caches the rendered partial, new pages entering the build pipeline will use the cached result.
-You can also pass additional arguments to `partialCached` to create *variants* of the cached partial. For example, if you have a complex partial that should be identical when rendered for pages within the same section, you could use a variant based upon section so that the partial is only rendered once per section:
+Pass additional arguments to `partialCached` to create variants of the cached partial. For example, if you have a complex partial that should be identical when rendered for pages within the same section, use a variant based on section so that the partial is only rendered once per section:
-{{< code file="partial-cached-example.html" >}}
+{{< code file=partial-cached-example.html >}}
{{ partialCached "footer.html" . .Section }}
{{< /code >}}
-If you need to pass additional arguments to create unique variants, you can pass as many variant arguments as you need:
+Pass additional arguments, of any data type, as needed to create unique variants:
-Note that the variant arguments are not made available to the underlying partial template. They are only use to create a unique cache key. Since Hugo `0.61.0` you can use any object as cache key(s), not just strings.
+The variant arguments are not available to the underlying partial template; they are only used to create unique cache keys.
+
+To return a value from a partial template, it must contain only one `return` statement, placed at the end of the template:
+
+```go-html-template
+{{ $result := false }}
+{{ if math.ModBool . 2 }}
+ {{ $result = "even" }}
+{{ else }}
+ {{ $result = "odd" }}
+{{ end }}
+{{ return $result }}
+```
+
+See [details][`return`].
-See also [The Full Partial Series Part 1: Caching!](https://regisphilibert.com/blog/2019/12/hugo-partial-series-part-1-caching-with-partialcached/).
-description: Join path elements into a single path.
-categories: [functions]
+description: Replaces path separators with slashes (`/`), joins the given path elements into a single path, and returns the shortest path name equivalent to the result.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: []
+ related:
+ - functions/path/Base
+ - functions/path/BaseName
+ - functions/path/Clean
+ - functions/path/Dir
+ - functions/path/Ext
+ - functions/path/Split
+ - functions/urls/JoinPath
returnType: string
signatures: [path.Join ELEMENT...]
-relatedFunctions:
- - path.Base
- - path.BaseName
- - path.Clean
- - path.Dir
- - path.Ext
- - path.Join
- - path.Split
- - urls.JoinPath
aliases: [/functions/path.join]
---
-`path.Join` joins path elements into a single path, adding a separating slash if necessary.
-All empty strings are ignored.
+See Go's [`path.Join`] and [`path.Clean`] documentation for details.
+
+[`path.Clean`]: https://pkg.go.dev/path#Clean
+[`path.Join`]: https://pkg.go.dev/path#Join
-**Note:** All path elements on Windows are converted to slash ('/') separators.
-description: Split path immediately following the final slash.
-categories: [functions]
+description: Replaces path separators with slashes (`/`) and splits the resulting path immediately following the final slash, separating it into a directory and file name component.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: []
- returnType: DirFile
+ related:
+ - functions/path/Base
+ - functions/path/BaseName
+ - functions/path/Clean
+ - functions/path/Dir
+ - functions/path/Ext
+ - functions/path/Join
+ returnType: paths.DirFile
signatures: [path.Split PATH]
-relatedFunctions:
- - path.Base
- - path.BaseName
- - path.Clean
- - path.Dir
- - path.Ext
- - path.Join
- - path.Split
aliases: [/functions/path.split]
---
-`path.Split` splits `PATH` immediately following the final slash, separating it into a directory and a base component.
-
-The returned values have the property that `PATH` = `DIR`+`BASE`.
-If there is no slash in `PATH`, it returns an empty directory and the base is set to `PATH`.
-
-**Note:** On Windows, `PATH` is converted to slash (`/`) separators.
+If there is no slash in the given path, `path.Split` returns an empty directory, and file set to path. The returned values have the property that path = dir+file.
+We add the main project's `node_modules` to `NODE_PATH` when running Babel and similar tools. There are some known [issues](https://github.com/babel/babel/issues/5618) with Babel in this area, so if you have a `babel.config.js` living in a Hugo Module (and not in the project itself), we recommend using `require` to load the presets/plugins, e.g.:
+
+```js
+module.exports = {
+ presets: [
+ [
+ require("@babel/preset-env"),
+ {
+ useBuiltIns: "entry",
+ corejs: 3,
+ },
+ ],
+ ],
+};
+```
+
+## Options
+
+config
+: (`string`) Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration).
+
+minified
+: (`bool`) Save as many bytes as possible when printing
+
+noComments
+: (`bool`) Write comments to generated output (true by default)
+
+compact
+: (`bool`) Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set.
+
+verbose
+: (`bool`) Log everything
+
+sourceMap
+: (`string`) Output `inline` or `external` sourcemap from the babel compile. External sourcemaps will be written to the target with the output file name + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps.
+This function operates on global resources. A global resource is a file within the assets directory, or within any directory mounted to the assets directory.
+
+For page resources, use the [`Resources.ByType`] method on the Page object.
+Asset files of the same [media type] can be bundled into one resource using the `resources.Concat` function which takes two arguments, the target path for the created resource bundle and a slice of resource objects to be concatenated.
+Hugo publishes the resource to the target path when you call its`.Publish`, `.Permalink`, or `.RelPermalink` method. The resource is cached, using the target path as the cache key.
+
+Let's say you have a CSS file that you wish to populate with values from your site configuration:
+Although most commonly used with CSS and JavaScript resources, you can use the `resources.Fingerprint` function with any resource type.
+
+The hash algorithm may be one of `md5`, `sha256` (default), `sha384`, or `sha512`.
+
+After cryptographically hashing the resource content:
+
+1. The values returned by the `.Permalink` and `.RelPermalink` methods include the hash sum
+2. The resource's `.Data.Integrity` method returns a [Subresource Integrity] (SRI) value consisting of the name of the hash algorithm, one hyphen, and the base64-encoded hash sum
+Hugo publishes the resource to the target path when you call its`.Publish`, `.Permalink`, or `.RelPermalink` method. The resource is cached, using the target path as the cache key.
+
+Let's say you need to publish a file named "site.json" in the root of your public directory, containing the build date, the Hugo version used to build the site, and the date that the content was last modified. For example:
+This function operates on global resources. A global resource is a file within the assets directory, or within any directory mounted to the assets directory.
+
+For page resources, use the [`Resources.Get`] method on the Page object.
+This function operates on global resources. A global resource is a file within the assets directory, or within any directory mounted to the assets directory.
+
+For page resources, use the [`Resources.GetMatch`] method on the Page object.
+
+[`Resources.GetMatch`]: /methods/page/resources
+{{% /note %}}
+
+Hugo determines a match using a case-insensitive [glob pattern].
+
+{{% include "functions/_common/glob-patterns.md" %}}
+ {{ errorf "Unable to get remote resource %q" $url }}
+{{ end }}
+```
+
+## Error handling
+
+The [`Err`] method on a resource returned by the `resources.GetRemote` function returns an error message if the HTTP request fails, else nil. If you do not handle the error yourself, Hugo will fail the build.
+This function operates on global resources. A global resource is a file within the assets directory, or within any directory mounted to the assets directory.
+
+For page resources, use the [`Resources.Match`] method on the Page object.
+
+[`Resources.Match`]: /methods/page/resources
+{{% /note %}}
+
+Hugo determines a match using a case-insensitive [glob pattern].
+
+{{% include "functions/_common/glob-patterns.md" %}}
+Follow the steps below to transform CSS using any of the available [PostCSS plugins].
+
+Step 1
+: Install [Node.js].
+
+Step 2
+: Install the required Node.js packages in the root of your project. For example, to add vendor prefixes to your CSS rules:
+
+```sh
+npm i -D postcss postcss-cli autoprefixer
+```
+
+Step 3
+: Create a PostCSS configuration file in the root of your project. You must name this file `postcss.config.js` or another [supported file name]. For example:
+
+```js
+module.exports = {
+ plugins: [
+ require('autoprefixer')
+ ]
+};
+```
+
+{{% note %}}
+{{% include "functions/resources/_common/postcss-windows-warning.md" %}}
+{{% /note %}}
+
+Step 4
+: Place your CSS file within the `assets/css` directory.
+
+Step 5
+: Process the resource with PostCSS:
+
+```go-html-template
+{{ with resources.Get "css/main.css" | postCSS }}
+The `resources.PostCSS` method takes an optional map of options.
+
+config
+: (`string`) The directory that contains the PostCSS configuration file. Default is the root of the project directory.
+
+noMap
+: (`bool`) Default is `false`. If `true`, disables inline sourcemaps.
+
+inlineImports
+: (`bool`) Default is `false`. Enable inlining of @import statements. It does so recursively, but will only import a file once. URL imports (e.g. `@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');`) and imports with media queries will be ignored. Note that this import routine does not care about the CSS spec, so you can have @import anywhere in the file. Hugo will look for imports relative to the module mount and will respect theme overrides.
+
+skipInlineImportsNotFound
+: (`bool`) Default is `false`. Before Hugo 0.99.0 when `inlineImports` was enabled and we failed to resolve an import, we logged it as a warning. We now fail the build. If you have regular CSS imports in your CSS that you want to preserve, you can either use imports with URL or media queries (Hugo does not try to resolve those) or set `skipInlineImportsNotFound` to true.
+The current Hugo environment name (set by `--environment` or in configuration or OS environment) is available in the Node context, which allows constructs like this:
+Marking a resource with `resources.PostProcess` postpones transformations until the build has finished.
+
+Call `resources.PostProcess` when one or more of the steps in the transformation chain depends on the result of the build.
+
+A prime use case for this is purging unused CSS rules using the [PurgeCSS] plugin for the PostCSS Node.js package.
+
+## CSS Purging
+
+{{% note %}}
+There are several ways to set up CSS purging with PostCSS in Hugo. If you have a simple project, you should consider going the simpler route and drop the use of `resources.PostProcess` and just extract keywords from the templates. See the [Tailwind documentation](https://tailwindcss.com/docs/controlling-file-size/#app) for examples.
+{{% /note %}}
+
+Step 1
+: Install [Node.js].
+
+Step 2
+: Install the required Node.js packages in the root of your project:
+
+```sh
+npm i -D postcss postcss-cli autoprefixer @fullhuman/postcss-purgecss
+```
+
+Step 3
+: Create a PostCSS configuration file in the root of your project. You must name this file `postcss.config.js` or another [supported file name]. For example:
+{{% include "functions/resources/_common/postcss-windows-warning.md" %}}
+{{% /note %}}
+
+Step 4
+: Enable creation of the `hugo_stats.json` file when building the site. If you are only using this for the production build, consider placing it below [config/production].
+
+{{< code-toggle file=hugo >}}
+[build.buildStats]
+enable = true
+{{< /code-toggle >}}
+
+See the [configure build] documentation for details and options.
+
+Step 5
+: Place your CSS file within the `assets/css` directory.
+
+Step 6
+: If the current environment is not `development`, process the resource with PostCSS:
+: The absolute path to the project working directory.
+
+HUGO_ENVIRONMENT
+: The current Hugo environment, set with the `--environment` command line flag.
+Default is `production` for `hugo` and `development` for `hugo server`.
+
+HUGO_PUBLISHDIR
+: The absolute path to the publish directory (the `public` directory). Note that the value will always point to a directory on disk even when running `hugo server` in memory mode. If you write to this folder from PostCSS when running the server, you could run the server with one of these flags:
+
+```sh
+hugo server --renderToDisk
+hugo server --renderStaticToDisk
+```
+
+Also, Hugo will add environment variables for all files mounted below `assets/_jsconfig`. A default mount will be set up with files in the project root matching this regexp: `(babel|postcss|tailwind)\.config\.js`.
+
+These will get environment variables named on the form `HUGO_FILE_:filename:` where `:filename:` is all upper case with periods replaced with underscore. This allows you to do something like:
+Do not use `resources.PostProcess` when running Hugo's built-in development server. The examples above specifically prevent this by verifying that the current environment is not "development".
+
+The `resources.PostProcess` function only works within templates that produce HTML files.
+
+You cannot manipulate the values returned from the resource’s methods. For example, the `strings.ToUpper` function in this example will not work as expected:
+Transpile Sass to CSS using the LibSass transpiler included in Hugo's extended edition, or [install Dart Sass](#dart-sass) to use the latest features of the Sass language.
+
+Sass has two forms of syntax: [SCSS] and [indented]. Hugo supports both.
+: (`string`) The transpiler to use, either `libsass` (default) or `dartsass`. Hugo's extended edition includes the LibSass transpiler. To use the Dart Sass transpiler, see the [installation instructions](#dart-sass) below.
+
+targetPath
+: (`string`) If not set, the transformed resource's target path will be the original path of the asset file with its extension replaced by `.css`.
+
+vars
+: (`map`) A map of key/value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/).
+
+```scss
+// LibSass
+@import "hugo:vars";
+
+// Dart Sass
+@use "hugo:vars" as v;
+```
+
+outputStyle
+: (`string`) Output styles available to LibSass include `nested` (default), `expanded`, `compact`, and `compressed`. Output styles available to Dart Sass include `expanded` (default) and `compressed`.
+
+precision
+: (`int`) Precision of floating point math. Not applicable to Dart Sass.
+
+enableSourceMap
+: (`bool`) If `true`, generates a source map.
+
+sourceMapIncludeSources
+: (`bool`) If `true`, embeds sources in the generated source map. Not applicable to LibSass.
+
+includePaths
+: (`slice`) A slice of paths, relative to the project root, that the transpiler will use when resolving `@use` and `@import` statements.
+The extended version of Hugo includes [LibSass] to transpile Sass to CSS. In 2020, the Sass team deprecated LibSass in favor of [Dart Sass].
+
+Use the latest features of the Sass language by installing Dart Sass in your development and production environments.
+
+### Installation overview
+
+Dart Sass is compatible with Hugo v0.114.0 and later.
+
+If you have been using Embedded Dart Sass[^1] with Hugo v0.113.0 and earlier, uninstall Embedded Dart Sass, then install Dart Sass. If you have installed both, Hugo will use Dart Sass.
+
+If you install Hugo as a [Snap package] there is no need to install Dart Sass. The Hugo Snap package includes Dart Sass.
+
+[^1]: In 2023, the Sass team deprecated Embedded Dart Sass in favor of Dart Sass.
+
+### Installing in a development environment
+
+When you install Dart Sass somewhere in your PATH, Hugo will find it.
+You may also install [prebuilt binaries] for Linux, macOS, and Windows.
+
+Run `hugo env` to list the active transpilers.
+
+### Installing in a production environment
+
+For [CI/CD] deployments (e.g., GitHub Pages, GitLab Pages, Netlify, etc.) you must edit the workflow to install Dart Sass before Hugo builds the site[^2]. Some providers allow you to use one of the package managers above, or you can download and extract one of the prebuilt binaries.
+
+[^2]: You do not have to do this if (a) you have not modified the assets cache location, and (b) you have not set `useResourceCacheWhen` to `never` in your [site configuration], and (c) you add and commit your resources directory to your repository.
+
+#### GitHub Pages
+
+To install Dart Sass for your builds on GitHub Pages, add this step to the GitHub Pages workflow file:
+
+```yaml
+- name: Install Dart Sass
+ run: sudo snap install dart-sass
+```
+
+If you are using GitHub Pages for the first time with your repository, GitHub provides a [starter workflow] for Hugo that includes Dart Sass. This is the simplest way to get started.
+
+#### GitLab Pages
+
+To install Dart Sass for your builds on GitLab Pages, the `.gitlab-ci.yml` file should look something like this:
+If you build Hugo from source and run `mage test -v`, the test will fail if you install Dart Sass as a Snap package. This is due to the Snap package's strict confinement model.
+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.
+If you are a Windows user, and the path to your project contains a space, you must place the PostCSS configuration within the package.json file. See [this example] and issue [#7333].
description: Returns a slice of all successive matches of the regular expression. Each element is a slice of strings holding the text of the leftmost match of the regular expression and the matches, if any, of its subexpressions.
By default, `findRESubmatch` finds all matches. You can limit the number of matches with an optional LIMIT argument. A return value of nil indicates no match.
-`split` essentially does the opposite of [delimit](/functions/collections/delimit). While `split` creates a slice from a string, `delimit` creates a string from a slice.
+The `strings.Split` function essentially does the opposite of the [`collections.Delimit`] function. While `split` creates a slice from a string, `delimit` creates a string from a slice.
-description: Converts the provided string to title case.
-categories: [functions]
+description: Returns the given string, converting it to title case.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [title]
+ related:
+ - functions/strings/FirstUpper
+ - functions/strings/ToLower
+ - functions/strings/ToUpper
returnType: string
signatures: [strings.Title STRING]
-relatedFunctions:
- - strings.FirstUpper
- - strings.Title
- - strings.ToLower
- - strings.ToUpper
aliases: [/functions/title]
---
```go-html-template
-{{ title "table of contents (TOC)" }} → "Table of Contents (TOC)"
+{{ title "table of contents (TOC)" }} → Table of Contents (TOC)
```
-By default, Hugo adheres to the capitalization rules in the [Associated Press (AP) Stylebook]. Change your [site configuration] if you would prefer to follow the [Chicago Manual of Style], or to use Go's convention of capitalizing every word.
+By default, Hugo follows the capitalization rules published in the [Associated Press Stylebook]. Change your [site configuration] if you would prefer to:
-description: Returns a slice of a passed string with all leading and trailing characters from cutset removed.
-categories: [functions]
+description: Returns the given string, removing leading and trailing characters specified in the cutset.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
- aliases: [title]
+action:
+ aliases: [trim]
+ related:
+ - functions/strings/Chomp
+ - functions/strings/TrimLeft
+ - functions/strings/TrimPrefix
+ - functions/strings/TrimRight
+ - functions/strings/TrimSuffix
returnType: string
signatures: [strings.Trim INPUT CUTSET]
-relatedFunctions:
- - strings.Chomp
- - strings.Trim
- - strings.TrimLeft
- - strings.TrimPrefix
- - strings.TrimRight
- - strings.TrimSuffix
aliases: [/functions/trim]
---
```go-html-template
-{{ trim "++Batman--" "+-" }} → "Batman"
+{{ trim "++foo--" "+-" }} → foo
```
-`trim` *requires* the second argument, which tells the function specifically what to remove from the first argument. There is no default value for the second argument, so **the following usage will not work**:
+To remove leading and trailing newline characters and carriage returns:
```go-html-template
-{{ trim .Inner }}
+{{ trim "\nfoo\n" "\n\r" }} → foo
+{{ trim "\n\nfoo\n\n" "\n\r" }} → foo
+
+{{ trim "\r\nfoo\r\n" "\n\r" }} → foo
+{{ trim "\r\n\r\nfoo\r\n\r\n" "\n\r" }} → foo
```
-Instead, the following example tells `trim` to remove extra new lines from the content contained in the [shortcode `.Inner` variable][shortcodevars]:
+The `strings.Trim` function is commonly used in shortcodes to remove leading and trailing newlines characters and carriage returns from the content within the opening and closing shortcode tags.
-```go-html-template
-{{ trim .Inner "\n" }}
+For example, with this markdown:
+
+```text
+{{</* my-shortcode */>}}
+Able was I ere I saw Elba.
+{{</* /my-shortcode */>}}
+```
+
+The value of `.Inner` in the shortcode template is:
+
+```text
+\nAble was I ere I saw Elba.\n
```
-{{% note %}}
-Go templates also provide a simple [method for trimming whitespace](/templates/introduction/#whitespace) from either side of a Go tag by including a hyphen (`-`).
-{{% /note %}}
+If authored on a Windows system the value of `.Inner` might, depending on the editor configuration, be:
@@ -22,5+18,7 @@ Since Go templates are HTML-aware, `truncate` will intelligently handle normal s
```
{{% note %}}
-If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the [`safeHTML` template function](/functions/safe/html) before sending the value to truncate. Otherwise, the HTML tags will be escaped when passed through the `truncate` function.
+If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the [`safeHTML`]function before sending the value to `truncate`. Otherwise, the HTML tags will be escaped when passed through the `truncate` function.
-description: Reports whether a template file exists under the given path relative to the `layouts` directory.
-categories: [functions]
+description: Reports whether a template file exists under the given path relative to the layouts directory.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: []
+ related: []
returnType: bool
signatures: [templates.Exists PATH]
-namespace: templates
-relatedFunctions: []
aliases: [/functions/templates.exists]
---
-A template file is any file living below the `layouts` directories of either the project or any of its theme components including partials and shortcodes.
+A template file is any file within the `layouts` directory of either the project or any of its theme components.
-The function is particularly handy with dynamic path. The following example ensures the build will not break on a `.Type` missing its dedicated `header` partial.
+Use the `templates.Exists` function with dynamic template paths:
-description: Converts a timestamp string into a `time.Time` structure.
-categories: [functions]
+description: Returns the given string representation of a date/time value as a time.Time value.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [time]
+ related:
+ - functions/time/Duration
+ - functions/time/Format
+ - functions/time/Now
+ - functions/time/ParseDuration
returnType: time.Time
signatures: ['time.AsTime INPUT [TIMEZONE]']
-relatedFunctions:
- - time.AsTime
- - time.Duration
- - time.Format
- - time.Now
- - time.ParseDuration
aliases: [/functions/time]
+toc: true
---
+## Overview
-`time` converts a timestamp string with an optional default location into a [`time.Time`](https://godoc.org/time#Time) structure so you can access its fields:
+Hugo provides [functions] and [methods] to format, localize, parse, compare, and manipulate date/time values. Before you can do any of these with string representations of date/time values, you must first convert them to [`time.Time`] values using the `time.AsTime` function.
```go-html-template
-{{ time "2016-05-28" }} → "2016-05-28T00:00:00Z"
-{{ (time "2016-05-28").YearDay }} → 149
-{{ mul 1000 (time "2016-05-28T10:30:00.00+10:00").Unix }} → 1464395400000, or Unix time in milliseconds
-The optional `TIMEZONE` argument is a string that sets a default time zone (or more specific, the location, which represents the collection of time offsets in a geographical area) that is associated with the specified time value. If the time value has an explicit timezone or offset specified, it will take precedence over the `TIMEZONE` argument.
+As shown above, the first argument must be a *parsable* string representation of a date/time value. For example:
-The list of valid locations may be system dependent, but should include `UTC`, `Local`, or any location in the [IANA Time Zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
+{{% include "functions/time/_common/parsable-date-time-strings.md" %}}
-If no `TIMEZONE` is set, the `timeZone` from site configuration will be used.
+## Time zones
-```go-html-template
-{{ time "2020-10-20" }} → 2020-10-20 00:00:00 +0000 UTC
-{{ time "2020-10-20" "America/Los_Angeles" }} → 2020-10-20 00:00:00 -0700 PDT
-{{ time "2020-01-20" "America/Los_Angeles" }} → 2020-01-20 00:00:00 -0800 PST
-```
+When the parsable string does not contain a time zone offset, you can do either of the following to assign a time zone other than Etc/UTC:
+
+- Provide a second argument to the `time.AsTime` function
+
+ ```go-html-template
+ {{ time.AsTime "15 Oct 2023" "America/Chicago" }}
+ ```
-## Example: Using `time` to get month index
+- Set the default time zone in your site configuration
-The following example takes a UNIX timestamp---set as `utimestamp: "1489276800"` in a content's front matter---converts the timestamp (string) to an integer using the [`int` function][int], and then uses [`printf`] to convert the `Month` property of `time` into an index.
+ {{< code-toggle file=hugo >}}
+ timeZone = 'America/New_York'
+ {{< /code-toggle >}}
-The following example may be useful when setting up [multilingual sites][multilingual]:
+The order of precedence for determining the time zone is:
-{{< code file="unix-to-month-integer.html" >}}
-{{ $time := time (int .Params.addDate)}}
-=> $time = 1489276800
-{{ $time.Month }}
-=> "March"
-{{ $monthindex := printf "%d" $time.Month }}
-=> $monthindex = 3
-{{< /code >}}
+1. The time zone offset in the date/time string
+2. The time zone provide as the second argument to the `time.AsTime` function
+3. The time zone specified in your site configuration
+The list of valid time zones may be system dependent, but should include `UTC`, `Local`, or any location in the [IANA Time Zone database].
-`time.Duration` converts a given number into a [`time.Duration`](https://pkg.go.dev/time#Duration) structure so you can access its fields. E.g. you can perform [time operations](https://pkg.go.dev/time#Duration) on the returned `time.Duration` value:
+The `time.Duration` function returns a [`time.Duration`] value that you can use with any of the `Duration` [methods].
+
+This template:
```go-html-template
-{{ printf "There are %.0f seconds in one day." (duration "hour" 24).Seconds }}
-<!-- Output: There are 86400 seconds in one day. -->
+{{ $duration := time.Duration "hour" 24 }}
+{{ printf "There are %.0f seconds in one day." $duration.Seconds }}
```
-Make your code simpler to understand by using a [chained pipeline](https://pkg.go.dev/text/template#hdr-Pipelines):
+Is rendered to:
-```go-html-template
-{{ mul 7.75 60 | duration "minute" }} → 7h45m0s
-{{ mul 120 60 | mul 1000 | duration "millisecond" }} → 2h0m0s
+```text
+There are 86400 seconds in one day.
```
-You have to specify a time unit for the number given to the function. Valid time units are:
-description: Parses a given duration string into a `time.Duration` structure.
-categories: [functions]
+description: Returns a time.Duration value by parsing the given duration string.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: []
+ related:
+ - functions/time/AsTime
+ - functions/time/Duration
+ - functions/time/Format
+ - functions/time/Now
returnType: time.Duration
signatures: [time.ParseDuration DURATION]
-relatedFunctions:
- - time.AsTime
- - time.Duration
- - time.Format
- - time.Now
- - time.ParseDuration
aliases: [/functions/time.parseduration]
---
-`time.ParseDuration` parses a duration string into a [`time.Duration`](https://pkg.go.dev/time#Duration) structure so you can access its fields.
+The `time.ParseDuration` function returns a time.Duration value that you can use with any of the `Duration` [methods].
+
+
A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as `300ms`, `-1.5h` or `2h45m`. Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`.
-You can perform [time operations](https://pkg.go.dev/time#Duration) on the returned `time.Duration` value:
+This template:
```go-html-template
-{{ printf "There are %.0f seconds in one day." (time.ParseDuration "24h").Seconds }}
-<!-- Output: There are 86400 seconds in one day. -->
+{{ $duration := time.ParseDuration "24h" }}
+{{ printf "There are %.0f seconds in one day." $duration.Seconds }}
+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.
description: Runs a string through the Emoji emoticons processor.
-categories: [functions]
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [emojify]
+ related: []
returnType: template.HTML
signatures: [transform.Emojify INPUT]
-namespace: transform
-relatedFunctions: []
aliases: [/functions/emojify]
---
`emojify` runs a passed string through the Emoji emoticons processor.
-See the [Emoji cheat sheet][emojis] for available emoticons.
+See the list of [emoji shortcodes] for available emoticons.
-The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration]. Then you can write emoji shorthand directly into your content files; e.g. <code>I :</code><code>heart</code><code>: Hugo!</code>:
+The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration]. Then you can write emoji shorthand directly into your content files;
-description: Returns the given string with HTML escape codes un-escaped.
-categories: [functions]
+description: Returns the given string, replacing each HTML entity with its corresponding character.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [htmlUnescape]
+ related:
+ - functions/transform/HTMLEscape
returnType: string
signatures: [transform.HTMLUnescape INPUT]
-relatedFunctions:
- - transform.HTMLEscape
- - transform.HTMLUnescape
aliases: [/functions/htmlunescape]
---
-Remember to pass the output of this to `safeHTML` if fully un-escaped characters are desired. Otherwise, the output will be escaped again as normal.
+The `transform.HTMLUnescape` function replaces [HTML entities] with their corresponding characters.
```go-html-template
-{{ htmlUnescape "Hugo & Caddy > WordPress & Apache" }} → "Hugo & Caddy > WordPress & Apache"
+{{ htmlUnescape "Lilo & Stitch" }} → Lilo & Stitch
+{{ htmlUnescape "7 > 6" }} → 7 > 6
```
+
+In most contexts Go's [html/template] package will escape special characters. To bypass this behavior, pass the unescaped string through the [`safeHTML`] function.
+
+```go-html-template
+{{ htmlUnescape "Lilo & Stitch" | safeHTML }}
: The language of the code to highlight. Choose from one of the [supported languages]. Case-insensitive.
OPTIONS
-: An optional, comma-separated list of zero or more [options]. Set default values in [site configuration].
+: A map, or comma-separated list, of zero or more [options]. Set default values in [site configuration].
## Options
@@ -57,7+51,7 @@ The number to display at the beginning of the first line. Irrelevant if `lineNos
hl_Lines
: String. Default is `""`.\
-A space-separated 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.
+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.
hl_inline
: Boolean. Default is `false`.\
@@ -82,10+76,10 @@ If the `LANG` argument is blank or an unrecognized language, auto-detect the lan
{{% note %}}
Instead of specifying both `lineNos` and `lineNumbersInTable`, you can use the following shorthand notation:
-`lineNos=inline`
+lineNos=inline
: equivalent to `lineNos=true` and `lineNumbersInTable=false`
-`lineNos=table`
+lineNos=table
: equivalent to `lineNos=true` and `lineNumbersInTable=true`
{{% /note %}}
@@ -101,8+95,8 @@ Instead of specifying both `lineNos` and `lineNumbersInTable`, you can use the f
If the resulting HTML is a single paragraph, Hugo removes the wrapping `p` tags to produce inline HTML as required per the example above.
-To keep the wrapping `p` tags for a single paragraph, use the [`.Page.RenderString`] method, setting the `display` option to `block`.
+To keep the wrapping `p` tags for a single paragraph, use the [`RenderString`] method on the `Page` object, setting the `display` option to `block`.
-If the resulting HTML is two or more paragraphs, Hugo leaves the wrapping `p` tags in place.
-
-[`.Page.RenderString`]: /functions/renderstring/
+[`RenderString`]: /methods/page/renderstring/
{{% note %}}
-Although the `markdownify` function honors [markdown render hooks] when rendering markdown to HTML, use the `.Page.RenderString` method instead of `markdownify` if a render hook accesses `.Page` context. See issue [#9692] for details.
+Although the `markdownify` function honors [markdown render hooks] when rendering markdown to HTML, use the `RenderString` method instead of `markdownify` if a render hook accesses `.Page` context. See issue [#9692] for details.
-The function accepts either a `Resource` created in [Hugo Pipes](/hugo-pipes/) or via [Page Bundles](/content-management/page-bundles/), or simply a string. The two examples below will produce the same map:
+The input can be a string or a [resource].
+
+## Unmarshal a string
+
+```go-html-template
+{{ $string := `
+title: Les Misérables
+author: Victor Hugo
+`}}
+
+{{ $book := unmarshal $string }}
+{{ $book.title }} → Les Misérables
+{{ $book.author }} → Victor Hugo
+```
+
+## Unmarshal a resource
+
+Use the `transform.Unmarshal` function with global, page, and remote resources.
+
+### Global resource
+
+A global resource is a file within the assets directory, or within any directory mounted to the assets directory.
-As a convenience, Hugo allows you to access XML data in the same way that you access JSON, TOML, and YAML: you do not need to specify the root node when accessing the data.
+## Working with XML
-To get the contents of `<title>` in the document below, you use `{{ .message.title }}`:
+When unmarshaling an XML file, do not include the root node when accessing data. For example, after unmarshaling the RSS feed below, access the feed title with `$data.channel.title`.
```xml
-<root>
- <message>
- <title>Hugo rocks!</title>
- <description>Thanks for using Hugo</description>
-description: Takes a string and sanitizes it the same way as the [`defaultMarkdownHandler`](/getting-started/configuration-markup#default-configuration) does for markdown headers.
-categories: [functions]
+description: Returns the given string, sanitized for usage in an HTML id attribute.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [anchorize]
+ related:
+ - functions/urls/URLize
returnType: string
signatures: [urls.Anchorize INPUT]
-relatedFunctions:
- - urls.Anchorize
- - urls.URLize
aliases: [/functions/anchorize]
---
-If [Goldmark](/getting-started/configuration-markup#goldmark) is set as `defaultMarkdownHandler`, the sanitizing logic adheres to the setting [`markup.goldmark.parser.autoHeadingIDType`](/getting-started/configuration-markup#goldmark).
+{{% include "/functions/urls/_common/anchorize-vs-urlize.md" %}}
-Since the `defaultMarkdownHandler` and this template function use the same sanitizing logic, you can use the latter to determine the ID of a header for linking with anchor tags.
+## Sanitizing logic
-```go-html-template
-{{ anchorize "This is a header" }} → "this-is-a-header"
-{{ anchorize "This is also a header" }} → "this-is-also----a-header"
description: Joins the provided elements into a URL string and cleans the result of any ./ or ../ elements. If the argument list is empty, JoinPath returns an empty string.
-description: Returns the absolute permalink to a page.
-categories: [functions]
+description: Returns the absolute permalink to a page at the given path.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [ref]
- returnType: template.HTML
- signatures: [urls.Ref . PAGE]
-relatedFunctions:
- - urls.Ref
- - urls.RelRef
+ related:
+ - functions/urls/RelRef
+ - methods/page/Ref
+ - methods/page/RelRef
+ returnType: string
+ signatures:
+ - urls.Ref PAGE PATH
+ - urls.Ref PAGE OPTIONS
aliases: [/functions/ref]
---
-This function takes two arguments:
+The first argument is the context of the page from which to resolve relative paths, typically the current page.
-- The context of the page from which to resolve relative paths, typically the current page (`.`)
-- The path to a page, with or without a file extension, with or without an anchor. A path without a leading `/` is first resolved relative to the given context, then to the remainder of the site.
+The second argument is a path to a page, with or without a file extension, with or without an anchor. A path without a leading `/` is first resolved relative to the given context, then to the remainder of the site. Alternatively, provide an [options map](#options) instead of a path.
```go-html-template
{{ ref . "about" }}
@@ -32,6+30,19 @@ This function takes two arguments:
{{ ref . "/blog/my-post.md" }}
```
+## Options
+
+Instead of specifying a path, you can also provide an options map:
+
+path
+: (`string`) The path to the page, relative to the content directory. Required.
+
+lang
+: (`string`) The language (site) to search for the page. Default is the current language. Optional.
+
+outputFormat
+: (`string`) The output format to search for the page. Default is the current output format. Optional.
+
To return the absolute permalink to another language version of a page:
```go-html-template
@@ -44,6+55,9 @@ To return the absolute permalink to another Output Format of a page:
-Hugo emits an error or warning if the page cannot be uniquely resolved. The error behavior is configurable; see [Ref and RelRef Configuration](/content-management/cross-references/#ref-and-relref-configuration).
+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.
-This function is used by Hugo's built-in [`ref`](/content-management/shortcodes/#ref-and-relref) shortcode. For a detailed explanation of how to leverage this shortcode for content management, see [Links and Cross References](/content-management/cross-references/).
-description: Returns the relative permalink to a page.
-categories: [functions]
+description: Returns the relative permalink to a page at the given path.
+categories: []
keywords: []
-menu:
- docs:
- parent: functions
-function:
+action:
aliases: [relref]
- returnType: template.HTML
- signatures: [urls.RelRef . PAGE]
-relatedFunctions:
- - urls.Ref
- - urls.RelRef
+ related:
+ - functions/urls/Ref
+ - methods/page/Ref
+ - methods/page/RelRef
+ returnType: string
+ signatures:
+ - urls.RelRef PAGE PATH
+ - urls.RelRef PAGE OPTIONS
aliases: [/functions/relref]
---
-This function takes two arguments:
-
-- The context of the page from which to resolve relative paths, typically the current page (`.`)
-- The path to a page, with or without a file extension, with or without an anchor. A path without a leading `/` is first resolved relative to the given context, then to the remainder of the site.
+The first argument is the context of the page from which to resolve relative paths, typically the current page.
+The second argument is a path to a page, with or without a file extension, with or without an anchor. A path without a leading `/` is first resolved relative to the given context, then to the remainder of the site. Alternatively, provide an [options map](#options) instead of a path.
+.
```go-html-template
{{ relref . "about" }}
{{ relref . "about#anchor" }}
@@ -36,8+34,21 @@ The permalink returned is relative to the protocol+host portion of the baseURL s
-Hugo emits an error or warning if the page cannot be uniquely resolved. The error behavior is configurable; see [Ref and RelRef Configuration](/content-management/cross-references/#ref-and-relref-configuration).
+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.
-This function is used by Hugo's built-in [`relref`](/content-management/shortcodes/#ref-and-relref) shortcode. For a detailed explanation of how to leverage this shortcode for content management, see [Links and Cross References](/content-management/cross-references/).
+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.
: Enable custom attribute support for titles and blocks by adding attribute lists inside single curly brackets (`{.myclass class="class1 class2" }`) and placing it _after the Markdown element it decorates_, on the same line for titles and on a new line directly below for blocks.
@@ -120,13+119,13 @@ Note that attributes in [code fences](/content-management/syntax-highlighting/#h
````
autoHeadingIDType ("github")
-: The strategy used for creating auto IDs (anchor names). Available types are `github`, `github-ascii` and `blackfriday`. `github` produces GitHub-compatible IDs, `github-ascii` will drop any non-Ascii characters after accent normalization, and `blackfriday` will make the IDs compatible with Blackfriday, the default Markdown engine before Hugo 0.60. Note that if Goldmark is your default Markdown engine, this is also the strategy used in the [anchorize](/functions/urls/anchorize) template func.
+: The strategy used for creating auto IDs (anchor names). Available types are `github`, `github-ascii` and `blackfriday`. `github` produces GitHub-compatible IDs, `github-ascii` will drop any non-ASCII characters after accent normalization, and `blackfriday` will make the IDs compatible with Blackfriday, the default Markdown engine before Hugo 0.60. Note that if Goldmark is your default Markdown engine, this is also the strategy used in the [anchorize](/functions/urls/anchorize) template func.
## Asciidoc
This is the default configuration for the AsciiDoc markdown renderer:
-{{< code-toggle config="markup.asciidocExt" />}}
+{{< code-toggle config=markup.asciidocExt />}}
attributes
: (`map`) Variables to be referenced in your AsciiDoc file. This is a list of variable name/value maps. See Asciidoctor’s [attributes].
@@ -190,7+189,7 @@ INFO 2019/12/22 09:08:48 Rendering book-as-pdf.adoc with C:\Ruby26-x64\bin\ascii
This is the default `highlight` configuration. Note that some of these settings can be set per code block, see [Syntax Highlighting](/content-management/syntax-highlighting/).
-{{< code-toggle config="markup.highlight" />}}
+{{< code-toggle config=markup.highlight />}}
For `style`, see these galleries:
@@ -201,7+200,7 @@ For CSS, see [Generate Syntax Highlighter CSS](/content-management/syntax-highli
@@ -35,7+35,7 @@ Multiple site configuration files can be specified as a comma-separated string t
In Hugo 0.110.0 we changed the default configuration base file name to `hugo`, e.g. `hugo.toml`. We will still look for `config.toml` etc., but we recommend you eventually rename it (but you need to wait if you want to support older Hugo versions). The main reason we're doing this is to make it easier for code editors and build tools to identify this as a Hugo configuration file and project.
-{{< new-in "0.110.0" >}}
+{{< new-in 0.110.0 >}}
## Configuration directory
@@ -44,12+44,12 @@ In addition to using a single site configuration file, one can use the `configDi
- Each file represents a configuration root object, such as `params.toml` for `[Params]`, `menu(s).toml` for `[Menu]`, `languages.toml` for `[Languages]` etc...
- Each file's content must be top-level, for example:
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 `googleAnalytics = "G-XXXXXXXX"` in `hugo.toml`. Now consider the following scenario:
-- You don't want the Analytics code to be loaded in development i.e. in your `localhost`
-- You want to use separate googleAnalytics IDs for your production & staging environments (say):
- - `G-PPPPPPPP` for production
- - `G-SSSSSSSS` for staging
+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:
-This is how you need to configure your `hugo.toml` files considering the above scenario:
-1. In `_default/hugo.toml` you don't need to mention `googleAnalytics` parameter at all. This ensures that no Google Analytics code is loaded in your development server i.e. when you run `hugo server`. This works since, by default Hugo sets `Environment=development` when you run `hugo server` which uses the configuration files from `_default` folder
-2. In `production/hugo.toml` you just need to have one line:
+[Google tag ID]: https://support.google.com/tagmanager/answer/12326985?hl=en
- ```googleAnalytics = "G-PPPPPPPP"```
+{{< code-toggle file=hugo >}}
+[services.googleAnalytics]
+ID = 'G-XXXXXXXXX'
+{{< /code-toggle >}}
- You don't need to mention all other parameters like `title`, `baseURL`, `theme` etc. again in this configuration file. You need to mention only those parameters which are different or new for the production environment. This is due to the fact that Hugo is going to __merge__ this on top of `_default/hugo.toml`. Now when you run `hugo` (build command), by default hugo sets `Environment=production`, so the `G-PPPPPPPP` analytics code will be there in your production website
-3. Similarly in `staging/hugo.toml` you just need to have one line:
+Now consider the following scenario:
- ```googleAnalytics = "G-SSSSSSSS"```
+1. You don't want to load the analytics code when running `hugo server`.
+2. You want to use different Google tag IDs for your production and staging environments. For example:
- Now you need to tell Hugo that you are using the staging environment. So your build command should be `hugo --environment staging` which will load the `G-SSSSSSSS` analytics code in your staging website
+ - `G-PPPPPPPPP` for production
+ - `G-SSSSSSSSS` for staging
-{{% note %}}
-Default environments are __development__ with `hugo server` and __production__ with `hugo`.
-{{%/ note %}}
+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.
+
+2. `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.
+
+3. `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.
@@ -162,13+190,19 @@ See [Configure File Caches](#configure-file-caches)
### cascade
-Pass down default configuration values (front matter) to pages in the content tree. The options in site configuration is the same as in page front matter, see [Front Matter Cascade](/content-management/front-matter#front-matter-cascade).
+Pass down down default configuration values (front matter) to pages in the content tree. The options in site config is the same as in page front matter, see [Front Matter Cascade](/content-management/front-matter#front-matter-cascade).
+
+{{% note %}}
+For a website in a single language, define the `[[cascade]]` in [Front Matter](/content-management/front-matter#front-matter-cascade). For a multilingual website, define the `[[cascade]]` in [Site Config](../../getting-started/configuration/#cascade).
+
+To remain consistent and prevent unexpected behaviour, do not mix these strategies.
+{{% /note %}}
### canonifyURLs
**Default value:** false
-Enable to turn relative URLs into absolute. See[details](/content-management/urls/#canonical-urls).
+Enable to turn relative URLs into absolute. See [details](/content-management/urls/#canonical-urls).
### cleanDestinationDir
@@ -240,7+274,7 @@ Do not convert the url/path to lowercase.
**Default value:** false
-Enable Emoji emoticons support for page content; see the [Emoji Cheat Sheet](https://www.webpagefx.com/tools/emoji-cheat-sheet/).
+Enable Emoji emoticons support for page content; see the [emoji shortcode quick reference guide](/quick-reference/emojis/).
### enableGitInfo
@@ -270,12+304,6 @@ Enable generation of `robots.txt` file.
See [Front matter Configuration](#configure-front-matter).
-### googleAnalytics
-
-**Default value:** ""
-
-Google Analytics tracking ID.
-
### hasCJKLanguage
**Default value:** false
@@ -355,7+383,7 @@ Default number of elements per page in [pagination](/templates/pagination/).
**Default value:** "page"
-The path element used during pagination (`https://example.com/page/2`).
+The path element used during pagination (`https://example.org/page/2`).
### permalinks
@@ -381,7+409,7 @@ See [Related Content](/content-management/related/#configure-related-content).
**Default value:** false
-Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. See[details](/content-management/urls/#relative-urls).
+Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. See [details](/content-management/urls/#relative-urls).
### refLinksErrorLevel
@@ -403,12+431,6 @@ Removes [non-spacing marks](https://www.compart.com/en/unicode/category/Mn) from
The `build` configuration section contains global build-related configuration options.
-{{< code-toggle config="build" />}}
+{{< code-toggle config=build />}}
-buildStats {{< new-in "0.115.1" >}}
+buildStats {{< new-in 0.115.1 >}}
: When enabled, creates 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.
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:
This is only relevant when running `hugo server`, and it allows to set HTTP headers during development, which allows you to test out your Content Security Policy and similar. The configuration format matches [Netlify's](https://docs.netlify.com/routing/headers/#syntax-for-the-netlify-configuration-file) with slightly more powerful [Glob matching](https://github.com/gobwas/glob):
@@ -589,7+610,7 @@ You can also specify simple redirects rules for the server. The syntax is again
Note that a `status` code of 200 will trigger a [URL rewrite](https://docs.netlify.com/routing/redirects/rewrites-proxies/), which is what you want in SPA situations, e.g:
@@ -601,11+622,11 @@ Setting `force=true` will make a redirect even if there is existing content in t
## 404 server error page {#_404-server-error-page}
-{{< new-in "0.103.0" >}}
+{{< new-in 0.103.0 >}}
Hugo will, by default, render all 404 errors when running `hugo server` with the `404.html` template. Note that if you have already added one or more redirects to your [server configuration](#configure-server), you need to add the 404 redirect explicitly, e.g:
-Set `titleCaseStyle` to specify the title style used by the [title](/functions/strings/title) template function and the automatic section titles in Hugo.
+By default, Hugo follows the capitalization rules published in the [Associated Press Stylebook] when creating automatic section titles, and when transforming strings with the [`strings.Title`] function.
-Can be one of:
+Change this behavior by setting `titleCaseStyle` in your site configuration to any of the values below:
-* `ap` (default), the capitalization rules in the [Associated Press (AP) Stylebook]
-* `chicago`, the [Chicago Manual of Style]
-* `go`, Go's convention of capitalizing every word.
-* `firstupper`, capitalize the first letter of the first word.
-* `none`, no capitalization.
+ap
+: Use the capitalization rules published in the [Associated Press Stylebook].
+: 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.
@@ -647,7+678,7 @@ In your configuration file, you can direct Hugo as to how you want your website
The following is a typical example of a configuration file. The values nested under `params:` will populate the [`.Site.Params`] variable for use in [templates]:
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
baseURL: "https://yoursite.example.com/"
title: "My Hugo Site"
permalinks:
@@ -684,19+715,21 @@ If you are using snake_cased variable names, the above will not work. Hugo deter
## Ignore content and data files when rendering
-**Note:** This works, but we recommend you use the newer and more powerful [includeFiles and excludeFiles](/hugo-modules/configuration/#module-configuration-mounts) mount options.
+{{% note %}}
+This works, but we recommend you use the newer and more powerful [includeFiles and excludeFiles](/hugo-modules/configuration/#module-configuration-mounts) mount options.
+{{% /note %}}
To exclude specific files from the `content`, `data`, and `i18n` directories when rendering your site, set `ignoreFiles` to one or more regular expressions to match against the absolute file path.
@@ -740,7+773,7 @@ The above will try first to extract the value for `.Lastmod` starting with the `
An example:
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[frontmatter]
date = [":filename", ":default"]
{{< /code-toggle >}}
@@ -758,32+791,32 @@ Hugo v0.20 introduced the ability to render your content to multiple output form
Default configuration:
-{{< code-toggle config="minify" />}}
+{{< code-toggle config=minify />}}
## Configure file caches
Since Hugo 0.52 you can configure more than just the `cacheDir`. This is the default configuration:
-{{< code-toggle config="caches" />}}
+{{< code-toggle config=caches />}}
You can override any of these cache settings in your own `hugo.toml`.
### The keywords explained
-`:cacheDir`
-: See [Configure cacheDir](#configure-cachedir).
+cacheDir
+: (`string`) See [Configure cacheDir](#configure-cachedir).
-`:project`
-: The base directory name of the current Hugo project. This means that, in its default setting, every project will have separated file caches, which means that when you do `hugo --gc` you will not touch files related to other Hugo projects running on the same PC.
+project
+: (`string`) The base directory name of the current Hugo project. This means that, in its default setting, every project will have separated file caches, which means that when you do `hugo --gc` you will not touch files related to other Hugo projects running on the same PC.
-`:resourceDir`
-: This is the value of the `resourceDir` configuration option.
+resourceDir
+: (`string`) This is the value of the `resourceDir` configuration option.
maxAge
-: This is the duration before a cache entry will be evicted, -1 means forever and 0 effectively turns that particular cache off. Uses Go's `time.Duration`, so valid values are `"10s"` (10 seconds), `"10m"` (10 minutes) and `"10h"` (10 hours).
+: (`string`) This is the duration before a cache entry will be evicted, -1 means forever and 0 effectively turns that particular cache off. Uses Go's `time.Duration`, so valid values are `"10s"` (10 seconds), `"10m"` (10 minutes) and `"10h"` (10 hours).
dir
-: The absolute path to where the files for this cache will be stored. Allowed starting placeholders are `:cacheDir` and `:resourceDir` (see above).
+: (`string`) The absolute path to where the files for this cache will be stored. Allowed starting placeholders are `:cacheDir` and `:resourceDir` (see above).
This is the directory where Hugo by default will store its file caches. See [Configure File Caches](#configure-file-caches).
@@ -811,10+843,9 @@ This can be set using the `cacheDir` config option or via the OS env variable `H
If this is not 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 vendors, please read their documentation. For an CircleCI example, see [this configuration](https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml).
-1. In a `hugo_cache` directory below the OS user cache directory as defined by Go's [os.UserCacheDir](https://pkg.go.dev/os#UserCacheDir). On Unix systems, this is `$XDG_CACHE_HOME` as specified by [basedir-spec-latest](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) 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`. {{< new-in "0.116.0" >}}
+1. In a `hugo_cache` directory below the OS user cache directory as defined by Go's [os.UserCacheDir](https://pkg.go.dev/os#UserCacheDir). On Unix systems, this is `$XDG_CACHE_HOME` as specified by [basedir-spec-latest](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) 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`. {{< new-in 0.116.0 >}}
1. In a `hugo_cache_$USER` directory below the OS temp dir.
If you want to know the current value of `cacheDir`, you can run `hugo config`, e.g: `hugo config | grep cachedir`.
description: Terms commonly used throughout the documentation.
+categories: [getting started]
keywords: [glossary]
menu:
docs:
parent: getting-started
weight: 60
weight: 60
-type: glossary
+# Use level 6 headings for each term in the glossary.
---
-<!-- Use level 3 headings for each term in the glossary. -->
-
-### action
+###### action
See [template action](#template-action).
-### archetype
+###### archetype
-A template for new content. See[details](/content-management/archetypes/).
+A template for new content. See [details](/content-management/archetypes/).
-### argument
+###### argument
A [scalar](#scalar), [array](#array), [slice](#slice), [map](#map), or [object](#object) passed to a [function](#function), [method](#method), or [shortcode](#shortcode).
-### array
+###### array
-A numbered sequence of elements. Unlike Go's [slice](#slice) data type, an array has a fixed length. See the [Go documentation](https://go.dev/ref/spec#Array_types) for details.
+A numbered sequence of elements. Unlike Go's [slice](#slice) data type, an array has a fixed length. [Elements](#element) within an array can be [scalars](#scalar), slices, [maps](#map), pages, or other arrays. See the [Go documentation](https://go.dev/ref/spec#Array_types) for details.
-### bool
+###### bool
See [boolean](#boolean).
-### boolean
+###### boolean
A data type with two possible values, either `true` or `false`.
-### branch bundle
+###### branch bundle
-A [page bundle](#page-bundle) with an _index.md file and zero or more [resources](#resource). Analogous to a physical branch, a branch bundle may have descendants including regular pages, [leaf bundles](/getting-started/glossary/#leaf-bundle), and other branch bundles. See[details](/content-management/page-bundles/).
+A [page bundle](#page-bundle) with an _index.md file and zero or more [resources](#resource). Analogous to a physical branch, a branch bundle may have descendants including regular pages, [leaf bundles](/getting-started/glossary/#leaf-bundle), and other branch bundles. See [details](/content-management/page-bundles/).
-### build
+###### build
To generate a static site that includes HTML files and assets such as images, CSS, and JavaScript. The build process includes rendering and resource transformations.
-### bundle
+###### bundle
See [page bundle](#page-bundle).
-### cache
+###### cache
A software component that stores data so that future requests for the same data are faster.
-### collection
+###### chain
+
+Within a template, to connect one or more [identifiers](#identifier) with a dot. An identifier can represent a method, object, or field. For example, `.Site.Params.author.name` or `.Date.UTC.Hour`.
-Typically, a collection of pages, but may also refer to an [array](#array), [slice](#slice), or [map](#map). For example, the pages within a site's "articles" section are a page collection.
+###### collection
-### content format
+An [array](#array), [slice](#slice), or [map](#map).
-A markup language for creating content. Typically markdown, but may also be HTML, AsciiDoc, Org, Pandoc, or reStructuredText. See [details](/content-management/formats/).
+###### content format
-### content type
+A markup language for creating content. Typically markdown, but may also be HTML, AsciiDoc, Org, Pandoc, or reStructuredText. See [details](/content-management/formats/).
+
+###### content type
A classification of content inferred from the top-level directory name or the `type` set in [front matter](#front-matter). Pages in the root of the content directory, including the home page, are of type "page". Accessed via `.Page.Type` in [templates](#template). See [details](/content-management/types/).
-### content view
+###### content view
A template called with the `.Page.Render` method. See [details](/templates/views/).
-### context
+###### context
+
+Represented by a dot "." within a [template action](#template-action), context is the current location in a data structure. For example, while iterating over a [collection](#collection) of pages, the context within each iteration is the page's data structure. The context received by each template depends on template type and/or how it was called. See [details](/templates/introduction/#the-dot).
+
+###### default sort order
+
+The default sort order for page collections. Hugo sorts by [weight](#weight), then by date (descending), then by link title, and then by file path.
+
+###### element
+
+A member of a slice or array.
+
+###### environment
+
+Typically one of `development`, `staging`, or `production`, each environment may exhibit different behavior depending on configuration and template logic. For example, in a production environment you might minify and fingerprint CSS, but that probably doesn't make sense in a development environment.
+
+When running the built-in development server with the `hugo server` command, the environment is set to `development`. When building your site with the `hugo` command, the environment is set to `production`. To override the environment value, use the `--environment` command line flag.
+
+To determine the current environment within a template, use the [`hugo.Environment`] function.
-Represented by a period "." within a [template action](#template-action), context is the current location in a data structure. For example, while iterating over a [collection](#collection) of pages, the context within each iteration is the page's data structure. The context received by each template depends on template type and/or how it was called. See [details](/templates/introduction/#the-dot).
+###### field
-### flag
+A predefined key/value pair in front matter such as `date` or `title`. See also [parameter](#parameter).
-An option passed to a command-line program, beginning with one or two hyphens. See [details](/commands/hugo/).
-### float
+###### flag
+
+An option passed to a command-line program, beginning with one or two hyphens. See [details](/commands/hugo/).
+
+###### float
See [floating point](#floating-point).
-### floating point
+###### floating point
A numeric data type with a fractional component. For example, `3.14159`.
-### function
+###### fragment
-Used within a [template action](#template-action), a function takes one or more [arguments](#argument) and returns a value. Unlike [methods](#method), functions are not associated with an [object](#object). See [details](/functions/).
+The final segment of a URL, beginning with a hash (`#`) mark, that references an `id` attribute of an HTML element on the page.
-### front matter
+###### front matter
Metadata at the beginning of each content page, separated from the content by format-specific delimiters. See [details](/content-management/front-matter/).
-### identifier
+###### function
+
+Used within a [template action](#template-action), a function takes one or more [arguments](#argument) and returns a value. Unlike [methods](#method), functions are not associated with an [object](#object). See [details](/functions/).
+
+###### global resource
+
+A file within the assets directory, or within any directory [mounted](/hugo-modules/configuration/#module-configuration-mounts) to the assets directory. Capture one or more global resources using the [`resources.Get`], [`resources.GetMatch`], [`resources.Match`], or [`resources.ByType`] functions.
A string that represents a variable, method, object, or field. It must conform to Go's [language specification](https://go.dev/ref/spec#Identifiers), beginning with a letter or underscore, followed by zero or more letters, digits, or underscores.
-### int
+###### int
See [integer](#integer).
-### integer
+###### integer
A numeric data type without a fractional component. For example, `42`.
-### internationalization
+###### internationalization
Software design and development efforts that enable [localization](#localization). See the [W3C definition](https://www.w3.org/International/questions/qa-i18n). Abbreviated i18n.
-### kind
+###### kind
See [page kind](#page-kind).
-### layout
+###### layout
See [template](#template).
-### leaf bundle
+###### leaf bundle
-A [page bundle](#page-bundle) with an index.md file and zero or more [resources](#resource). Analogous to a physical leaf, a leaf bundle is at the end of a branch. Hugo ignores content (but not resources) beneath the leaf bundle. See[details](/content-management/page-bundles/).
+A [page bundle](#page-bundle) with an index.md file and zero or more [resources](#resource). Analogous to a physical leaf, a leaf bundle is at the end of a branch. Hugo ignores content (but not resources) beneath the leaf bundle. See [details](/content-management/page-bundles/).
-### list page
+###### list page
Any [page kind](#page-kind) that receives a page [collection](#collection) in [context](#context). This includes the home page, [section pages](#section-page), [taxonomy pages](#taxonomy-page), and [term pages](#term-page).
-### localization
+###### localization
-Adaptation of a site to meet language and regional requirements. This includes translations, language-specific media, date and currency formats, etc. See[details](/content-management/multilingual/) and the [W3C definition](https://www.w3.org/International/questions/qa-i18n). Abbreviated l10n.
+Adaptation of a site to meet language and regional requirements. This includes translations, language-specific media, date and currency formats, etc. See [details](/content-management/multilingual/) and the [W3C definition](https://www.w3.org/International/questions/qa-i18n). Abbreviated l10n.
-### map
+###### map
An unordered group of elements, each indexed by a unique key. See the [Go documentation](https://go.dev/ref/spec#Map_types) for details.
-### method
+###### markdown attribute
+
+A list of attributes, containing one or more key/value pairs, separated by spaces or commas, and wrapped by braces. Apply markdown attributes to images and block-level elements including blockquotes, fenced code blocks, headings, horizontal rules, lists, paragraphs, and tables. See [details](/getting-started/configuration-markup/#goldmark).
+
+###### marshal
+
+To transform a data structure into a serialized object. For example, transforming a [map](#map) into a JSON string. See [unmarshal](#unmarshal).
+
+###### method
Used within a [template action](#template-action) and associated with an [object](#object), a method takes zero or more [arguments](#argument) and either returns a value or performs an action. For example, `.IsHome` is a method on the `.Page` object which returns `true` if the current page is the home page. See also [function](#function).
-### module
+###### module
-Like a [theme](#theme), a module is a packaged combination of [archetypes](#archetype), assets, content, data, [templates](#template), translation tables, static files, or configuration settings. A module may serve as the basis for a new site, or to augment an existing site. See[details](/hugo-modules/).
+Like a [theme](#theme), a module is a packaged combination of [archetypes](#archetype), assets, content, data, [templates](#template), translation tables, static files, or configuration settings. A module may serve as the basis for a new site, or to augment an existing site. See [details](/hugo-modules/).
-### object
+###### object
A data structure with or without associated [methods](#method).
-### page bundle
+###### ordered taxonomy
+
+Created by invoking the [`Alphabetical`] or [`ByCount`] method on a [taxonomy object](#taxonomy-object), which is a [map](#map), an ordered taxonomy is a [slice](#slice), where each element is an object that contains the [term](#term) and a slice of its [weighted pages](#weighted-page).
+
+[`Alphabetical`]: /methods/taxonomy/alphabetical
+[`ByCount`]: /methods/taxonomy/bycount
-A directory that encapsulates both content and associated [resources](#resource). There are two types of page bundles: [leaf bundles](/getting-started/glossary/#leaf-bundle) and [branch bundles](/getting-started/glossary/#branch-bundle). See [details](/content-management/page-bundles/).
+###### output format
-### page kind
+{{% include "methods/page/_common/output-format-definition.md" %}}
-A classification of rendered pages, one of "home", "page", "section", "taxonomy", or "term". Accessed via `.Page.Kind` in [templates](#template). See [details](/templates/section-templates/#page-kinds).
+###### page bundle
-### pager
+A directory that encapsulates both content and associated [resources](#resource). There are two types of page bundles: [leaf bundles](#leaf-bundle) and [branch bundles](#branch-bundle). See [details](/content-management/page-bundles/).
+
+###### page kind
+
+A classification of pages, one of `home`, `page`, `section`, `taxonomy`, or `term`. See [details](/templates/section-templates/#page-kinds).
+
+Note that there are also `RSS`, `sitemap`, `robotsTXT`, and `404` page kinds, but these are only available during the rendering of each of these respective page's kind and therefore *not* available in any of the `Pages` collections.
+
+###### page resource
+
+A file within a [page bundle](#page-bundle). Capture one or more page resources using any of the [`Resources`] methods on a `Page` object.
+
+[`Resources`]: /methods/page/resources/#methods
+
+###### pager
Created during [pagination](#pagination), a pager contains a subset of a section list, and navigation links to other pagers.
-### paginate
+###### paginate
To split a [section](#section) list into two or more [pagers](#pager) See [details](/templates/pagination/).
-### pagination
+###### pagination
The process of [paginating](#paginate) a [section](#section) list.
-### parameter
+###### parameter
-Typically, a user-defined key/value pair at the site or page level, but may also refer to a configuration setting or an [argument](#argument).
+Typically, a user-defined key/value pair at the site or page level, but may also refer to a configuration setting or an [argument](#argument). See also [field](#field).
-### partial
+###### partial
A [template](#template) called from any other template including [shortcodes](#shortcode), [render hooks](#render-hook), and other partials. A partial either renders something or returns something. A partial can also call itself, for example, to [walk](#walk) a data structure.
-### permalink
+###### permalink
-The absolute URL of a rendered page, including scheme and host.
+The absolute URL of a published resource or a rendered page, including scheme and host.
-### pipe
+###### pipe
See [pipeline](#pipeline).
-### pipeline
+###### pipeline
Within a [template action](#template-action), a pipeline is a possibly chained sequence of values, [function](#function) calls, or [method](#method) calls. Functions and methods in the pipeline may take multiple [arguments](#argument).
A pipeline may be *chained* by separating a sequence of commands with pipeline characters "|". In a chained pipeline, the result of each command is passed as the last argument to the following command. The output of the final command in the pipeline is the value of the pipeline. See the [Go documentation](https://pkg.go.dev/text/template#hdr-Pipelines) for details.
-### publish
+###### publish
See [build](#build).
-### regular page
+###### regular page
Content with the "page" [page kind](#page-kind). See also [section page](#section-page).
-### render hook
+###### relative permalink
-A [template](#template) that overrides standard markdown rendering. See [details](/templates/render-hooks/).
+The host-relative URL of a published resource or a rendered page.
-### resource
+###### render hook
+
+A [template](#template) that overrides standard markdown rendering. See [details](/templates/render-hooks/).
+
+###### remote resource
+
+A file on a remote server, accessible via HTTP or HTTPS with the [`resources.GetRemote`](/functions/resources/getremote) function.
+
+###### resource
Any file consumed by the build process to augment or generate content, structure, behavior, or presentation. For example: images, videos, content snippets, CSS, Sass, JavaScript, and data.
-Hugo supports three types of resources: page resources (located in a [page bundle](/getting-started/glossary/#page-bundle)), global resources (located in the assets directory), and remote resources (typically accessed via HTTPS).
+Hugo supports three types of resources: [global](#global-resource), [page](#page-resource), and [remote](#remote-resource)
-### scalar
+###### scalar
A single value, one of [string](#string), [integer](#integer), [floating point](#floating-point), or [boolean](#boolean).
-### section
+###### scratch pad
+
+Conceptually, a [map](#map) with [methods](#method) to set, get, update, and delete values. Attach the data structure to a `Page` object using the [`Scratch`] or [`Store`] methods, or created a locally scoped scratch pad using the [`newScratch`] function.
-A top-level content directory, or any content directory with an _index.md file. A content directory with an _index.md file is also known as a [branch bundle](/getting-started/glossary/#branch-bundle). Section templates receive one or more page [collections](#collection) in [context](#context). See [details](/content-management/sections/).
+###### section
-### section page
+A top-level content directory, or any content directory with an _index.md file. A content directory with an _index.md file is also known as a [branch bundle](/getting-started/glossary/#branch-bundle). Section templates receive one or more page [collections](#collection) in [context](#context). See [details](/content-management/sections/).
+
+###### section page
Content with the "section" [page kind](#page-kind). Typically a listing of [regular pages](#regular-page) and/or [section pages](#section-page) within the current [section](#section). See also [regular page](#regular-page).
-### shortcode
+###### shortcode
-A [template](#template) called from within markdown, taking zero or more [arguments](#argument). See[details](/content-management/shortcodes/).
+A [template](#template) called from within markdown, taking zero or more [arguments](#argument). See [details](/content-management/shortcodes/).
-### slice
+###### slice
-A numbered sequence of elements. Unlike Go's [array](#array) data type, slices are dynamically sized. See the [Go documentation](https://go.dev/ref/spec#Slice_types) for details.
+A numbered sequence of elements. Unlike Go's [array](#array) data type, slices are dynamically sized. [Elements](#element) within a slice can be [scalars](#scalar), [arrays](#array), [maps](#map), pages, or other slices. See the [Go documentation](https://go.dev/ref/spec#Slice_types) for details.
-### string
+###### string
A sequence of bytes. For example, `"What is 6 times 7?"` .
-### taxonomy
+###### taxonomic weight
+
+Defined in front matter and unique to each taxonomy, this [weight](#weight) determines the sort order of page collections contained within a [taxonomy object](#taxonomy-object). See [details](/templates/taxonomy-templates/#assign-weight).
+
+###### taxonomy
A group of related [terms](#term) used to classify content. For example, a "colors" taxonomy might include the terms "red", "green", and "blue". See [details](/content-management/taxonomies/).
-### taxonomy page
+###### taxonomy object
+
+A [map](#map) of [terms](#term) and the [weighted pages](#weighted-page) associated with each term.
+
+###### taxonomy page
Content with the "taxonomy" [page kind](#page-kind). Typically a listing of [terms](#term) within a given [taxonomy](#taxonomy).
-### template
+###### template
A file with [template actions](#template-action), located within the layouts directory of a project, theme, or module. See [details](/templates/).
-### template action
+###### template action
A data evaluation or control structure within a [template](#template), delimited by "{{" and "}}". See the [Go documentation](https://pkg.go.dev/text/template#hdr-Actions) for details.
-### term
+###### term
A member of a [taxonomy](#taxonomy), used to classify content. See [details](/content-management/taxonomies/).
-### term page
+###### term page
Content with the "term" [page kind](#page-kind). Typically a listing of [regular pages](#regular-page) and [section pages](#section-page) with a given [term](#term).
-### theme
+###### theme
A packaged combination of [archetypes](#archetype), assets, content, data, [templates](#template), translation tables, static files, or configuration settings. A theme may serve as the basis for a new site, or to augment an existing site. See also [module](#module).
-### token
+###### token
An identifier within a format string, beginning with a colon and replaced with a value when rendered. For example, use tokens in format strings for both [permalinks](/content-management/urls/#permalinks) and [dates](/functions/time/format/#localization).
-
-### type
+###### type
See [content type](#content-type).
-### variable
+###### unmarshal
-A variable initialized within a [template action](#template-action).
+To transform a serialized object into a data structure. For example, transforming a JSON file into a [map](#map) that you can access within a template. See [marshal](#marshal).
-### walk
+###### variable
+
+A user-defined [identifier](#identifier) prefaced with a `$` symbol, representing a value of any data type, initialized or assigned within a [template action](#template-action). For example, `$foo` and `$bar` are variables.
+
+###### walk
To recursively traverse a nested data structure. For example, rendering a multilevel menu.
+
+###### weight
+
+Used to position an element within a collection sorted by weight. Assign weights using non-zero integers. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted elements are placed at the end of the collection. Weights are typically assigned to pages, menu entries, languages, and output formats.
+
+###### weighted page
+
+Contained within a [taxonomy object](#taxonomy-object), a weighted page is a [map](#map) with two elements: a `Page` object, and its [taxonomic weight](#taxonomic-weight) as defined in front matter. Access the elements using the `Page` and `Weight` keys.
To build your site, `cd` into your project directory and run:
-```bash
+```sh
hugo
```
@@ -60,7+60,6 @@ Depending on your needs, you may wish to manually clear the contents of the publ
Hugo allows you to set `draft`, `date`, `publishDate`, and `expiryDate` in the [front matter] of your content. By default, Hugo will not publish content when:
-
- The `draft` value is `true`
- The `date` is in the future
- The `publishDate` is in the future
@@ -68,7+67,7 @@ Hugo allows you to set `draft`, `date`, `publishDate`, and `expiryDate` in the [
You can override the default behavior when running `hugo` or `hugo server` with command line flags:
-```bash
+```sh
hugo --buildDrafts # or -D
hugo --buildExpired # or -E
hugo --buildFuture # or -F
@@ -86,7+85,7 @@ A common practice is to manually clear the contents of the `public` directory be
To view your site while developing layouts or creating content, `cd` into your project directory and run:
-```bash
+```sh
hugo server
```
@@ -108,7+107,7 @@ While the server is running, Hugo injects JavaScript into the generated HTML pag
When editing content, if you want your browser to automatically redirect to the page you last modified, run:
-```bash
+```sh
hugo server --navigateToChanged
```
@@ -120,7+119,7 @@ As noted above, Hugo does not clear the public directory before building your si
When you are ready to deploy your site, run:
-```bash
+```sh
hugo
```
@@ -129,16+128,16 @@ This builds your site, publishing the files to the public directory. The directo
Go to the [Firebase console][console] and create a new project (unless you already have a project). You will need to globally install `firebase-tools` (node.js):
-```txt
+```sh
npm install -g firebase-tools
```
Log in to Firebase (setup on your local machine) using `firebase login`, which opens a browser where you can select your account. Use `firebase logout` in case you are already logged in but to the wrong account.
-
-```txt
+```sh
firebase login
```
In the root of your Hugo project, initialize the Firebase project with the `firebase init` command:
-```txt
+```sh
firebase init
```
@@ -78,7+77,7 @@ Don't forget to update your static pages before push!
To deploy your Hugo site, execute the `firebase deploy` command, and your site will be up in no time:
description: GitLab makes it easy to build, deploy, and host your Hugo website via their free GitLab Pages service, which provides native support for Hugo.
categories: [hosting and deployment]
-keywords: [hosting,deployment,git,gitlab]
+keywords: [hosting,gitlab]
menu:
docs:
parent: hosting-and-deployment
@@ -25,7+25,7 @@ The `baseURL` in your [site configuration](/getting-started/configuration/) must
Define your [CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) jobs by creating a `.gitlab-ci.yml` file in the root of your project.
Next, create a new repository on GitLab. It is *not* necessary to make the repository public. In addition, you might want to add `/public` to your .gitignore file, as there is no need to push compiled assets to GitLab or keep your output website in version control.
description: "Accelerate your Hugo site globally with a KeyCDN integration. This tutorial shows you how to set up your static site as a GitLab page behind a KeyCDN pull zone."
Using this integration method, you will have to specify the Zone ID and your [KeyCDN API](https://www.keycdn.com/api) key as secret variables. To do this, navigate to the top-left menu bar in GitLab and select Projects. Then, select your project and click on the Settings page. Finally, select Pipelines from the sub-menu and scroll down to the Secret Variable section.
The Secret Variable for your Zone ID should look similar to:
@@ -76,7+76,7 @@ The Zone ID and API key are used to purge your zone – it’s not strictly need
Now it’s time to push the newly created repository to GitLab:
-Go to [app.netlify.com] and select your preferred signup method. This will likely be a hosted Git provider, although you also have the option to sign up with an email address.
+Go to [app.netlify.com] and select your preferred signup method. This will likely be a hosted Git provider, although you also have the option to sign up with an email address.
The following examples use GitHub, but other git providers will follow a similar process.
@@ -55,21+55,21 @@ You can [set Hugo version](https://www.netlify.com/blog/2017/04/11/netlify-plus-
For production:
-{{< code file="netlify.toml" >}}
+{{< code file=netlify.toml >}}
[context.production.environment]
HUGO_VERSION = "0.115.4"
{{< /code >}}
For testing:
-{{< code file="netlify.toml" >}}
+{{< code file=netlify.toml >}}
[context.deploy-preview.environment]
HUGO_VERSION = "0.115.4"
{{< /code >}}
The Netlify configuration file can be a little hard to understand and get right for the different environment, and you may get some inspiration and tips from this site's `netlify.toml`:
You can use the "hugo deploy" command to upload your site directly to a Google Cloud Storage (GCS) bucket, an AWS S3 bucket, and/or an Azure Storage container.
+
## Assumptions
* You have completed the [Quick Start] or have a Hugo website you are ready to deploy and share with the world.
@@ -22,73+23,202 @@ You can use the "hugo deploy" command to upload your site directly to a Google C
* AWS: [Install the CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and run [`aws configure`](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html).
* Azure: [Install the CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) and run [`az login`](https://docs.microsoft.com/en-us/cli/azure/authenticate-azure-cli).
* NOTE: Each service supports alternatives for authentication, including using environment variables. See [here](https://gocloud.dev/howto/blob/#services) for more details.
+* You have created a bucket to deploy to. If you want your site to be
+ public, be sure to configure the bucket to be publicly readable as a static website.
+ * Google Cloud: [create a bucket](https://cloud.google.com/storage/docs/creating-buckets) and [host a static website](https://cloud.google.com/storage/docs/hosting-static-website)
+ * Amazon S3: [create a bucket](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html) and [host a static website](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html)
+ * Microsoft Azure: [create a storage container](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal) and [host a static website](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website)
+
+
+## Configuring your first deployment
+
+In the configuration file for your site, add a `[deployment]` section
+and a `[[deployment.targets]]` subsection. The only required parameters are
+the name and URL:
+
+```toml
+[deployment]
+
+[[deployment.targets]]
+# An arbitrary name for this target.
+name = "production"
+
+# URL specifies the Go Cloud Development Kit URL to deploy to. Examples:
+URL = "<FILL ME IN>"
+
+# Google Cloud Storage -- see https://gocloud.dev/howto/blob/#gcs
+#URL = "gs://<Bucket Name>"
+
+# Amazon Web Services S3; see https://gocloud.dev/howto/blob/#s3
+# For S3-compatible endpoints, see https://gocloud.dev/howto/blob/#s3-compatible
+#URL = "s3://<Bucket Name>?region=<AWS region>"
+
+# Microsoft Azure Blob Storage; see https://gocloud.dev/howto/blob/#azure
+#URL = "azblob://$web"
+
+```
+
+## Deploy
+
+To deploy to a target:
+
+```bash
+hugo deploy [--target=<target name>]
+```
+
+The deploy process recursively walks through your local publish directory
+(`public` by default) and syncs it to the destination bucket, to ensure
+that the local and remote contents match.
+
+If you don't specify a target, Hugo will deploy to the first target in your
+configuration.
+
+See `hugo help deploy` or [the deploy command-line documentation][commandline] for more command-line options.
+
+
+### How the file list works
-## Create a bucket to deploy to
+The first thing `hugo deploy` does is create file lists for local and remote by
+traversing the local publish directory and remote bucket.
-Create a storage bucket to deploy your site to. If you want your site to be
-public, be sure to configure the bucket to be publicly readable.
+For both local and remote, the file list includes and excludes files according to
+* If the configuration specifies an `include` pattern, all files
+ are skipped by default except those matching the pattern.
+* If the configuration specifies an `exclude` pattern, files matching the
+ pattern are skipped.
-### Google Cloud Storage (GCS)
-Follow the [GCS instructions for how to create a bucket](https://cloud.google.com/storage/docs/creating-buckets).
+{{% note %}}
+When creating the local file list, a few additional skips apply: first, Hugo always
+skips files named `.DS_Store`.
-### AWS S3
+Second, Hugo always skips local hidden directories
+(directories with names starting with a period, e.g. `.git`) and does not
+traverse into them, except for the special [hidden directory named
+`.well-known`](https://en.wikipedia.org/wiki/Well-known_URI), which is
+traversed if it exists.
+{{% /note %}}
-Follow the [AWS instructions for how to create a bucket](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html).
-### Azure Storage
-Follow the [Azure instructions for how to create a storage container](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal).
+### How the local and remote file lists are compared
-## Configure the deployment
+In the second step, Hugo compares the two file lists to figure out what changes
+actually need to be made on the remote. File names are compared first; if the
+local and remote files both exist then the sizes and md5sums are compared. Any
+difference means that the file will be (re-)uploaded.
-In the configuration file for your site, add a `[deployment]` section with one
-or more `[[deployment.targets]]` section, one for each deployment target. Here's
-a detailed example:
+Specifying the `--force` flag will ensure all files are re-uploaded even
+if Hugo cannot detect any differences between local and remote.
+
+Files are deleted from the remote bucket if they are not present in the local
+file list.
+
+{{% note %}}
+If a remote file is excluded from the file list generation using the
+exclude/include configs, then the comparison step will not know to delete the
+file -- so it will remain on the remote even if it isn't present locally.
+{{% /note %}}
+
+If the [`--confirm` or `--dryRun` flags][commandline] are given, Hugo displays
+what differences it has found and either pauses or stops here.
+
+### How synchronization works
+
+Hugo applies the list of changes to the remote storage bucket. Missing and/or
+changed files are uploaded, and files missing locally but present remotely are
+deleted. As files are uploaded, their headers are also configured on the remote
+according to the matchers configuration.
+
+{{% note %}}
+As a safety measure to help prevent accidents, if there are more than 256 files
+to delete, Hugo won't delete any files from the remote. Use the `--maxDeletes`
+command line flag to override this.
+{{% /note %}}
+
+## Advanced configuration
+
+Here's a full example deployment configuration:
```toml
[deployment]
+
# By default, files are uploaded in an arbitrary order.
-# Files that match the regular expressions in the "Order" list
-# will be uploaded first, in the listed order.
+# If you specify an `order` list, files that match regular expressions
+# in this list will be uploaded first, in the specified order.
order = [".jpg$", ".gif$"]
-
[[deployment.targets]]
+# Define one or more targets, e.g., staging and production.
+# Each target gets its own [[deployment.targets]] section.
+
# An arbitrary name for this target.
name = "mydeployment"
# The Go Cloud Development Kit URL to deploy to. Examples:
+URL = "<FILL ME IN>"
+
# GCS; see https://gocloud.dev/howto/blob/#gcs
-#URL = "gs://<Bucket Name>"
+#URL = "gs://<Bucket Name>"
# S3; see https://gocloud.dev/howto/blob/#s3
# For S3-compatible endpoints, see https://gocloud.dev/howto/blob/#s3-compatible
-#URL = "s3://<Bucket Name>?region=<AWS region>"
+#URL = "s3://<Bucket Name>?region=<AWS region>"
# Azure Blob Storage; see https://gocloud.dev/howto/blob/#azure
-#URL = "azblob://$web"
+#URL = "azblob://$web"
# You can use a "prefix=" query parameter to target a subfolder of the bucket:
-#URL = "gs://<Bucket Name>?prefix=a/subfolder/"
+#URL = "gs://<Bucket Name>?prefix=a/subfolder/"
# If you are using a CloudFront CDN, deploy will invalidate the cache as needed.
-cloudFrontDistributionID = <ID>
+#cloudFrontDistributionID = "<FILL ME IN>"
-# Optionally, you can include or exclude specific files.
-# See https://godoc.org/github.com/gobwas/glob#Glob for the glob pattern syntax.
-# If non-empty, the pattern is matched against the local path.
-# All paths are matched against in their filepath.ToSlash form.
+# Include or exclude specific files when deploying to this target:
# If exclude is non-empty, and a local or remote file's path matches it, that file is not synced.
# If include is non-empty, and a local or remote file's path does not match it, that file is not synced.
-# As a result, local files that don't pass the include/exclude filters are not uploaded to remote,
+# Note: local files that don't pass the include/exclude filters are not uploaded to remote,
# and remote files that don't pass the include/exclude filters are not deleted.
-# include = "**.html" # would only include files with ".html" suffix
-# exclude = "**.{jpg, png}" # would exclude files with ".jpg" or ".png" suffix
+#
+# The pattern syntax is documented here: https://godoc.org/github.com/gobwas/glob#Glob
+# Patterns should be written with forward slashes as separator.
+#
+#include = "**.html" # would only include files with ".html" suffix
+#exclude = "**.{jpg, png}" # would exclude files with ".jpg" or ".png" suffix
+
+#######################
+[[deployment.matchers]]
+# Matchers enable special caching, content type and compression behavior for
+# specified file types. You can include any number of matcher blocks; the first one
+# matching a given file pattern will be used.
-# [[deployment.matchers]] configure behavior for files that match the Pattern.
# See https://golang.org/pkg/regexp/syntax/ for pattern syntax.
# Pattern searching is stopped on first match.
+pattern = "<FILL ME IN>"
+
+# If true, Hugo will gzip the file before uploading it to the bucket.
+# With many storage services, this will save on storage and bandwidth costs
+# for uncompressed file types.
+#gzip = false
+
+# If true, Hugo always re-uploads this file even if size and md5 match.
+# This is useful if Hugo isn't reliably able to determine whether to re-upload
+# the file on its own.
+#force = false
+
+# Content-type header to configure for this file when served.
+# By default this can be determined from the file extension.
+#contentType = ""
+
+# Cache-control header to configure for this file when served.
+# The default is the empty string.
+#cacheControl = ""
+
+# Content-encoding header to configure for this file when served.
+# By default, if gzip is True, this will be filled with "gzip".
**Hugo Modules** are the core building blocks in Hugo. A _module_ can be your main project or a smaller module providing one or more of the 7 component types defined in Hugo: **static**, **content**, **layouts**, **data**, **assets**, **i18n**, and **archetypes**.
@@ -56,7+56,7 @@ env HUGO_MODULE_PROXY=https://proxy.example.org hugo
If your module requires a particular version of Hugo to work, you can indicate that in the `module` section and the user will be warned if using a too old/new version.
Also see the [CLI Doc](/commands/hugo_mod_graph/).
@@ -134,7+133,7 @@ Also see the [CLI Doc](/commands/hugo_mod_clean/).
## Module workspaces
-{{< new-in "0.109.0" >}}
+{{< new-in 0.109.0 >}}
Workspace support was added in [Go 1.18](https://go.dev/blog/get-familiar-with-workspaces) and Hugo got solid support for it in the `v0.109.0` version.
@@ -155,7+154,7 @@ Using the `use` directive, list all the modules you want to work on, pointing to
With that you can start the Hugo server with that workspace enabled:
-```bash
+```sh
HUGO_MODULE_WORKSPACE=hugo.work hugo server --ignoreVendorPaths "**"
Any JavaScript resource file can be transpiled to another JavaScript version using `resources.Babel` which takes for argument the resource object and an optional dict of options listed below. Babel uses the [babel cli](https://babeljs.io/docs/en/babel-cli).
-
{{% note %}}
Hugo Pipe's Babel requires the `@babel/cli` and `@babel/core` JavaScript packages to be installed in the project or globally (`npm install -g @babel/cli @babel/core`) along with any Babel plugin(s) or preset(s) used (e.g., `npm install @babel/preset-env --save-dev`).
@@ -26,7+28,6 @@ If you are using the Hugo Snap package, Babel and plugin(s) need to be installed
We add the main project's `node_modules` to `NODE_PATH` when running Babel and similar tools. There are some known [issues](https://github.com/babel/babel/issues/5618) with Babel in this area, so if you have a `babel.config.js` living in a Hugo Module (and not in the project itself), we recommend using `require` to load the presets/plugins, e.g.:
-: Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration).
-
-minified [bool]
-: Save as many bytes as possible when printing
+config
+: (`string`) Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration).
-noComments [bool]
-: Write comments to generated output (true by default)
+minified
+: (`bool`) Save as many bytes as possible when printing
-compact [bool]
-: Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set.
+noComments
+: (`bool`) Write comments to generated output (true by default)
-verbose [bool]
-: Log everything
+compact
+: (`bool`) Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set.
-sourceMap [string]
-: Output `inline` or `external` sourcemap from the babel compile. External sourcemaps will be written to the target with the output file name + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps.
+verbose
+: (`bool`) Log everything
+sourceMap
+: (`string`) Output `inline` or `external` sourcemap from the babel compile. External sourcemaps will be written to the target with the output file name + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps.
-This is about the global Resources mounted inside `/assets`. For the `.Page` scoped Resources, see [Page Resources](/content-management/page-resources/).
+This is about global and remote resources.
-Note that you can mount any directory into Hugo's virtual `assets` folder using the [Mount Configuration](/hugo-modules/configuration/#module-configuration-mounts).
+global resource
+: A file within the assets directory, or within any directory [mounted] to the assets directory.
-| Function | Description |
-| ------------- | ------------- |
-| `resources.Get` | Get locates the file name given in Hugo's assets filesystem and creates a `Resource` object that can be used for further transformations. See [Get a resource](#get-a-resource). |
-| `resources.GetRemote` | Same as `Get`, but it accepts remote URLs. See [Get a resource](#get-a-resource).|
-| `resources.GetMatch` | `GetMatch` finds the first Resource matching the given pattern, or nil if none found. See Match for a more complete explanation about the rules used. |
-| `resources.Match` | `Match` gets all resources matching the given base path prefix, e.g "*.png" will match all png files. The "*" does not match path delimiters (/), so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: "images/*.png". To match any PNG image anywhere in the bundle you can do "\*\*.png", and to match all PNG images below the images folder, use "images/\*\*.jpg". The matching is case insensitive. Match matches by using the files name with path relative to the file system root with Unix style slashes (/) and no leading slash, e.g. "images/logo.png". See https://github.com/gobwas/glob for the full rules set.|
+remote resource
+: A file on a remote server, accessible via HTTP or HTTPS.
-See the [GoDoc Page](https://pkg.go.dev/github.com/gohugoio/hugo/tpl/resources) for the `resources` package for an up to date overview of all template functions in this namespace.
-
-## Get a resource
-
-In order to process an asset with Hugo Pipes, it must be retrieved as a `Resource` using `resources.Get` or `resources.GetRemote`.
-
-With `resources.Get`, the first argument is a local path relative to the `assets` directory/directories:
-
-```go-html-template
-{{ $local := resources.Get "sass/main.scss" }}
-```
-
-With `resources.GetRemote`, the first argument is a remote URL:
-`resources.Get` and `resources.GetRemote` return `nil` if the resource is not found.
-
-{{< new-in "0.110.0" >}} You can get information about the HTTP Response using `.Data` in the returned `Resource`. This is especially useful for HEAD request without any body. The Data object contains:
-
-StatusCode
-: The HTTP status code, e.g. 200
-
-Status
-: The HTTP status text, e.g. "200 OK"
-
-TransferEncoding
-: The transfer encoding, e.g. "chunked"
-
-ContentLength
-: The content length, e.g. 1234
-
-ContentType
-: The content type, e.g. "text/html"
-
-### Caching
-
-By default, Hugo calculates a cache key based on the `URL` and the `options` (e.g. headers) given.
-
-{{< new-in "0.97.0" >}} You can override this by setting a `key` in the options map. This can be used to get more fine grained control over how often a remote resource is fetched, e.g.:
+For `.Page` scoped resources, see the [page resources] section.
-The return value from `resources.GetRemote` includes an `.Err` method that will return an error if the call failed. If you want to just log any error as a `WARNING` you can use a construct similar to the one below.
-Remote resources fetched with `resources.GetRemote` will be cached on disk. See [Configure File Caches](/getting-started/configuration/#configure-file-caches) for details.
+See the [GoDoc Page](https://pkg.go.dev/github.com/gohugoio/hugo/tpl/resources) for the `resources` package for an up to date overview of all template functions in this namespace.
## Copy a resource
-{{< new-in "0.100.0" >}}
-
-Use `resources.Copy` to copy a page resource or a global resource. Commonly used to change a resource's published path, `resources.Copy` takes two arguments: the target path relative to the root of the `publishDir` (with or without a leading `/`), and the resource to copy.
-The target path must be different than the source path, as shown in the example above. See GitHub issue [#10412](https://github.com/gohugoio/hugo/issues/10412).
-{{% /note %}}
+See the [`resources.Copy`](/functions/resources/copy/) function.
## Asset directory
Asset files must be stored in the asset directory. This is `/assets` by default, but can be configured via the configuration file's `assetDir` key.
-### Asset publishing
+## Asset publishing
Hugo publishes assets to the `publishDir` (typically `public`) when you invoke `.Permalink`, `.RelPermalink`, or `.Publish`. You can use `.Content` to inline the asset.
@@ -158,18+66,6 @@ For improved readability, the Hugo Pipes examples of this documentation will be
-Each Hugo Pipes `resources` transformation method uses a __camelCased__ alias (`toCSS` for `resources.ToCSS`).
-Non-transformation methods deprived of such aliases are `resources.Get`, `resources.FromString`, `resources.ExecuteAsTemplate` and `resources.Concat`.
-
-The example above can therefore also be written as follows:
@@ -36,14+39,14 @@ import * as params from '@params';
Note that this is meant for small data sets, e.g. configuration settings. For larger data, please put/mount the files into `/assets` and import them directly.
-minify [bool]
-: Let `js.Build` handle the minification.
+minify
+: (`bool`) Let `js.Build` handle the minification.
-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
+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:
+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:
- Default is `iife`, a self-executing function, suitable for inclusion as a <script> tag.
+ Default is `iife`, a self-executing function, suitable for inclusion as a `<script>` tag.
-sourceMap [string]
-: Whether to generate `inline` or `external` source maps from esbuild. External source maps will be written to the target with the output file name + ".map". Input source maps can be read from js.Build and node modules and combined into the output source maps. By default, source maps are not created.
+sourceMap
+: (`string`) Whether to generate `inline` or `external` source maps from esbuild. External source maps will be written to the target with the output file name + ".map". Input source maps can be read from js.Build and node modules and combined into the output source maps. By default, source maps are not created.
### Import JS code from /assets
@@ -121,7+123,7 @@ For other files (e.g. `JSON`, `CSS`) you need to use the relative path including
import * as data from 'my/module/data.json';
```
-Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
+Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
Also note the new `params` option that can be passed from template to your JS files, e.g.:
Hugo will, by default, generate a `assets/jsconfig.json` file that maps the imports. This is useful for navigation/intellisense help inside code editors, but if you don't need/want it, you can [turn it off](/getting-started/configuration/#configure-build).
-
### Include dependencies In package.json / node_modules
-Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
+Any imports in a file outside `/assets` or that does not resolve to a component inside `/assets` will be resolved by [ESBuild](https://esbuild.github.io/) with the **project directory** as the resolve directory (used as the starting point when looking for `node_modules` etc.). Also see [hugo mod npm pack](/commands/hugo_mod_npm_pack/). If you have any imported npm dependencies in your project, you need to make sure to run `npm install` before you run `hugo`.
The start directory for resolving npm packages (aka. packages that live inside a `node_modules` folder) is always the main project folder.
-**Note:** If you're developing a theme/component that is supposed to be imported and depends on dependencies inside `package.json`, we recommend reading about [hugo mod npm pack](/commands/hugo_mod_npm_pack/), a tool to consolidate all the npm dependencies in a project.
-
+{{% note %}}
+If you're developing a theme/component that is supposed to be imported and depends on dependencies inside `package.json`, we recommend reading about [hugo mod npm pack](/commands/hugo_mod_npm_pack/), a tool to consolidate all the npm dependencies in a project.
: (`bool`) Default is `false`. Before Hugo 0.99.0 when `inlineImports` was enabled and we failed to resolve an import, we logged it as a warning. We now fail the build. If you have regular CSS imports in your CSS that you want to preserve, you can either use imports with URL or media queries (Hugo does not try to resolve those) or set `skipInlineImportsNotFound` to true.
The current Hugo environment name (set by `--environment` or in configuration or OS environment) is available in the Node context, which allows constructs like this:
@@ -36,7+39,7 @@ There are several ways to set up CSS purging with PostCSS in Hugo. If you have a
The below configuration will write a `hugo_stats.json` file to the project root as part of the build. If you're only using this for the production build, you should consider placing it below [config/production](/getting-started/configuration/#configuration-directory).
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[build.buildStats]
enable = true
{{< /code-toggle >}}
@@ -74,7+77,6 @@ Note that in the example above, the "CSS purge step" will only be applied to the
## Hugo environment variables available in PostCSS
These are the environment variables Hugo passes down to PostCSS (and Babel), which allows you do do `process.env.HUGO_ENVIRONMENT === 'production' ? [autoprefixer] : []` and similar:
: The value e.g. set with `hugo -e production` (defaults to `production` for `hugo` and `development` for `hugo server`).
HUGO_PUBLISHDIR
-: {{< new-in "0.109.0" >}} The absolute path to the publish directory (the `public` directory). Note that the value will always point to a directory on disk even when running `hugo server` in memory mode. If you write to this folder from PostCSS when running the server, you could run the server with one of these flags:
+: {{< new-in 0.109.0 >}} The absolute path to the publish directory (the `public` directory). Note that the value will always point to a directory on disk even when running `hugo server` in memory mode. If you write to this folder from PostCSS when running the server, you could run the server with one of these flags:
Transpile Sass to CSS using the LibSass transpiler included in Hugo's extended edition, or [install Dart Sass](#dart-sass) to use the latest features of the Sass language.
: (`string`) If not set, the transformed resource's target path will be the original path of the asset file with its extension replaced by `.css`.
-vars {{< new-in "0.109.0" >}}
+vars {{< new-in 0.109.0 >}}
: (`map`) A map of key/value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/).
Prebuilt binaries are available for a variety of operating systems and architectures. Visit the [latest release] page, and scroll down to the Assets section.
-<!-- markdownlint-disable-next-line MD051 -->
-1. Download the archive for the desired [edition], operating system, and architecture
+1. Download the archive for the desired edition, operating system, and architecture
1. Extract the archive
1. Move the executable to the desired directory
1. Add this directory to the PATH environment variable
@@ -14,7+17,6 @@ Please consult your operating system documentation if you need help setting file
If you do not see a prebuilt binary for the desired edition, operating system, and architecture, install Hugo using one of the methods described below.
+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 "installation/_common/03-prebuilt-binaries.md" %}}
## Package managers
### Snap
-[Snap] is a free and opensource package manager for Linux. Available for [most distributions], snap packages are simple to install and are automatically updated.
+[Snap] is a free and open-source package manager for Linux. Available for [most distributions], snap packages are simple to install and are automatically updated.
The Hugo snap package is [strictly confined]. Strictly confined snaps run in complete isolation, up to a minimal access level that’s deemed always safe. The sites you create and build must be located within your home directory, or on removable media.
+{{% include "installation/_common/homebrew.md" %}}
## Repository packages
-Most Linux distributions maintain a repository for commonly installed applications. Please note that these repositories may not contain the [latest release].
+Most Linux distributions maintain a repository for commonly installed applications.
+
+{{% note %}}
+Due to Long Term Release (LTR) guidelines, most Linux package repositories will not contain the [latest release].
@@ -92,7+97,6 @@ You can also download Debian packages from the [latest release] page.
Derivatives of the [Fedora] distribution of Linux include [CentOS], [Red Hat Enterprise Linux], and others. This will install the extended edition of Hugo:
+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.
+The `Next` and `Prev` methods on a `Pages` object are more flexible than the `Next` and `Prev` methods on a `Page` object.
+
+||Page collection|Custom sort order
+:--|:--|:-:
+[`PAGES.Next`] and [`PAGES.Prev`]|locally defined|✔️
+[`PAGE.Next`] and [`PAGE.Prev`]|globally defined|❌
+
+[`PAGES.Next`]: /methods/pages/next
+[`PAGES.Prev`]: /methods/pages/prev
+[`PAGE.Next`]: /methods/page/next
+[`PAGE.Prev`]: /methods/page/prev
+
+locally defined
+: Build the page collection every time you call `PAGES.Next` and `PAGES.Prev`. Navigation between pages is relative to the current page's position within the local collection, independent of the global collection.
+
+With a local collection, the navigation sort order is the same as the collection sort order.
+
+globally defined
+: Build the page collection once, on a list page. Navigation between pages is relative to the current page's position within the global collection.
+
+With a global collection, the navigation sort order is fixed, using Hugo's default sort order. In order of precedence:
+
+1. Page [weight]
+2. Page [date] (descending)
+3. Page [linkTitle], falling back to page [title]
+4. Page file path if the page is backed by a file
+
+For example, with a global collection sorted by title, the navigation sort order will use Hugo's default sort order. This is probably not what you want or expect. For this reason, the `Next` and `Prev` methods on a `Pages` object are generally a better choice.
+description: Returns the `identifier` property of the given menu entry.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: string
+ signatures: [MENUENTRY.Identifier]
+---
+
+The `Identifier` method returns the `identifier` property of the menu entry. If you define the menu entry [automatically], it returns the page's section.
+This example uses the `Identifier` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist:
+
+```go-html-template
+<ul>
+ {{ range .Site.Menus.main }}
+ <li><a href="{{ .URL }}">{{ or (T .Identifier) .Name }}</a></li>
+ {{ end }}
+</ul>
+```
+
+{{% note %}}
+In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables.
+description: Returns the `identifier` property of the given menu entry, falling back to its `name` property.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: string
+ signatures: [MENUENTRY.KeyName]
+---
+
+In this menu definition, the second entry does not contain an `identifier`, so the `Identifier` method returns its `name` property instead:
+
+{{< code-toggle file=hugo >}}
+[[menu.main]]
+identifier = 'about'
+name = 'About'
+pageRef = '/about'
+weight = 10
+
+[[menu.main]]
+name = 'Contact'
+pageRef = '/contact'
+weight = 20
+{{< /code-toggle >}}
+
+This example uses the `KeyName` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist:
+In the example above, we need to pass the value returned by `.KeyName` through the [`lower`] function because the keys in the translation table are lowercase.
+description: Returns the identifier of the menu that contains the given menu entry.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/IsMenuCurrent
+ - methods/page/HasMenuCurrent
+ returnType: string
+ signatures: [MENUENTRY.Menu]
+---
+
+```go-html-template
+{{ range .Site.Menus.main }}
+ {{ .Menu }} → main
+{{ end }}
+```
+
+Use this method with the [`IsMenuCurrent`] and [`HasMenuCurrent`] methods on a `Page` object to set "active" and "ancestor" classes on a rendered entry. See [this example].
+description: Returns the `name` property of the given menu entry.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: string
+ signatures: [MENUENTRY.Name]
+---
+
+If you define the menu entry [automatically], the `Name` method returns the page’s [`LinkTitle`], falling back to its [`Title`].
+
+If you define the menu entry [in front matter] or [in site configuration], the `Name` method returns the `name` property, falling back to the page’s `LinkTitle`, then to its `Title`.
+description: Returns the `params` property of the given menu entry.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: maps.Params
+ signatures: [MENUENTRY.Params]
+---
+
+When you define menu entries [in site configuration] or [in front matter], you can include a `params` key to attach additional information to the entry. For example:
+
+{{< code-toggle file=hugo >}}
+[[menu.main]]
+name = 'About'
+pageRef = '/about'
+weight = 10
+
+[[menu.main]]
+name = 'Contact'
+pageRef = '/contact'
+weight = 20
+
+[[menu.main]]
+name = 'Hugo'
+url = 'https://gohugo.io'
+weight = 30
+[menu.main.params]
+ rel = 'external'
+{{< /code-toggle >}}
+
+With this template:
+
+
+```go-html-template
+<ul>
+ {{ range .Site.Menus.main }}
+ <li>
+ <a href="{{ .URL }}" {{ with .Params.rel }}rel="{{ . }}"{{ end }}>
+description: Returns the `title` property of the given menu entry.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: string
+ signatures: [MENUENTRY.Title]
+---
+
+If you define the menu entry [automatically], the `Title` method returns the page’s [`LinkTitle`], falling back to its [`Title`].
+
+If you define the menu entry [in front matter] or [in site configuration], the `Name` method returns the `title` property, falling back to the page’s `LinkTitle`, then to its `Title`.
+description: Returns the `weight` property of the given menu entry.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: int
+ signatures: [MENUENTRY.Weight]
+---
+
+If you define the menu entry [automatically], the `Weight` method returns the page’s [`Weight`].
+
+If you define the menu entry [in front matter] or [in site configuration], the `Weight` method returns the `weight` property, falling back to the page’s `Weight`.
+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.
+description: Returns the given menu with its entries sorted by name.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: navigation.Menu
+ signatures: [MENU.ByName]
+---
+
+The `Sort` method returns the given menu with its entries sorted by `name`.
+
+Consider this menu definition:
+
+{{< code-toggle file=hugo >}}
+[[menu.main]]
+name = 'Services'
+pageRef = '/services'
+weight = 10
+
+[[menu.main]]
+name = 'About'
+pageRef = '/about'
+weight = 20
+
+[[menu.main]]
+name = 'Contact'
+pageRef = '/contact'
+weight = 30
+{{< /code-toggle >}}
+
+To sort the entries by `name`:
+
+```go-html-template
+<ul>
+ {{ range .Site.Menus.main.ByName }}
+ <li><a href="{{ .URL }}">{{ .Name }}</a></li>
+ {{ end }}
+</ul>
+```
+
+Hugo renders this to:
+
+```html
+<ul>
+ <li><a href="/about/">About</a></li>
+ <li><a href="/contact">Contact</a></li>
+ <li><a href="/services/">Services</a></li>
+</ul>
+```
+
+You can also sort menu entries using the [`sort`] function. For example, to sort by `name` in descending order:
+
+```go-html-template
+<ul>
+ {{ range sort .Site.Menus.main "Name" "desc" }}
+ <li><a href="{{ .URL }}">{{ .Name }}</a></li>
+ {{ end }}
+</ul>
+```
+
+When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`.
+description: Returns the given menu with its entries sorted by weight, then by name, then by identifier.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: navigation.Menu
+ signatures: [MENU.ByWeight]
+---
+
+The `ByWeight` method returns the given menu with its entries sorted by [`weight`], then by `name`, then by `identifier`. This is the default sort order.
+
+[`weight`]: /getting-started/glossary/#weight
+
+Consider this menu definition:
+
+{{< code-toggle file=hugo >}}
+[[menu.main]]
+identifier = 'about'
+name = 'About'
+pageRef = '/about'
+weight = 20
+
+[[menu.main]]
+identifier = 'services'
+name = 'Services'
+pageRef = '/services'
+weight = 10
+
+[[menu.main]]
+identifier = 'contact'
+name = 'Contact'
+pageRef = '/contact'
+weight = 30
+{{< /code-toggle >}}
+
+To sort the entries by `weight`, then by `name`, then by `identifier`:
+
+```go-html-template
+<ul>
+ {{ range .Site.Menus.main.ByWeight }}
+ <li><a href="{{ .URL }}">{{ .Name }}</a></li>
+ {{ end }}
+</ul>
+```
+
+Hugo renders this to:
+
+```html
+<ul>
+ <li><a href="/services/">Services</a></li>
+ <li><a href="/about/">About</a></li>
+ <li><a href="/contact">Contact</a></li>
+</ul>
+```
+
+{{% note %}}
+In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables.
+You can also sort menu entries using the [`sort`] function. For example, to sort by `weight` in descending order:
+
+```go-html-template
+<ul>
+ {{ range sort .Site.Menus.main "Weight" "desc" }}
+ <li><a href="{{ .URL }}">{{ .Name }}</a></li>
+ {{ end }}
+</ul>
+```
+
+When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`.
+description: Returns a slice of OutputFormat objects, excluding the current output format, each representing one of the output formats enabled for the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/OutputFormats
+ returnType: page.OutputFormats
+ signatures: [PAGE.AlternativeOutputFormats]
+---
+
+{{% include "methods/page/_common/output-format-definition.md" %}}
+
+The `AlternativeOutputFormats` method on a `Page` object returns a slice of `OutputFormat` objects, excluding the current output format, each representing one of the output formats enabled for the given page.. See [details](/templates/output-formats/).
+
+## Methods
+
+{{% include "methods/page/_common/output-format-methods.md" %}}
+
+## Example
+
+Generate a `link` element in the `<head>` of each page for each of the alternative output formats:
+description: Returns the bundle type of the given page, or an empty string if the page is not a page bundle.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: files.ContentClass
+ signatures: [PAGE.BundleType]
+---
+
+A page bundle is a directory that encapsulates both content and associated [resources]. There are two types of page bundles: [leaf bundles] and [branch bundles]. See [details](/content-management/page-bundles/).
+
+The `BundleType` method on a `Page` object returns `branch` for branch bundles, `leaf` for leaf bundles, and an empty string if the page is not a page bundle.
+description: Returns of slice of code owners for the given page, derived from the CODEOWNERS file in the root of the project directory.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/GitInfo
+ returnType: '[]string'
+ signatures: [PAGE.CodeOwners]
+---
+
+GitHub and GitLab support CODEOWNERS files. This file specifies the users responsible for developing and maintaining software and documentation. This definition can apply to the entire repository, specific directories, or to individual files. To learn more:
+
+- [GitHub CODEOWNERS documentation]
+- [GitLab CODEOWNERS documentation]
+
+Use the `CodeOwners` method on a `Page` object to determine the code owners for the given page.
+The `Data` method is only useful within [taxonomy] and [term] templates.
+
+Themes that are not actively maintained may still use `.Data.Pages` in list templates. Although that syntax remains functional, use one of these methods instead: [`Pages`], [`RegularPages`], or [`RegularPagesRecursive`]
+The date field in front matter is often considered to be the creation date, You can change its meaning, and its effect on your site, in the site configuration. See [details].
+The date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods].
+
+```go-html-template
+{{ .Date | time.Format ":date_medium" }} → Oct 19, 2023
+```
+
+In the example above we explicitly set the date in front matter. With Hugo's default configuration, the `Date` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the date is not defined in front matter. See [details].
+description: Reports whether the given page is a draft as defined in front matter.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: bool
+ signatures: [PAGE.Draft]
+---
+
+By default, Hugo does not publish draft pages when you build your site. To include draft pages when you build your site, use the `--buildDrafts` command line flag.
+The expiry date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods].
+
+```go-html-template
+{{ .ExpiryDate | time.Format ":date_medium" }} → Oct 19, 2024
+```
+
+In the example above we explicitly set the expiry date in front matter. With Hugo's default configuration, the `ExpiryDate` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the expiry date is not defined in front matter. See [details].
+description: For pages backed by a file, returns file information for the given page.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: hugolib.fileInfo
+ signatures: [PAGE.File]
+toc: true
+---
+
+By default, not all pages are backed by a file, including top level [section] pages, [taxonomy] pages, and [term] pages. By definition, you cannot retrieve file information when the file does not exist.
+
+To back one of the pages above with a file, create an _index.md file in the corresponding directory. For example:
+
+```text
+content/
+└── books/
+ ├── _index.md <-- the top level section page
+ ├── book-1.md
+ └── book-2.md
+```
+
+Code defensively by verifying file existence as shown in each of the examples below.
+
+## Methods
+
+{{% note %}}
+The path separators (slash or backslash) in `Path`, `Dir`, and `Filename` depend on the operating system.
+{{% /note %}}
+
+BaseFileName
+: (`string`) The file name, excluding the extension.
+
+```go-html-template
+{{ with .File }}
+ {{ .BaseFileName }}
+{{ end }}
+```
+
+ContentBaseName
+: (`string`) If the page is a branch or leaf bundle, the name of the containing directory, else the `TranslationBaseName`.
+
+```go-html-template
+{{ with .File }}
+ {{ .ContentBaseName }}
+{{ end }}
+```
+
+Dir
+: (`string`) The file path, excluding the file name, relative to the `content` directory.
+
+```go-html-template
+{{ with .File }}
+ {{ .Dir }}
+{{ end }}
+```
+
+Ext
+: (`string`) The file extension.
+
+```go-html-template
+{{ with .File }}
+ {{ .Ext }}
+{{ end }}
+```
+
+Filename
+: (`string`) The absolute file path.
+
+```go-html-template
+{{ with .File }}
+ {{ .Filename }}
+{{ end }}
+```
+
+Lang
+: (`string`) The language associated with the given file.
+
+```go-html-template
+{{ with .File }}
+ {{ .Lang }}
+{{ end }}
+```
+
+LogicalName
+: (`string`) The file name.
+
+```go-html-template
+{{ with .File }}
+ {{ .LogicalName }}
+{{ end }}
+```
+
+Path
+: (`string`) The file path, relative to the `content` directory.
+
+```go-html-template
+{{ with .File }}
+ {{ .Path }}
+{{ end }}
+```
+
+TranslationBaseName
+: (`string`) The file name, excluding the extension and language identifier.
+
+```go-html-template
+{{ with .File }}
+ {{ .TranslationBaseName }}
+{{ end }}
+```
+
+UniqueID
+: (`string`) The MD5 hash of `.File.Path`.
+
+```go-html-template
+{{ with .File }}
+ {{ .UniqueID }}
+{{ end }}
+```
+
+## Examples
+
+Consider this content structure in a multilingual project:
+description: Returns a data structure of the fragments in the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/TableOfContents
+ returnType: tableofcontents.Fragments
+ signatures: [PAGE.Fragments]
+toc: true
+---
+
+{{< new-in 0.111.0 >}}
+
+In a URL, whether absolute or relative, the [fragment] links to an `id` attribute of an HTML element on the page.
+
+```text
+/articles/article-1#section-2
+------------------- ---------
+ path fragment
+```
+
+Hugo assigns an `id` attribute to each markdown [ATX] and [setext] heading within the page content. You can override the `id` with a [markdown attribute] as needed. This creates the relationship between an entry in the [table of contents] (TOC) and a heading on the page.
+
+Use the `Fragments` method on a `Page` object to create a table of contents with the `Fragments.ToHTML` method, or by [walking] the `Fragments.Map` data structure.
+
+## Methods
+
+Headings
+: (`map`) A nested map of all headings on the page. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure:
+: (`slice`) A slice of maps of all headings on the page, with first-level keys for each heading. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure:
+: (`bool`) Reports whether one or more headings on the page has the given `id` attribute, useful for validating fragments within a link [render hook].
+: (`template.HTML`) Returns a TOC as a nested list, either ordered or unordered, identical to the HTML returned by the [`TableOfContents`] method. This method take three arguments: the start level (`int`), the end level (`int`), and a boolean (`true` to return an ordered list, `false` to return an unordered list).
+
+Use this method when you want to control the start level, end level, or list type independently from the table of contents settings in your site configuration.
+It is safe to use the `Fragments` methods within a render hook, even for the current page.
+
+When using the `Fragments` methods within a shortcode, call the shortcode using the `{{</* */>}}` notation. If you use the `{{%/* */%}}` notation, the rendered shortcode is included in the creation of the fragments map, resulting in a circular loop.
+description: Returns a collection of term pages for terms defined on the given page in the given taxonomy, ordered according to the sequence in which they appear in front matter.
+description: Returns Git information related to the last commit of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/CodeOwners
+ returnType: source.GitInfo
+ signatures: [PAGE.GitInfo]
+toc: true
+---
+
+The `GitInfo` method on a `Page` object returns an object with additional methods.
+
+{{% note %}}
+Hugo's Git integration is performant, but may increase build times on large sites.
+{{% /note %}}
+
+## Prerequisites
+
+Install [Git], create a repository, and commit your project files.
+
+You must also allow Hugo to access your repository. In your site configuration:
+
+{{< code-toggle file=hugo >}}
+enableGitInfo = true
+{{< /code-toggle >}}
+
+Alternatively, use the command line flag when building your site:
+
+```sh
+hugo --enableGitInfo
+```
+
+{{% note %}}
+When you set `enableGitInto` to `true`, or enable the feature with the command line flag, the last modification date for each content page will be the Author Date of the last commit for that file.
+By default, when `enableGitInfo` is `true`, the `Lastmod` method on a `Page` object returns the Git AuthorDate of the last commit that included the file.
+
+You can change this behavior in your [site configuration].
+When hosting your site in a CI/CD environment, the step that clones your project repository must perform a deep clone. If the clone is shallow, the Git information for a given file may not be accurate---it may reflect the most recent repository commit, not the commit that last modified the file.
+
+Some providers perform deep clones by default, others allow you to configure the clone depth, and some providers only perform shallow clones.
+
+Hosting service | Default clone depth | Configurable
+:-- | :-- | :--
+Cloudflare Pages | Shallow | Yes [^CFP]
+DigitalOcean App Platform | Deep | N/A
+GitHub Pages | Shallow | Yes [^GHP]
+GitLab Pages | Shallow | Yes [^GLP]
+Netlify | Deep | N/A
+Render | Shallow | No
+Vercel | Shallow | No
+
+[^CFP]: To configure a Cloudflare Pages site for deep cloning, preface the site's normal Hugo build command with `git fetch --unshallow &&` (*e.g.*, `git fetch --unshallow && hugo`).
+
+[^GHP]: You can configure the GitHub Action to do a deep clone by specifying `fetch-depth: 0` in the applicable "checkout" step of your workflow file, as shown in the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-github/#procedure).
+
+[^GLP]: You can configure the GitLab Runner's clone depth [as explained in the GitLab documentation](https://docs.gitlab.com/ee/ci/large_repositories/#shallow-cloning); see also the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-gitlab/#configure-gitlab-cicd).
+description: Reports whether the given page object matches the page object associated with one of the child menu entries under the given menu entry in the given menu.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/IsMenuCurrent
+ returnType: bool
+ signatures: [PAGE.HasMenuCurrent MENU MENUENTRY]
+aliases: [/functions/hasmenucurrent]
+---
+
+If the page object associated with the menu entry is a section, this method also returns `true` for any descendant of that section.
+description: Reports whether the given page is in the given section.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Ancestors
+ - methods/page/CurrentSection
+ - methods/page/FirstSection
+ - methods/page/IsAncestor
+ - methods/page/IsDescendant
+ - methods/page/Parent
+ - methods/page/Sections
+ returnType: bool
+ signatures: [PAGE.InSection SECTION]
+toc: true
+---
+
+The `InSection` method on a page object reports whether the given page is in the given section. Note that the method returns `true` when comparing a page to a sibling.
+
+{{% include "methods/page/_common/definition-of-section.md" %}}
+
+With this content structure:
+
+```text
+content/
+├── auctions/
+│ ├── 2023-11/
+│ │ ├── _index.md
+│ │ ├── auction-1.md
+│ │ └── auction-2.md
+│ ├── 2023-12/
+│ │ ├── _index.md
+│ │ ├── auction-3.md
+│ │ └── auction-4.md
+│ ├── _index.md
+│ ├── bidding.md
+│ └── payment.md
+└── _index.md
+```
+
+When rendering the "auction-1" page:
+
+```go-html-template
+{{ with .Site.GetPage "/" }}
+ {{ $.InSection . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.InSection . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11" }}
+ {{ $.InSection . }} → true
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
+ {{ $.InSection . }} → true
+{{ end }}
+```
+
+In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting:
+
+```go-html-template
+{{ $path := "/auctions/2023-11" }}
+{{ with .Site.GetPage $path }}
+ {{ $.InSection . }} → true
+{{ else }}
+ {{ errorf "Unable to find the section with path %s" $path }}
+{{ end }}
+ ```
+
+## Understanding context
+
+Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax:
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ .InSection . }} → true
+{{ end }}
+```
+
+The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself.
+
+{{% note %}}
+Use the `$` to get the context passed into the template.
+{{% /note %}}
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.InSection . }} → true
+{{ end }}
+```
+
+{{% note %}}
+Gaining a thorough understanding of context is critical for anyone writing template code.
+description: Reports whether PAGE1 in an ancestor of PAGE2.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Ancestors
+ - methods/page/CurrentSection
+ - methods/page/FirstSection
+ - methods/page/InSection
+ - methods/page/IsDescendant
+ - methods/page/Parent
+ - methods/page/Sections
+ returnType: bool
+ signatures: [PAGE1.IsAncestor PAGE2]
+toc: true
+---
+
+{{% include "methods/page/_common/definition-of-section.md" %}}
+
+With this content structure:
+
+```text
+content/
+├── auctions/
+│ ├── 2023-11/
+│ │ ├── _index.md
+│ │ ├── auction-1.md
+│ │ └── auction-2.md
+│ ├── 2023-12/
+│ │ ├── _index.md
+│ │ ├── auction-3.md
+│ │ └── auction-4.md
+│ ├── _index.md
+│ ├── bidding.md
+│ └── payment.md
+└── _index.md
+```
+
+When rendering the "auctions" page:
+
+```go-html-template
+{{ with .Site.GetPage "/" }}
+ {{ $.IsAncestor . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.IsAncestor . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11" }}
+ {{ $.IsAncestor . }} → true
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
+ {{ $.IsAncestor . }} → true
+{{ end }}
+```
+
+In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting:
+
+```go-html-template
+{{ $path := "/auctions/2023-11" }}
+{{ with .Site.GetPage $path }}
+ {{ $.IsAncestor . }} → true
+{{ else }}
+ {{ errorf "Unable to find the section with path %s" $path }}
+{{ end }}
+ ```
+
+## Understanding context
+
+Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax:
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ .IsAncestor . }} → true
+{{ end }}
+```
+
+The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself.
+
+{{% note %}}
+Use the `$` to get the context passed into the template.
+{{% /note %}}
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.IsAncestor . }} → true
+{{ end }}
+```
+
+{{% note %}}
+Gaining a thorough understanding of context is critical for anyone writing template code.
+description: Reports whether PAGE1 in a descendant of PAGE2.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Ancestors
+ - methods/page/CurrentSection
+ - methods/page/FirstSection
+ - methods/page/InSection
+ - methods/page/IsAncestor
+ - methods/page/Parent
+ - methods/page/Sections
+ returnType: bool
+ signatures: [PAGE1.IsDescendant PAGE2]
+---
+
+{{% include "methods/page/_common/definition-of-section.md" %}}
+
+With this content structure:
+
+```text
+content/
+├── auctions/
+│ ├── 2023-11/
+│ │ ├── _index.md
+│ │ ├── auction-1.md
+│ │ └── auction-2.md
+│ ├── 2023-12/
+│ │ ├── _index.md
+│ │ ├── auction-3.md
+│ │ └── auction-4.md
+│ ├── _index.md
+│ ├── bidding.md
+│ └── payment.md
+└── _index.md
+```
+
+When rendering the "auctions" page:
+
+```go-html-template
+{{ with .Site.GetPage "/" }}
+ {{ $.IsDescendant . }} → true
+{{ end }}
+
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.IsDescendant . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11" }}
+ {{ $.IsDescendant . }} → false
+{{ end }}
+
+{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
+ {{ $.IsDescendant . }} → false
+{{ end }}
+```
+
+In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting:
+
+```go-html-template
+{{ $path := "/auctions/2023-11" }}
+{{ with .Site.GetPage $path }}
+ {{ $.IsDescendant . }} → true
+{{ else }}
+ {{ errorf "Unable to find the section with path %s" $path }}
+{{ end }}
+ ```
+
+## Understanding context
+
+Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax:
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ .IsDescendant . }} → true
+{{ end }}
+```
+
+The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself.
+
+{{% note %}}
+Use the `$` to get the context passed into the template.
+{{% /note %}}
+
+```go-html-template
+{{ with .Site.GetPage "/auctions" }}
+ {{ $.IsDescendant . }} → true
+{{ end }}
+```
+
+{{% note %}}
+Gaining a thorough understanding of context is critical for anyone writing template code.
+description: Returns the language object for the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/site/Language
+ returnType: langs.Language
+ signatures: [PAGE.Language]
+---
+
+The `Language` method on a `Page` object returns the language object for the given page. The language object points to the language definition in the site configuration.
+
+You can also use the `Language` method on a `Site` object. See [details].
+
+## Methods
+
+The examples below assume the following in your site configuration:
+
+{{< code-toggle file=hugo >}}
+[languages.de]
+languageCode = 'de-DE'
+languageDirection = 'ltr'
+languageName = 'Deutsch'
+weight = 2
+{{< /code-toggle >}}
+
+Lang
+: (`string`) The language tag as defined by [RFC 5646].
+
+```go-html-template
+{{ .Language.Lang }} → de
+```
+
+LanguageCode
+: (`string`) The language code from the site configuration.
+
+```go-html-template
+{{ .Language.LanguageCode }} → de-DE
+```
+
+LanguageDirection
+: (`string`) The language direction from the site configuration, either `ltr` or `rtl`.
+
+```go-html-template
+{{ .Language.LanguageDirection }} → ltr
+```
+
+LanguageName
+: (`string`) The language name from the site configuration.
+
+```go-html-template
+{{ .Language.LanguageName }} → Deutsch
+```
+
+Weight
+: (`int`) The language weight from the site configuration which determines its order in the slice of languages returned by the `Languages` method on a `Site` object.
+The last modification date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods].
+
+```go-html-template
+{{ .Lastmod | time.Format ":date_medium" }} → Oct 19, 2023
+```
+
+In the example above we explicitly set the last modification date in front matter. With Hugo's default configuration, the `Lastmod` method returns the front matter value. This behavior is configurable, allowing you to:
+
+- Set the last modification date to the Author Date of the last Git commit for that file. See [`GitInfo`] for details.
+- Set fallback values if the last modification date is not defined in front matter.
+title = 'Seventeen delightful recipes for healthy desserts'
+linkTitle = 'Dessert recipes'
+{{< /code-toggle >}}
+
+```go-html-template
+{{ .LinkTitle }} → Dessert recipes
+```
+
+As demonstrated above, defining a link title in front matter is advantageous when the page title is long. Use it when generating anchor elements in your templates:
+description: Returns the next page within a section, relative to the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/PrevInSection
+ - methods/page/Next
+ - methods/page/Prev
+ - methods/pages/Next
+ - methods/pages/Prev
+ returnType: hugolib.pageState
+ signatures: [PAGE.NextInSection]
+---
+
+The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect.
+
+With this content structure:
+
+```text
+content/
+├── books/
+│ ├── _index.md
+│ ├── book-1.md
+│ ├── book-2.md
+│ └── book-3.md
+├── films/
+│ ├── _index.md
+│ ├── film-1.md
+│ ├── film-2.md
+│ └── film-3.md
+└── _index.md
+```
+
+When you visit book-2:
+
+- The `PrevInSection` method points to book-3
+- The `NextInSection` method points to book-1
+
+{{% note %}}
+Use the opposite label in your navigation links as shown in the example below.
+{{% /note %}}
+
+```go-html-template
+{{ with .NextInSection }}
+ <a href="{{ .RelPermalink }}">Previous in section</a>
+{{ end }}
+
+{{ with .PrevInSection }}
+ <a href="{{ .RelPermalink }}">Next in section</a>
+{{ end }}
+```
+
+{{% note %}}
+The navigation sort order may be different than the page collection sort order.
+{{% /note %}}
+
+With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence:
+
+1. Page [weight]
+2. Page [date] (descending)
+3. Page [linkTitle], falling back to page [title]
+4. Page file path if the page is backed by a file
+
+For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice.
+description: Returns a slice of OutputFormat objects, each representing one of the output formats enabled for the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/AlternativeOutputFormats
+ returnType: '[]OutputFormat'
+ signatures: [PAGE.OutputFormats]
+toc: true
+---
+
+{{% include "methods/page/_common/output-format-definition.md" %}}
+
+The `OutputFormats` method on a `Page` object returns a slice of `OutputFormat` objects, each representing one of the output formats enabled for the given page. See [details](/templates/output-formats/).
+
+## Methods
+
+{{% include "methods/page/_common/output-format-methods.md" %}}
+
+## Example
+
+To link to the RSS feed for the current page:
+
+```go-html-template
+{{ with .OutputFormats.Get "rss" -}}
+ <a href="{{ .RelPermalink }}">RSS Feed</a>
+{{ end }}
+```
+
+On the site's home page, Hugo renders this to:
+
+```html
+<a href="/index.xml">RSS Feed</a>
+```
+
+Please see the [link to output formats] section to understand the importance of the construct above.
+
+[link to output formats]: /templates/output-formats/#link-to-output-formats
+description: Returns the Page object of the given page.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: hugolib.pageState
+ signatures: [PAGE.Page]
+---
+
+This is a convenience method, useful within partial templates that are called from both [shortcodes] and page templates.
+
+{{< code file=layouts/shortcodes/foo.html >}}
+{{ partial "my-partial.html" . }}
+{{< /code >}}
+
+When the shortcode calls the partial, it passes the current [context] (the dot). The context includes identifiers such as `Page`, `Params`, `Inner`, and `Name`.
+
+{{< code file=layouts/_default/single.html >}}
+{{ partial "my-partial.html" . }}
+{{< /code >}}
+
+When the page template calls the partial, it also passes the current context (the dot). But in this case, the dot _is_ the `Page` object.
+description: Returns a collection of regular pages within the current section, and section pages of immediate descendant sections.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/RegularPages
+ - methods/page/RegularPagesRecursive
+ returnType: page.Pages
+ signatures: [PAGE.Pages]
+---
+
+The `Pages` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context].
+
+Range through the page collection in your template:
+When rendering the home page, the `Pages` method returns:
+
+ contact.md
+ legal.md
+ lessons/_index.md
+
+When rendering the lessons page, the `Pages` method returns:
+
+ lessons/grading-policy.md
+ lessons/lesson-plan.md
+ lessons/lesson-1/_index.md
+ lessons/lesson-2/_index.md
+
+When rendering lesson-1, the `Pages` method returns:
+
+ lessons/lesson-1/part-1.md
+ lessons/lesson-1/part-2.md
+
+When rendering lesson-2, the `Pages` method returns:
+
+ lessons/lesson-2/part-1.md
+ lessons/lesson-2/part-2.md
+ lessons/lesson-2/resources/task-list.md
+ lessons/lesson-2/resources/worksheet.md
+
+In the last example, the collection includes pages in the resources subdirectory. That directory is not a [section]---it does not contain an _index.md file. Its contents are part of the lesson-2 section.
+
+{{% note %}}
+When used with a `Site` object, the `Pages` method recursively returns all pages within the site. See [details].
+[Pagination] is the process of splitting a list page into two or more pagers, where each pager contains a subset of the page collection and navigation links to other pagers.
+
+By default, the number of elements on each pager is determined by the value of the `paginate` setting in your site configuration. The default value is `10`. Override the value in your site configuration by providing a second argument, an integer, when calling the `Paginate` method.
+
+{{% note %}}
+There is also a `Paginator` method on `Page` objects, but it can neither filter nor sort the page collection.
+
+The `Paginate` method is more flexible.
+{{% /note %}}
+
+You can invoke pagination on the home page template, [`section`] templates, [`taxonomy`] templates, and [`term`] templates.
+
+{{< code file=layouts/_default/list.html >}}
+{{ $pages := where .Site.RegularPages "Section" "articles" }}
+3. Paginate the collection, with 7 elements per pager
+4. Range over the paginated page collection, rendering a link to each page
+5. Call the internal "pagination" template to create the navigation links between pagers.
+
+{{% note %}}
+Please note that the results of pagination are cached. Once you have invoked either the `Paginator` or `Paginate` method, the paginated collection is immutable. Additional invocations of these methods will have no effect.
+description: Paginates the collection of regular pages received in context.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Paginate
+ returnType: page.Pager
+ signatures: [PAGE.Paginator]
+---
+
+[Pagination] is the process of splitting a list page into two or more pagers, where each pager contains a subset of the page collection and navigation links to other pagers. The number of elements on each pager is determined by the value of the `paginate` setting in your site configuration. The default value is `10`.
+
+You can invoke pagination on the home page template, [`section`] templates, [`taxonomy`] templates, and [`term`] templates. Each of these receive a collection of regular pages in [context]. When you invoke the `Paginator` method, it paginates the page collection received in context.
+In the example above, the internal "pagination" template creates the navigation links between pagers.
+
+{{% note %}}
+Although simple to invoke, with the `Paginator` method you can neither filter nor sort the page collection. It acts upon the page collection received in context.
+
+The [`Paginate`] method is more flexible, and strongly recommended.
+
+[`paginate`]: /methods/page/paginate
+{{% /note %}}
+
+{{% note %}}
+Please note that the results of pagination are cached. Once you have invoked either the `Paginator` or `Paginate` method, the paginated collection is immutable. Additional invocations of these methods will have no effect.
+description: Returns a page parameter with the given key, falling back to a site parameter if present.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: any
+ signatures: [PAGE.Param KEY]
+aliases: [/functions/param]
+---
+
+The `Param` method on a `Page` object looks for the given `KEY` in page parameters, and returns the corresponding value. If it cannot find the `KEY` in page parameters, it looks for the `KEY` in site parameters. If it cannot find the `KEY` in either location, the `Param` method returns `nil`.
+
+Site and theme developers commonly set parameters at the site level, allowing content authors to override those parameters at the page level.
+
+For example, to show a table of contents on every page, but allow authors to hide the table of contents as needed:
+The `Param` method returns the value associated with the given `KEY`, regardless of whether the value is truthy or falsy. If you need to ignore falsy values, use this construct instead:
+The `title` and `date` fields are standard parameters---the other fields are user-defined.
+
+Access the custom parameters by [chaining] the [identifiers]:
+
+```go-html-template
+{{ .Params.display_related }} → true
+{{ .Params.author.name }} → John Smith
+```
+
+In the template example above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function:
+description: Returns the Page object of the parent section of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Ancestors
+ - methods/page/CurrentSection
+ - methods/page/FirstSection
+ - methods/page/InSection
+ - methods/page/IsAncestor
+ - methods/page/IsDescendant
+ - methods/page/Sections
+ returnType: hugolib.pageState
+ signatures: [PAGE.Parent]
+---
+
+{{% include "methods/page/_common/definition-of-section.md" %}}
+
+{{% note %}}
+The parent section of a regular page is the [current section].
+
+[current section]: /methods/page/currentsection
+{{% /note %}}
+
+Consider this content structure:
+
+```text
+content/
+├── auctions/
+│ ├── 2023-11/
+│ │ ├── _index.md <-- parent: auctions
+│ │ ├── auction-1.md
+│ │ └── auction-2.md <-- parent: 2023-11
+│ ├── 2023-12/
+│ │ ├── _index.md
+│ │ ├── auction-3.md
+│ │ └── auction-4.md
+│ ├── _index.md <-- parent: home
+│ ├── bidding.md
+│ └── payment.md <-- parent: auctions
+├── books/
+│ ├── _index.md <-- parent: home
+│ ├── book-1.md
+│ └── book-2.md <-- parent: books
+├── films/
+│ ├── _index.md <-- parent: home
+│ ├── film-1.md
+│ └── film-2.md <-- parent: films
+└── _index.md <-- parent: nil
+```
+
+In the example above, note the parent section of the home page is nil. Code defensively by verifying existence of the parent section before calling methods on its `Page` object. To create a link to the parent section page of the current page:
+description: Returns the rendered content of the given page, removing all HTML tags.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Content
+ - methods/page/RawContent
+ - methods/page/PlainWords
+ - methods/page/RenderShortcodes
+ returnType: string
+ signatures: [PAGE.Plain]
+---
+
+The `Plain` method on a `Page` object renders markdown and [shortcodes] to HTML, then strips the HTML [tags]. It does not strip HTML [entities]. The plain content does not include front matter.
+
+To prevent Go's [html/template] package from escaping HTML entities, pass the result through the [`htmlUnescape`] function.
+description: Calls the Plain method, splits the result into a slice of words, and returns the slice.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Content
+ - methods/page/RawContent
+ - methods/page/Plain
+ returnType: '[]string'
+ signatures: [PAGE.PlainWords]
+---
+
+The `PlainWords` method on a `Page` object calls the [`Plain`] method, then uses Go's [`strings.Fields`] function to split the result into words.
+
+{{% note %}}
+_Fields splits the string s around each instance of one or more consecutive white space characters, as defined by [`unicode.IsSpace`], returning a slice of substrings of s or an empty slice if s contains only white space._
+description: Returns the previous page within a section, relative to the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/NextInSection
+ - methods/page/Next
+ - methods/pages/Next
+ - methods/page/Prev
+ - methods/pages/Prev
+ returnType: hugolib.pageState
+ signatures: [PAGE.PrevInSection]
+---
+
+
+The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect.
+
+With this content structure:
+
+```text
+content/
+├── books/
+│ ├── _index.md
+│ ├── book-1.md
+│ ├── book-2.md
+│ └── book-3.md
+├── films/
+│ ├── _index.md
+│ ├── film-1.md
+│ ├── film-2.md
+│ └── film-3.md
+└── _index.md
+```
+
+When you visit book-2:
+
+- The `PrevInSection` method points to book-3
+- The `NextInSection` method points to book-1
+
+{{% note %}}
+Use the opposite label in your navigation links as shown in the example below.
+{{% /note %}}
+
+```go-html-template
+{{ with .NextInSection }}
+ <a href="{{ .RelPermalink }}">Previous in section</a>
+{{ end }}
+
+{{ with .PrevInSection }}
+ <a href="{{ .RelPermalink }}">Next in section</a>
+{{ end }}
+```
+
+{{% note %}}
+The navigation sort order may be different than the page collection sort order.
+{{% /note %}}
+
+With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence:
+
+1. Page [weight]
+2. Page [date] (descending)
+3. Page [linkTitle], falling back to page [title]
+4. Page file path if the page is backed by a file
+
+For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice.
+description: Returns the publish date of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Date
+ - methods/page/ExpiryDate
+ - methods/page/LastMod
+ returnType: time.Time
+ signatures: [PAGE.PublishDate]
+---
+
+By default, Hugo excludes pages with future publish dates when building your site. To include future pages, use the `--buildFuture` command line flag.
+The publish date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods].
+
+```go-html-template
+{{ .PublishDate | time.Format ":date_medium" }} → Oct 19, 2023
+```
+
+In the example above we explicitly set the publish date in front matter. With Hugo's default configuration, the `PublishDate` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the publish date is not defined in front matter. See [details].
+description: Returns the raw content of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Content
+ - methods/page/Plain
+ - methods/page/PlainWords
+ - methods/page/RenderShortcodes
+ returnType: string
+ signatures: [PAGE.RawContent]
+---
+
+The `RawContent` method on a `Page` object returns the raw content. The raw content does not include front matter.
+
+```go-html-template
+{{ .RawContent }}
+```
+
+This is useful when rendering a page in a plain text [output format].
+
+{{% note %}}
+[Shortcodes] within the content are not rendered. To get the raw content with shortcodes rendered, use the [`RenderShortcodes`] method on a `Page` object.
+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.
+description: Returns a collection of regular pages within the current section.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Pages
+ - methods/page/RegularPagesRecursive
+ returnType: page.Pages
+ signatures: [PAGE.RegularPages]
+---
+
+The `RegularPages` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context].
+
+Range through the page collection in your template:
+When rendering the home page, the `RegularPages` method returns:
+
+ contact.md
+ legal.md
+
+When rendering the lessons page, the `RegularPages` method returns:
+
+ lessons/grading-policy.md
+ lessons/lesson-plan.md
+
+When rendering lesson-1, the `RegularPages` method returns:
+
+ lessons/lesson-1/part-1.md
+ lessons/lesson-1/part-2.md
+
+When rendering lesson-2, the `RegularPages` method returns:
+
+ lessons/lesson-2/part-1.md
+ lessons/lesson-2/part-2.md
+ lessons/lesson-2/resources/task-list.md
+ lessons/lesson-2/resources/worksheet.md
+
+In the last example, the collection includes pages in the resources subdirectory. That directory is not a [section]---it does not contain an _index.md file. Its contents are part of the lesson-2 section.
+
+{{% note %}}
+When used with the `Site` object, the `RegularPages` method recursively returns all regular pages within the site. See [details].
+description: Returns a collection of regular pages within the current section, and regular pages within all descendant sections.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Pages
+ - methods/page/RegularPages
+ returnType: page.Pages
+ signatures: [PAGE.RegularPagesRecursive]
+---
+
+The `RegularPagesRecursive` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context].
+
+Range through the page collection in your template:
+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.
+description: Renders the given template with the given page as context.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/partials/Include
+ - functions/partials/IncludeCached
+ returnType: template.HTML
+ signatures: [PAGE.Render NAME]
+aliases: [/functions/render]
+---
+
+Typically used when ranging over a page collection, the `Render` method on a `Page` object renders the given template, passing the given page as context.
+In the example above, note that the template ("summary") is identified by its file name without directory or extension.
+
+Although similar to the [`partial`] function, there are key differences.
+
+`Render` method|`partial` function|
+:--|:--
+The `Page` object is automatically passed to the given template. You cannot pass additional context.| You must specify the context, allowing you to pass a combination of objects, slices, maps, and scalars.
+The path to the template is determined by the [content type].|You must specify the path to the template, relative to the layouts/partials directory.
+
+Consider this layout structure:
+
+```text
+layouts/
+├── _default/
+│ ├── baseof.html
+│ ├── home.html
+│ ├── li.html <-- used for other content types
+│ ├── list.html
+│ ├── single.html
+│ └── summary.html
+└── books/
+ ├── li.html <-- used when content type is "books"
+ └── summary.html
+```
+
+And this template:
+
+```go-html-template
+<ul>
+ {{ range site.RegularPages.ByDate }}
+ {{ .Render "li" }}
+ {{ end }}
+</ul>
+```
+
+When rendering content of type "books" the `Render` method calls:
+
+```text
+layouts/books/li.html
+```
+
+For all other content types the `Render` methods calls:
+description: Renders all shortcodes in the content of the given page, preserving the surrounding markup.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/RenderString
+ - methods/page/Content
+ - methods/page/RawContent
+ - methods/page/Plain
+ - methods/page/PlainWords
+ returnType: template.HTML
+ signatures: [PAGE.RenderShortcodes]
+toc: true
+---
+
+{{< new-in 0.117.0 >}}
+
+Use this method in shortcode templates to compose a page from multiple content files, while preserving a global context for footnotes and the table of contents.
+{{ $s | .RenderString }} → An <em>emphasized</em> word
+```
+
+This method takes an optional map of options:
+
+display
+: (`string`) Specify either `inline` or `block`. If `inline`, removes surrounding `p` tags from short snippets. Default is `inline`.
+
+markup
+: (`string`) Specify a [markup identifier] for the provided markup. Default is the `markup` front matter value, falling back to the value derived from the page's file extension.
+
+Render with the default markup renderer:
+
+```go-html-template
+{{ $s := "An *emphasized* word" }}
+{{ $s | .RenderString }} → An <em>emphasized</em> word
+description: Returns a collection of page resources.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/resources/ByType
+ - functions/resources/Get
+ - functions/resources/GetMatch
+ - functions/resources/GetRemote
+ - functions/resources/Match
+ returnType: resource.Resources
+ signatures: [PAGE.Resources]
+toc: true
+---
+
+The `Resources` method on a `Page` object returns a collection of page resources. A page resource is a file within a [page bundle].
+
+To work with global or remote resources, see the [`resources`] functions.
+
+## Methods
+
+ByType
+: (`resource.Resources`) Returns a collection of page resources of the given [media type], or nil if none found. The media type is typically one of `image`, `text`, `audio`, `video`, or `application`.
+The `Scratch` method on a `Page` object creates a [scratch pad] to store and manipulate data. To create a scratch pad that is not reset on server rebuilds, use the [`Store`] method instead.
+
+To create a locally scoped scratch pad that is not attached to a `Page` object, use the [`newScratch`] function.
+However, if the `type` field in front matter has been defined on one or more pages, the page collection based on `Type` will be different than the page collection based on `Section`.
+description: Returns the sitemap settings for the given page as defined in front matter, falling back to the sitemap settings as defined in the site configuration.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: config.SitemapConfig
+ signatures: [PAGE.Sitemap]
+toc: true
+---
+
+Access to the `Sitemap` method on a `Page` object is restricted to [sitemap templates].
+
+## Methods
+
+ChangeFreq
+: (`string`) How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. Default is "" (change frequency omitted from rendered sitemap).
+
+```go-html-template
+{{ .Sitemap.ChangeFreq }}
+```
+
+Priority
+: (`float`) The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. Default is -1 (priority omitted from rendered sitemap).
+description: Creates a persistent "scratch pad" on the given page to store and manipulate data.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/scratch
+ - functions/collections/NewScratch
+ returnType: maps.Scratch
+ signatures: [PAGE.Store]
+aliases: [/functions/store]
+---
+
+The `Store` method on a `Page` object creates a persistent [scratch pad] to store and manipulate data. In contrast with the [`Scratch`] method, the scratch pad created by the `Store` method is not reset on server rebuilds.
+
+To create a locally scoped scratch pad that is not attached to a `Page` object, use the [`newScratch`] function.
+: Adds a given value to existing value(s) of the given key.
+
+: For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
+description: Returns the content summary of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Truncated
+ - methods/page/Description
+ returnType: template.HTML
+ signatures: [PAGE.Summary]
+---
+
+There are three ways to define the [content summary]:
+
+1. Let Hugo create the summary based on the first 70 words. You can change the number of words by setting the `summaryLength` in your site configuration.
+2. Manually split the content with a `<--more-->` tag in markdown. Everything before the tag is included in the summary.
+3. Create a `summary` field in front matter.
+
+To list the pages in a section with a summary beneath each link:
+description: Returns a table of contents for the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Fragments
+ returnType: template.HTML
+ signatures: [PAGE.TableOfContents]
+---
+
+The `TableOfContents` method on a `Page` object returns an ordered or unordered list of the markdown [ATX] and [setext] headings within the page content.
+description: Returns the translation key of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Translations
+ - methods/page/AllTranslations
+ - methods/page/IsTranslated
+ returnType: string
+ signatures: [PAGE.TranslationKey]
+---
+
+The translation key creates a relationship between all translations of a given page. The translation key is derived from the file path, or from the `translationKey` parameter if defined in front matter.
+description: Reports whether the content length exceeds the summary length.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Summary
+ returnType: bool
+ signatures: [PAGE.Truncated]
+---
+
+There are three ways to define the [content summary]:
+
+1. Let Hugo create the summary based on the first 70 words. You can change the number of words by setting the `summaryLength` in your site configuration.
+2. Manually split the content with a `<--more-->` tag in markdown. Everything before the tag is included in the summary.
+3. Create a `summary` field in front matter.
+
+{{% note %}}
+The `Truncated` method returns `false` if you define the summary in front matter.
+{{% /note %}}
+
+The `Truncated` method returns `true` if the content length exceeds the summary length. This is useful for rendering a "read more" link:
+description: Returns the content type of the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/Kind
+ - methods/page/Layout
+ - methods/page/Type
+ returnType: string
+ signatures: [PAGE.Type]
+---
+
+The `Type` method on a `Page` object returns the [content type] of the given page. The content type is defined by the `type` field in front matter, or inferred from the top-level directory name if the `type` field in front matter is not defined.
+
+With this content structure:
+
+```text
+content/
+├── auction/
+│ ├── _index.md
+│ ├── item-1.md
+│ └── item-2.md <-- front matter: type = books
+├── books/
+│ ├── _index.md
+│ ├── book-1.md
+│ └── book-2.md
+├── films/
+│ ├── _index.md
+│ ├── film-1.md
+│ └── film-2.md
+└── _index.md
+```
+
+To list the books, regardless of [section]:
+
+```go-html-template
+{{ range where .Site.RegularPages.ByTitle "Type" "books" }}
+Page weight controls the position of a page within a collection that is sorted by weight. Assign weights using non-zero integers. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted elements are placed at the end of the collection.
+
+Although rarely used within a template, you can access the value with:
+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.
+Hugo generates one or more files per page when building a site. For example, when rendering home, [section], [taxonomy], and [term] pages, Hugo generates an HTML file and an RSS file. Both HTML and RSS are built-in _output formats_. Create multiple output formats, and control generation based on [page kind], or by enabling one or more output formats for one or more pages. See [details].
+: Adds a given value to existing value(s) of the given key.
+
+: For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
+description: Returns the given page collection sorted by weight in ascending order.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: page.Pages
+ signatures: [PAGES.ByWeight]
+---
+
+Assign a [weight] to a page using the `weight` field in front matter. The weight must be a non-zero integer. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted pages are placed at the end of the collection.
+description: Returns the given page collection grouped by date in descending order.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/pages/GroupByExpiryDate
+ - methods/pages/GroupByLastMod
+ - methods/pages/GroupByParamDate
+ - methods/pages/GroupByPublishDate
+ returnType: page.PagesGroup
+ signatures: ['PAGES.GroupByDate LAYOUT [SORT]']
+---
+
+When grouping by date, the value is determined by your [site configuration], defaulting to the `date` field in front matter.
+
+The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region.
+The pages within each group will also be sorted by date, either ascending or descending depending on the grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title:
+When grouping by expiration date, the value is determined by your [site configuration], defaulting to the `expiryDate` field in front matter.
+
+The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region.
+The pages within each group will also be sorted by expiration date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title:
+
+```go-html-template
+{{ range .Pages.GroupByExpiryDate "January 2006" }}
+When grouping by last modification date, the value is determined by your [site configuration], defaulting to the `lastmod` field in front matter.
+
+The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region.
+The pages within each group will also be sorted by last modification date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title:
+The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region.
+The pages within each group will also be sorted by the parameter date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title:
+
+```go-html-template
+{{ range .Pages.GroupByParamDate "eventDate" "January 2006" }}
+When grouping by publish date, the value is determined by your [site configuration], defaulting to the `publishDate` field in front matter.
+
+The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region.
+The pages within each group will also be sorted by publish date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title:
+
+```go-html-template
+{{ range .Pages.GroupByPublishDate "January 2006" }}
+description: Returns a collection of pages related to the given page.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/HeadingsFiltered
+ - functions/collections/KeyVals
+ returnType: page.Pages
+ signatures:
+ - PAGES.Related PAGE
+ - PAGES.Related OPTIONS
+---
+
+Based on front matter, Hugo uses several factors to identify content related to the given page. Use the default [related content configuration], or tune the results to the desired indices and parameters. See [details].
+
+The argument passed to the `Related` method may be a `Page` or an options map. For example, to pass the current page:
+
+{{< code file=layouts/_default/single.html >}}
+{{ with .Site.RegularPages.Related . | first 5 }}
+: (`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.
+
+[`keyVals`]: /functions/collections/keyvals/
+
+fragments
+: (`slice`) A list of special keywords that is used for indices configured as type "fragments". This will match the [fragment] identifiers of the documents.
+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.
+description: Applicable to resources returned by the resources.GetRemote function, returns an error message if the HTTP request fails, else nil.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/resources/GetRemote
+ - methods/resource/Data
+ returnType: resource.resourceError
+ signatures: [RESOURCE.Err]
+---
+
+The `Err` method on a resource returned by the [`resources.GetRemote`] function returns an error message if the HTTP request fails, else nil. If you do not handle the error yourself, Hugo will fail the build.
+ {{ errorf "Unable to get remote resource %q" $url }}
+{{ end }}
+```
+
+The code above captures the error from the HTTP request, then fails the build:
+
+```text
+ERROR error calling resources.GetRemote: Get "https://broken-example.org/images/a.jpg": dial tcp: lookup broken-example.org on 127.0.0.53:53: no such host
+```
+
+To log an error as a warning instead of an error:
+ {{ errorf "Unable to get remote resource %q" $url }}
+{{ end }}
+```
+
+{{% note %}}
+An HTTP response with a 404 status code is not an HTTP request error. To handle 404 status codes, code defensively using the nested `with-else-end` construct as shown above.
+description: Applicable to images, returns an EXIF object containing image metadata.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: exif.ExifInfo
+ signatures: [RESOURCE.Exif]
+toc: true
+---
+
+Applicable to images, the `Exif` method on an image `Resource` object returns an [EXIF] object containing image metadata.
+
+## Methods
+
+Date
+: (`time.Time`) Returns the image creation date/time. Format with the [`time.Format`]function.
+
+Lat
+: (`float64`) Returns the GPS latitude in degrees.
+
+Long
+: (`float64`) Returns the GPS longitude in degrees.
+
+Tags
+: (`exif.Tags`) Returns a collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration].
+
+## Examples
+
+To list the creation date, location, and EXIF tags:
+
+```go-html-template
+{{ with resources.Get "images/a.jpg" }}
+ {{ with .Exif }}
+ <p>Date: {{ .Date }}</p>
+ <p>Lat/Long: {{ .Lat }}/{{ .Long }}</p>
+ {{ with .Tags }}
+ <p>Tags</p>
+ <table>
+ <thead>
+ <tr><th>Tag</th><th>Value</th></tr>
+ </thead>
+ <tbody>
+ {{ range $k, $v := . }}
+ <tr><td>{{ $k }}</td><td>{{ $v }}</td></tr>
+ {{ end }}
+ </tbody>
+ </table>
+ {{ end }}
+ {{ end }}
+{{ end }}
+```
+
+To list specific values:
+
+```go-html-template
+{{ with resources.Get "images/a.jpg" }}
+ {{ with .Exif }}
+ <ul>
+ {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }}
+ {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.FormatNumber 2 . }}</li>{{ end }}
+ {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.FormatNumber 2 . }}</li>{{ end }}
+ {{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }}
+ {{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }}
+ {{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }}
+ {{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }}
+ {{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }}
+ </ul>
+ {{ end }}
+{{ end }}
+```
+
+{{% include "methods/resource/_common/global-page-remote-resources.md" %}}
+description: Returns the unique key for the given resource, equivalent to its publishing path.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/resource/Permalink
+ - methods/resource/RelPermalink
+ - methods/resource/Publish
+ returnType: string
+ signatures: [RESOURCE.Key]
+---
+
+By way of example, consider this site configuration:
+
+{{< code-toggle file=hugo >}}
+baseURL = 'https://example.org/docs/'
+{{< /code-toggle >}}
+
+And this template:
+
+```go-html-template
+ {{ with resources.Get "images/a.jpg" }}
+ {{ with resources.Copy "foo/bar/b.jpg" . }}
+ {{ .Key }} → foo/bar/b.jpg
+
+ {{ .Name }} → images/a.jpg
+ {{ .Title }} → images/a.jpg
+
+ {{ .RelPermalink }} → /docs/foo/bar/b.jpg
+ {{ end }}
+ {{ end }}
+```
+
+We used the [`resources.Copy`] function to change the publishing path. The `Key` method returns the updated path, but note that it is different than the value returned by [`RelPermalink`]. The `RelPermalink` value includes the subdirectory segment of the `baseURL` in the site configuration.
+
+The `Key` method is useful if you need to get the resource's publishing path without publishing the resource. Unlike the `Permalink`, `RelPermalink`, or `Publish` methods, calling `Key` will not publish the resource.
+
+
+{{% include "methods/resource/_common/global-page-remote-resources.md" %}}
+description: Returns the name of the given resource as optionally defined in front matter, falling back to a relative path or hashed file name depending on resource type.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/resource/Title
+ returnType: string
+ signatures: [RESOURCE.Name]
+toc: true
+---
+
+The value returned by the `Name` method on a `Resource` object depends on the resource type.
+
+## Global resource
+
+With a [global resource], the `Name` method returns the path to the resource, relative to the assets directory.
+
+```text
+assets/
+└── images/
+ └── a.jpg
+```
+
+```go-html-template
+{{ with resources.Get "images/a.jpg" }}
+ {{ .Name }} → images/a.jpg
+{{ end }}
+```
+
+## Page resource
+
+With a [page resource], the `Name` method returns the path to the resource, relative to the page bundle.
+
+```text
+content/
+├── posts/
+│ ├── post-1/
+│ │ ├── images/
+│ │ │ └── a.jpg
+│ │ └── index.md
+│ └── _index.md
+└── _index.md
+```
+
+```go-html-template
+{{ with .Resources.Get "images/a.jpg" }}
+ {{ .Name }} → images/a.jpg
+{{ end }}
+```
+
+If you create an element in the `resources` array in front matter, the `Name` method returns the value of the `name` parameter:
+description: Applicable to images, returns an image resource processed with the given specification.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/resource/Crop
+ - methods/resource/Fit
+ - methods/resource/Fill
+ - methods/resource/Resize
+ - functions/images/Process
+ returnType: images.ImageResource
+ signatures: [RESOURCE.Process SPEC]
+toc: true
+---
+
+Process an image with the given specification. The specification can contain an optional action, one of `crop`, `fill`, `fit`, or `resize`. This means that you can use this method instead of [`Crop`], [`Fill`], [`Fit`], or [`Resize`].
+You can also use this method to apply simple transformations such as rotation and conversion:
+
+```go-html-template
+{{/* Rotate 90 degrees counter-clockwise. */}}
+{{ $image := $image.Process "r90" }}
+
+{{/* Convert to WebP. */}}
+{{ $image := $image.Process "webp" }}
+```
+
+The `Process` method is also available as a filter, which is more effective if you need to apply multiple filters to an image. See [`images.Process`].
+
+{{% include "methods/resource/_common/global-page-remote-resources.md" %}}
+
+{{% include "/methods/resource/_common/processing-spec.md" %}}
+The `Publish` method on a `Resource` object writes the resource to the publish directory, typically `public`.
+
+```go-html-template
+{{ with resources.Get "images/a.jpg" }}
+ {{ .Publish }}
+{{ end }}
+```
+
+The `Permalink` and `RelPermalink` methods also publish a resource. `Publish` is a convenience method for publishing without a return value. For example, this:
+
+```go-html-template
+{{ $resource.Publish }}
+```
+
+Instead of this:
+
+```go-html-template
+{{ $noop := $resource.Permalink }}
+```
+
+{{% include "methods/resource/_common/global-page-remote-resources.md" %}}
+description: Returns the title of the given resource as optionally defined in front matter, falling back to a relative path or hashed file name depending on resource type.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/resource/Name
+ returnType: string
+ signatures: [RESOURCE.Title]
+toc: true
+---
+
+The value returned by the `Title` method on a `Resource` object depends on the resource type.
+
+## Global resource
+
+With a [global resource], the `Title` method returns the path to the resource, relative to the assets directory.
+
+```text
+assets/
+└── images/
+ └── a.jpg
+```
+
+```go-html-template
+{{ with resources.Get "images/a.jpg" }}
+ {{ .Title }} → images/a.jpg
+{{ end }}
+```
+
+## Page resource
+
+With a [page resource], the `Title` method returns the path to the resource, relative to the page bundle.
+
+```text
+content/
+├── posts/
+│ ├── post-1/
+│ │ ├── images/
+│ │ │ └── a.jpg
+│ │ └── index.md
+│ └── _index.md
+└── _index.md
+```
+
+```go-html-template
+{{ with .Resources.Get "images/a.jpg" }}
+ {{ .Title }} → images/a.jpg
+{{ end }}
+```
+
+If you create an element in the `resources` array in front matter, the `Title` method returns the value of the `title` parameter:
+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.
+The process specification is a space-delimited, case-insensitive list of one or more of the following in any sequence:
+
+action
+: Applicable to the [`Process`](/methods/resource/process) method only. Specify zero or one of `crop`, `fill`, `fit`, or `resize`. If you specify an action you must also provide dimensions.
+
+dimensions
+: Provide width _or_ height when using the [`Resize`](/methods/resource/resize) method, else provide both width _and_ height. See [details](/content-management/image-processing/#dimensions).
+
+anchor
+: Use with the [`Crop`](/methods/resource/crop) and [`Fill`](/methods/resource/fill) methods. Specify zero or one of `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. Default is `Smart`. See [details](/content-management/image-processing/#anchor).
+
+rotation
+: Typically specify zero or one of `r90`, `r180`, or `r270`. Also supports arbitrary rotation angles. See [details](/content-management/image-processing/#rotation).
+
+target format
+: Specify zero or one of `gif`, `jpeg`, `png`, `tiff`, or `webp`. See [details](/content-management/image-processing/#target-format).
+
+quality
+: Applicable to JPEG and WebP images. Optionally specify `qN` where `N` is an integer in the range [0, 100]. Default is `75`. See [details](/content-management/image-processing/#quality).
+
+hint
+: Applicable to WebP images and equivalent to the `-preset` flag for the [`cwebp`] encoder. Specify zero or one of `drawing`, `icon`, `photo`, `picture`, or `text`. Default is `photo`. See [details](/content-management/image-processing/#hint).
+: When converting a PNG or WebP with transparency to a format that does not support transparency, optionally specify a background color using a 3-digit or a 6-digit hexadecimal color code. Default is `#ffffff` (white). See [details](/content-management/image-processing/#background-color).
+
+resampling filter
+: Typically specify zero or one of `Box`, `Lanczos`, `CatmullRom`, `MitchellNetravali`, `Linear`, or `NearestNeighbor`. Other resampling filters are available. See [details](/content-management/image-processing/#resampling-filter).
+description: Returns the value of the given parameter.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/shortcode/IsNamedParams
+ - methods/shortcode/Params
+ returnType: any
+ signatures: [SHORTCODE.Get PARAM]
+toc: true
+---
+
+Specify the parameter by position or by name. When calling a shortcode within markdown, use either positional or named parameters, but not both.
+
+{{% note %}}
+Some shortcodes support positional parameters, some support named parameters, and others support both. Refer to the shortcode's documentation for usage details.
+description: Returns the content between opening and closing shortcode tags, applicable when the shortcode call includes a closing tag.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/strings/Trim
+ - methods/page/RenderString
+ - functions/transform/Markdownify
+ - methods/shortcode/InnerDeindent
+ returnType: template.HTML
+ signatures: [SHORTCODE.Inner]
+---
+
+This content:
+
+{{< code file=content/services.md lang=md >}}
+{{</* card title="Product Design" */>}}
+We design the **best** widgets in the world.
+{{</* /card */>}}
+{{< /code >}}
+
+With this shortcode:
+
+{{< code file=layouts/shortcodes/card.html >}}
+<div class="card">
+ {{ with .Get "title" }}
+ <div class="card-title">{{ . }}</div>
+ {{ end }}
+ <div class="card-content">
+ {{ trim .Inner "\r\n" }}
+ </div>
+</div>
+{{< /code >}}
+
+Is rendered to:
+
+```html
+<div class="card">
+ <div class="card-title">Product Design</div>
+ <div class="card-content">
+ We design the **best** widgets in the world.
+ </div>
+</div>
+```
+
+{{% note %}}
+Content between opening and closing shortcode tags may include leading and/or trailing newlines, depending on placement within the markdown. Use the [`trim`] function as shown above to remove both carriage returns and newlines.
+
+[`trim`]: /functions/strings/trim
+{{% /note %}}
+
+{{% note %}}
+In the example above, the value returned by `Inner` is markdown, but it was rendered as plain text. Use either of the following approaches to render markdown to HTML.
+{{% /note %}}
+
+
+## Use the RenderString method
+
+Let's modify the example above to pass the value returned by `Inner` through the [`RenderString`] method on the `Page` object:
+
+[`RenderString`]: /methods/page/renderstring
+
+{{< code file=layouts/shortcodes/card.html >}}
+<div class="card">
+ {{ with .Get "title" }}
+ <div class="card-title">{{ . }}</div>
+ {{ end }}
+ <div class="card-content">
+ {{ trim .Inner "\r\n" | .Page.RenderString }}
+ </div>
+</div>
+{{< /code >}}
+
+Hugo renders this to:
+
+```html
+<div class="card">
+ <div class="card-title">Product design</div>
+ <div class="card-content">
+ We produce the <strong>best</strong> widgets in the world.
+ </div>
+</div>
+```
+
+You can use the [`markdownify`] function instead of the `RenderString` method, but the latter is more flexible. See [details].
+Instead of calling the shortcode with the `{{</* */>}}` notation, use the `{{%/* */%}}` notation:
+
+{{< code file=content/services.md lang=md >}}
+{{%/* card title="Product Design" */%}}
+We design the **best** widgets in the world.
+{{%/* /card */%}}
+{{< /code >}}
+
+When you use the `{{%/* */%}}` notation, Hugo renders the entire shortcode as markdown, requiring the following changes.
+
+First, configure the renderer to allow raw HTML within markdown:
+
+{{< code-toggle file=hugo >}}
+[markup.goldmark.renderer]
+unsafe = true
+{{< /code-toggle >}}
+
+This configuration is not unsafe if _you_ control the content. Read more about Hugo's [security model].
+
+Second, because we are rendering the entire shortcode as markdown, we must adhere to the rules governing [indentation] and inclusion of [raw HTML blocks] as provided in the [CommonMark] specification.
+
+{{< code file=layouts/shortcodes/card.html >}}
+<div class="card">
+ {{ with .Get "title" }}
+ <div class="card-title">{{ . }}</div>
+ {{ end }}
+ <div class="card-content">
+
+ {{ trim .Inner "\r\n" }}
+ </div>
+</div>
+{{< /code >}}
+
+The difference between this and the previous example is subtle but required. Note the change in indentation, the addition of a blank line, and removal of the `RenderString` method.
+
+```diff
+--- layouts/shortcodes/a.html
++++ layouts/shortcodes/b.html
+@@ -1,8 +1,9 @@
+ <div class="card">
+ {{ with .Get "title" }}
+- <div class="card-title">{{ . }}</div>
++ <div class="card-title">{{ . }}</div>
+ {{ end }}
+ <div class="card-content">
+- {{ trim .Inner "\r\n" | .Page.RenderString }}
++
++ {{ trim .Inner "\r\n" }}
+ </div>
+ </div>
+```
+
+{{% note %}}
+When using the `{{%/* */%}}` notation, do not pass the value returned by `Inner` through the `RenderString` method or the `markdownify` function.
+description: Returns the content between opening and closing shortcode tags, with indentation removed, applicable when the shortcode call includes a closing tag.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/shortcode/Inner
+ returnType: template.HTML
+ signatures: [SHORTCODE.InnerDeindent]
+---
+
+Similar to the [`Inner`] method, `InnerDeindent` returns the content between opening and closing shortcode tags. However, with `InnerDeindent`, indentation before the content is removed.
+
+This allows us to effectively bypass the rules governing [indentation] as provided in the [CommonMark] specification.
+
+Consider this markdown, an unordered list with a small gallery of thumbnail images within each list item:
+
+{{< code file=content/about.md lang=md >}}
+- Gallery one
+
+ {{</* gallery */>}}
+ 
+ 
+ {{</* /gallery */>}}
+
+- Gallery two
+
+ {{</* gallery */>}}
+ 
+ 
+ {{</* /gallery */>}}
+{{< /code >}}
+
+In the example above, notice that the content between the opening and closing shortcode tags is indented by four spaces. Per the CommonMark specification, this is treated as an indented code block.
+
+With this shortcode, calling `Inner` instead of `InnerDeindent`:
+Although technically correct per the CommonMark specification, this is not what we want. If we remove the indentation using the `InnerDeindent` method:
+description: Returns the zero-based ordinal of the shortcode in relation to its parent.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: int
+ signatures: [SHORTCODE.Ordinal]
+---
+
+The `Ordinal` method returns the zero-based ordinal of the shortcode in relation to its parent. If the parent is the page itself, the ordinal represents the position of this shortcode in the page content.
+
+This method is useful for, among other things, assigning unique element IDs when a shortcode is called two or more times from the same page. For example:
+
+{{< code file=content/about.md lang=md >}}
+{{</* img src="images/a.jpg" */>}}
+
+{{</* img src="images/b.jpg" */>}}
+{{< /code >}}
+
+This shortcode performs error checking, then renders an HTML `img` element with a unique `id` attribute:
+In the shortcode template above, the [`with`] statement is used to create conditional blocks. Remember that the `with` statement binds context (the dot) to its expression. Inside of a `with` block, preface shortcode method calls with a `$` to access the top level context passed into the template.
+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.
+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.
+description: Creates a "scratch pad" scoped to the shortcode to store and manipulate data.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/collections/NewScratch
+ returnType: maps.Scratch
+ signatures: [SHORTCODE.Scratch]
+---
+
+The `Scratch` method within a shortcode creates a [scratch pad] to store and manipulate data. The scratch pad is scoped to the shortcode, and is reset on server rebuilds.
+
+{{% note %}}
+With the introduction of the [`newScratch`] function, and the ability to [assign values to template variables] after initialization, the `Scratch` method within a shortcode is obsolete.
+
+[assign values to template variables]: https://go.dev/doc/go1.11#text/template
+description: Returns a data structure composed from the files in the data directory.
+categories: []
+keywords: []
+action:
+ related:
+ - functions/collections/IndexFunction
+ - functions/transform/Unmarshal
+ - functions/collections/Where
+ - functions/collections/Sort
+ returnType: map
+ signatures: [SITE.Data]
+---
+
+Use the `Data` method on a `Site` object to access data within the data directory, or within any directory [mounted] to the data directory. Supported data formats include JSON, TOML, YAML, and XML.
+Although Hugo can unmarshal CSV files with the [`transform.Unmarshal`] function, do not place CSV files in the data directory. You cannot access data within CSV files using this method.
+{{ range $category, $books := .Site.Data.books }}
+ <p>{{ $category | title }}</p>
+ <ul>
+ {{ range $books }}
+ <li>{{ .title }} ({{ .isbn }})</li>
+ {{ end }}
+ </ul>
+{{ end }}
+```
+
+Hugo renders this to:
+
+```html
+<p>Fiction</p>
+<ul>
+ <li>The Hunchback of Notre Dame (978-0140443530)</li>
+ <li>Les Misérables (978-0451419439)</li>
+</ul>
+<p>Nonfiction</p>
+<ul>
+ <li>The Ancien Régime and the Revolution (978-0141441641)</li>
+ <li>Interpreting the French Revolution (978-0521280495)</li>
+</ul>
+```
+
+To limit the listing to fiction, and sort by title:
+
+```go-html-template
+<ul>
+ {{ range sort .Site.Data.books.fiction "title" }}
+ <li>{{ .title }} ({{ .author }})</li>
+ {{ end }}
+</ul>
+```
+
+To find a fiction book by ISBN:
+
+```go-html-template
+{{ range where .Site.Data.books.fiction "isbn" "978-0140443530" }}
+ <li>{{ .title }} ({{ .author }})</li>
+{{ end }}
+```
+
+In the template examples above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function:
+description: Returns the language object for the given site.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/language
+ returnType: langs.Language
+ signatures: [SITE.Language]
+toc: true
+---
+
+The `Language` method on a `Site` object returns the language object for the given site. The language object points to the language definition in the site configuration.
+
+You can also use the `Language` method on a `Page` object. See [details].
+
+## Methods
+
+The examples below assume the following in your site configuration:
+
+{{< code-toggle file=hugo >}}
+[languages.de]
+languageCode = 'de-DE'
+languageDirection = 'ltr'
+languageName = 'Deutsch'
+weight = 1
+{{< /code-toggle >}}
+
+Lang
+: (`string`) The language tag as defined by [RFC 5646].
+
+```go-html-template
+{{ .Site.Language.Lang }} → de
+```
+
+LanguageCode
+: (`string`) The language code from the site configuration.
+
+```go-html-template
+{{ .Site.Language.LanguageCode }} → de-DE
+```
+
+LanguageDirection
+: (`string`) The language direction from the site configuration, either `ltr` or `rtl`.
+
+```go-html-template
+{{ .Site.Language.LanguageDirection }} → ltr
+```
+
+LanguageName
+: (`string`) The language name from the site configuration.
+
+```go-html-template
+{{ .Site.Language.LanguageName }} → Deutsch
+```
+
+Weight
+: (`int`) The language weight from the site configuration which determines its order in the slice of languages returned by the `Languages` method on a `Site` object.
+
+```go-html-template
+{{ .Site.Language.Weight }} → 1
+```
+
+## Example
+
+Some of the methods above are commonly used in a base template as attributes for the `html` element.
+
+```go-html-template
+<html
+ lang="{{ or site.Language.LanguageCode site.Language.Lang }}"
+ dir="{{ or site.Language.LanguageDirection `ltr` }}
+>
+```
+
+The example above uses the global [`site`] function instead of accessing the `Site` object via the `.Site` notation.
+
+Also note that each attribute has a fallback value assigned via the [`or`] operator.
+description: Returns a collection of language objects for all sites, ordered by language weight.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/site/Language
+ returnType: langs.Languages
+ signatures: [SITE.Languages]
+---
+
+The `Languages` method on a `Site` object returns a collection of language objects for all sites, ordered by language weight. Each language object points to its language definition in the site configuration.
+description: Returns a slice of the main section names as defined in the site configuration, falling back to the top level section with the most pages.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: '[]string'
+ signatures: [SITE.MainSections]
+---
+
+Site configuration:
+
+{{< code-toggle file=hugo >}}
+[params]
+mainSections = ['books','films']
+{{< /code-toggle >}}
+
+Template:
+
+```go-html-template
+{{ .Site.MainSections }} → [books films]
+```
+
+If `params.mainSections` is not defined in the site configuration, this method returns a slice with one element---the top level section with the most pages.
+
+With this content structure, the "films" section has the most pages:
+
+```text
+content/
+├── books/
+│ ├── book-1.md
+│ └── book-2.md
+├── films/
+│ ├── film-1.md
+│ ├── film-2.md
+│ └── film-3.md
+└── _index.md
+```
+
+Template:
+
+```go-html-template
+{{ .Site.MainSections }} → [films]
+```
+
+When creating a theme, instead of hardcoding section names when listing the most relevant pages on the front page, instruct site authors to set `params.mainSections` in their site configuration.
+
+Then your home page template can do something like this:
+
+```go-html-template
+{{ range where .Site.RegularPages "Section" "in" .Site.MainSections }}
+description: Returns a collection of menu objects for the given site.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/page/IsMenuCurrent
+ - methods/page/HasMenuCurrent
+ returnType: navigation.Menus
+ signatures: [SITE.Menus]
+---
+
+The `Menus` method on a `Site` object returns a collection of menus, where each menu contains one or more entries, either flat or nested. Each entry points to a page within the site, or to an external resource.
+
+{{% note %}}
+Menus can be defined and localized in several ways. Please see the [menus] section for a complete explanation and examples.
+
+[menus]: /content-management/menus/
+{{% /note %}}
+
+A site can have multiple menus. For example, a main menu and a footer menu:
+You will typically render a menu using a partial template. As the active menu entry will be different on each page, use the [`partial`] function to call the template. Do not use the [`partialCached`] function.
+
+The example above is simplistic. Please see the [menu templates] section for more information.
+This method returns all page [kinds] in the current language. That includes the home page, section pages, taxonomy pages, term pages, and regular pages.
+
+In most cases you should use the [`RegularPages`] method instead.
+In the template example above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function:
+description: Returns a data structure containing the site's taxonomy objects, the terms within each taxonomy object, and the pages to which the terms are assigned.
+categories: []
+keywords: []
+action:
+ related: []
+ returnType: page.TaxonomyList
+ signatures: [SITE.Taxonomies]
+---
+
+Conceptually, the `Taxonomies` method on a `Site` object returns a data structure such as:
+
+{{< code-toggle >}}
+taxonomy a:
+ - term 1:
+ - page 1
+ - page 2
+ - term 2:
+ - page 1
+taxonomy b:
+ - term 1:
+ - page 2
+ - term 2:
+ - page 1
+ - page 2
+{{< /code-toggle >}}
+
+For example, on a book review site you might create two taxonomies; one for genres and another for authors.
+description: Returns an ordered taxonomy, sorted alphabetically by term.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/taxonomy/ByCount
+ returnType: page.OrderedTaxonomy
+ signatures: [TAXONOMY.Alphabetical]
+toc: true
+---
+
+The `Alphabetical` method on a `Taxonomy` object returns an [ordered taxonomy], sorted alphabetically by [term].
+
+While a `Taxonomy` object is a [map], an ordered taxonomy is a [slice], where each element is an object that contains the term and a slice of its [weighted pages].
+
+{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}}
+
+## Get the ordered taxonomy
+
+Now that we have captured the “genres” Taxonomy object, let’s get the ordered taxonomy sorted alphabetically by term:
+description: Returns an ordered taxonomy, sorted by the number of pages associated with each term.
+categories: []
+keywords: []
+action:
+ related:
+ - methods/taxonomy/Alphabetical
+ returnType: page.OrderedTaxonomy
+ signatures: [TAXONOMY.ByCount]
+toc: true
+---
+
+The `ByCount` method on a `Taxonomy` object returns an [ordered taxonomy], sorted by the number of pages associated with each [term].
+
+While a `Taxonomy` object is a [map], an ordered taxonomy is a [slice], where each element is an object that contains the term and a slice of its [weighted pages].
+
+{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}}
+
+## Get the ordered taxonomy
+
+Now that we have captured the “genres” Taxonomy object, let’s get the ordered taxonomy sorted by the number of pages associated with each term:
+But, if the term is not a valid [identifier], you cannot use the [chaining] syntax. For example, this will throw an error because the identifier contains a hyphen:
+
+```go-html-template
+{{ $weightedPages := $taxonomyObject.my-genre }}
+```
+
+You could also use the [`index`] function, but the syntax is more verbose:
+
+```go-html-template
+{{ $weightedPages := index $taxonomyObject "my-genre" }}
+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.
+Although the [`Alphabetical`] and [`ByCount`] methods provide a better data structure for ranging through the taxonomy, you can render the weighted pages by term directly from the `Taxonomy` object:
+
+```go-html-template
+{{ range $term, $weightedPages := $taxonomyObject }}
+An ordered taxonomy is a slice, where each element is an object that contains the term and a slice of its weighted pages.
+
+Each element of the slice provides these methods:
+
+Count
+: (`int`) Returns the number of pages to which the term is assigned.
+
+Page
+: (`hugolib.pageState`) Returns the term's `Page` object, useful for linking to the term page.
+
+Pages
+: (`page.Pages`) Returns a `Pages` object containing the `Page` objects to which the term is assigned, sorted by [taxonomic weight]. To sort or group, use any of the [methods] available to the `Pages` object. For example, sort by the last modification date.
+
+Term
+: (`string`) Returns the term name.
+
+WeightedPages
+: (`page.WeightedPages`) Returns a slice of weighted pages to which the term is assigned, sorted by [taxonomic weight]. The `Pages` method above is more flexible, allowing you to sort and group.
+When adding months or years, Hugo normalizes the final `time.Time` value if the resulting day does not exist. For example, adding one month to 31 January produces 2 March or 3 March, depending on the year.
+
+See [this explanation](https://github.com/golang/go/issues/31145#issuecomment-479067967) from the Go team.
+description: Include emoji shortcodes in your markdown or templates.
+categories: [quick reference]
+keywords: [emoji]
+menu:
+ docs:
+ parent: quick-reference
+ weight: 20
+weight: 20
+toc: true
+---
+
+Configure Hugo to enable emoji processing in markdown:
+
+{{< code-toggle file=hugo >}}
+enableEmoji = true
+{{< /code-toggle >}}
+
+With emoji processing enabled, this markdown:
+
+```md
+Hello! :wave:
+```
+
+Is rendered to:
+
+```html
+Hello! 👋
+```
+
+And in your browser... Hello! :wave:
+
+To process an emoji shortcode from within a template, use the [`emojify`] function or pass the string through the [`RenderString`] method on a `Page` object:
+
+```go-html-template
+{{ "Hello! :wave:" | .RenderString }}
+```
+
+[`emojify`]: /functions/transform/emojify
+[`RenderString`]: /methods/page/renderstring
+
+## Introduction
+
+This quick reference guide was automatically generated from [GitHub Emoji API] and [Unicode Full Emoji List]. Specials thanks to [@ikatyang] for making [this list] available to the open-source community.
+description: A quick reference guide to Hugo's functions, grouped by namespace. Aliases, if any, appear in parentheses to the right of the function name.
**1Password** is a password manager that keeps you safe online. It protects your secure information behind the one password only you know.
-
The [1Password Support](https://support.1password.com/) website was built from scratch with **Hugo** and enhanced with **React** and **Elasticsearch** to give us the best of both worlds: The simplicity and performance of a static site, with the richness of a hosted web app.
@@ -34,6+34,6 @@ Finding a tool that will make your customers, writers, designers, _and_ DevOps t
* [1Password Support](https://support.1password.com) uses Hugo with a custom theme. It shares styles and some template code with [1Password.com](https://1password.com), which we also moved to Hugo in 2016.
* Code and articles live in a private GitHub repository, which is deployed to a static content server using Git hooks.
* Writers build and preview the site on their computers and contribute content using pull requests.
-* We use Hugo's [multilingual support](/content-management/multilingual/) to build the site in English, Spanish, French, Italian, German, and Russian. With the help of Hugo, 1Password Support became our very first site in multiple languages.
+* We use Hugo's [multilingual support](/content-management/multilingual/) to build the site in English, Spanish, French, Italian, German, and Russian. With the help of Hugo, 1Password Support became our very first site in multiple languages.
* Our [contact form](https://support.1password.com/contact) is a single-page React app. We were able to integrate it with Hugo seamlessly thanks to its support for static files.
* The one part of the support site which is not static is our search engine, which we developed with Elasticsearch and host on AWS.
-**Alora Labs** is a product development consultancy headquartered in Toronto, Canada.
+**Alora Labs** is a product development consultancy headquartered in Toronto, Canada.
We help companies build software and IoT products and were recently recognized as one of the [**top IoT development firms**](https://aloralabs.com/insights/alora-labs-receives-clutch-2021-top-iot-agency-award) in Toronto.
At Alora Labs we always have an eye open for new tools and technology that we can utilize to the benefit of our customers or internal projects like our website.
-The previous iteration of our site was built with Jekyll, which served us well at first. However as time went on, we became frustrated with the number of dependencies we had to rely on, that would often break at the most inconvenient times.
+The previous iteration of our site was built with Jekyll, which served us well at first. However as time went on, we became frustrated with the number of dependencies we had to rely on, that would often break at the most inconvenient times.
Hugo was a breath of fresh air in this regard, a single binary that works equally well on Windows as it did on macOS or Linux. We no longer need additional tools for image optimization, Sass compilation or JavaScript bundling. Everything just works, and with a substantial performance boost too.
-Hugo has become a favorite tool in the toolbelt and the foundation for many client projects. We couldn't be happier with the switch and we are optimistic about recommending Hugo for many years to come.
+Hugo has become a favorite tool in the tool belt and the foundation for many client projects. We couldn't be happier with the switch and we are optimistic about recommending Hugo for many years to come.
-Thank you to the vibrant community and talented development team for all the hard work in making Hugo a success. As excellent as Hugo is now, we cannot wait to see what the release notes have in store for us next.
\ No newline at end of file
+Thank you to the vibrant community and talented development team for all the hard work in making Hugo a success. As excellent as Hugo is now, we cannot wait to see what the release notes have in store for us next.
@@ -33,7+33,7 @@ The turning point was the introduction of a new key requirement---each document
On top of that new development, we had to remember another one of our key requirements, namely, that mostly non-programmers were to be responsible for the service maintenance and content creation. Initially, we were leaning towards headless CMS-based solutions, but finally we made a bold move and decided to create a Git-managed Jamstack service and see what happens.
-## Hugo to the rescue!
+## Hugo to the rescue
Hugo was our first choice of SSG. The multilingualism support was the primary feature that convinced us. Later on, going through the documentation, we continued to discover new exciting features that we didn't even know we needed when we started.
@@ -47,7+47,7 @@ We even implemented a simple REST API generated by Hugo! We have yet to find som
When talking about Hugo, we cannot forget about the speed. At the beginning we were not considering it a killer feature, but as our document base grew bigger, we appreciated it more and more. Dry-runs are not so common---most of the time we are working on one of the documents with cache already built during one of the previous Hugo runs. In such a scenario, Hugo rebuilds the site in about a second and we consider it a very good result.
@@ -21,4+21,4 @@ It's a simply site, basically one page in seven languages. I had no problems get
Thanks to the design by [Leyla Avsar](https://www.leylaavsar.com/) the site also looks good. I used the [Hugo Zen theme](https://github.com/frjo/hugo-theme-zen) with a few custom templates and the needed CSS.
-The editors can maintain content via [Forestry.io CMS](https://forestry.io/) or directly via Git. Forestry does unfortunately not have multilingual support. All the language versions are in one pile making it harder to find the right file to edit, but it works.
\ No newline at end of file
+The editors can maintain content via [Forestry.io CMS](https://forestry.io/) or directly via Git. Forestry does unfortunately not have multilingual support. All the language versions are in one pile making it harder to find the right file to edit, but it works.
@@ -12,11+12,11 @@ Through collaboration in our communities of practice, Digital.gov is a window in
Digital.gov is built using the [U.S. Web Design System](https://designsystem.digital.gov/) (USWDS) and have followed the [design principles](https://designsystem.digital.gov/maturity-model/) in building out our new site:
-- **Start with real user needs** — We used human-centered design methods to inform our product decisions (like qualitative user research), and gathered feedback from real users. We also continually test our assumptions with small experiments.
-- **Earn trust** —We recognize that trust has to be earned every time. We are including all [required links and content](https://digital.gov/resources/required-web-content-and-links/) on our site, clearly identifying as a government site, building with modern best practices, and using HTTPS.
-- **Embrace accessibility** — [Accessibility](https://digital.gov/resources/intro-accessibility/) affects everybody, and we built it into every decision. We’re continually working to conform to Section 508 requirements, use user experience best practices, and support a wide range of devices.
-- **Promote continuity** — We started from shared solutions like USWDS and [Federalist](https://federalist.18f.gov/). We designed our site to clearly identify as a government site by including USWDS’s .gov banner, common colors and patterns, and built with modern best practices.
-- **Listen** — We actively collect user feedback and web metrics. We use the [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) and analyze the data to discover actionable insights. We make small, incremental changes to continuously improve our website by listening to readers and learning from what we hear.
+- **Start with real user needs** — We used human-centered design methods to inform our product decisions (like qualitative user research), and gathered feedback from real users. We also continually test our assumptions with small experiments.
+- **Earn trust** —We recognize that trust has to be earned every time. We are including all [required links and content](https://digital.gov/resources/required-web-content-and-links/) on our site, clearly identifying as a government site, building with modern best practices, and using HTTPS.
+- **Embrace accessibility** — [Accessibility](https://digital.gov/resources/intro-accessibility/) affects everybody, and we built it into every decision. We’re continually working to conform to Section 508 requirements, use user experience best practices, and support a wide range of devices.
+- **Promote continuity** — We started from shared solutions like USWDS and [Federalist](https://federalist.18f.gov/). We designed our site to clearly identify as a government site by including USWDS’s .gov banner, common colors and patterns, and built with modern best practices.
+- **Listen** — We actively collect user feedback and web metrics. We use the [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) and analyze the data to discover actionable insights. We make small, incremental changes to continuously improve our website by listening to readers and learning from what we hear.
_More on the [USWDS maturity model »](https://designsystem.digital.gov/maturity-model/)_
@@ -34,7+34,7 @@ At the moment, it takes around `32 seconds` to build close to `~10,000` pages!
In addition to Hugo, we are proudly using a number of other tools and services, all built by government are free to use:
-- [Federalist](https://federalist.18f.gov/)
-- [Search.gov](https://www.search.gov/) — A free, hosted search platform for federal websites.
-- [Cloud.gov](https://www.cloud.gov/) — helps teams build, run, and authorize cloud-ready or legacy government systems quickly and cheaply.
-- [Federal CrowdSource Mobile Testing Program](https://digital.gov/services/mobile-application-testing-program/) — Free mobile compatibility testing by feds, for feds.
-- [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) — A free analytics tool for measuring digital services in the federal government
-- [Section508.gov](https://www.section508.gov/) and [PlainLanguage.gov](https://www.plainlanguage.gov/) resources
-- [API.data.gov](https://api.data.gov/) — a free API management service for federal agencies
-- [U.S. Digital Registry](https://digital.gov/services/u-s-digital-registry/) — A resource for confirming the official status of government social media accounts, mobile apps, and mobile websites.
-
+- [Federalist](https://federalist.18f.gov/)
+- [Search.gov](https://www.search.gov/) — A free, hosted search platform for federal websites.
+- [Cloud.gov](https://www.cloud.gov/) — helps teams build, run, and authorize cloud-ready or legacy government systems quickly and cheaply.
+- [Federal CrowdSource Mobile Testing Program](https://digital.gov/services/mobile-application-testing-program/) — Free mobile compatibility testing by feds, for feds.
+- [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) — A free analytics tool for measuring digital services in the federal government
+- [Section508.gov](https://www.section508.gov/) and [PlainLanguage.gov](https://www.plainlanguage.gov/) resources
+- [API.data.gov](https://api.data.gov/) — a free API management service for federal agencies
+- [U.S. Digital Registry](https://digital.gov/services/u-s-digital-registry/) — A resource for confirming the official status of government social media accounts, mobile apps, and mobile websites.
**Questions or feedback?** [Submit an issue](https://github.com/GSA/digitalgov.gov/issues) or send us an email to [digitalgov@gsa.gov](mailto:digitalgov@gsa.gov) :heart:
@@ -14,7+14,7 @@ In our early research we looked at Ionic’s [site](https://github.com/ionic-tea
We knew Hugo was fast but we did [some additional benchmarking](https://forestry.io/blog/hugo-vs-jekyll-benchmark/) before making our decision. Seeing Hugo in action is a whole different world of awesome. Hugo takes less than one second to build our 150-page site! Take a look:
-```bash
+```text
| EN
+------------------+-----+
Pages | 141
@@ -41,7+41,7 @@ Lastly, we want to take the opportunity to give some love to other amazing tools
* Chris can’t think of modern web development without [**Gulp**](https://gulpjs.com/) & [**Webpack**](https://webpack.js.org/). We used them to add additional build steps such as Browsersync, CSS, JS and SVG optimization.
* Speaking about adding steps to our build, our lives would be much harder without [**CircleCI**](https://circleci.com/) for continuous deployment and automated testing purposes.
* We can’t stop raving about [**Algolia**](https://www.algolia.com/). Chris loves it and even wrote a tutorial on [how to implement Algolia](https://forestry.io/blog/search-with-algolia-in-hugo/) into static sites using Hugo’s [Custom Outputs](/templates/output-formats/).
-* [**Cloudinary**](https://cloudinary.com/) is probably one of the easiest ways to get responsive images into your website.
+* [**Cloudinary**](https://cloudinary.com/) is probably one of the easiest ways to get responsive images into your website.
* We might be a little biased on this one - We think [**Forestry.io**](https://forestry.io/) is a great way to add a content management system with a clean UI on top of your site without interrupting your experience as a developer.
* For hosting purposes we use the almighty [**AWS**](https://aws.amazon.com/).
* [**Formspree.io**](https://formspree.io/) is managing our support and enterprise requests.
@@ -13,7+13,6 @@ byline: "[Godot Tutorials](https://godottutorials.com), Web Developer & Game Pro
---
-
[Godot Tutorials](https://godottutorials.com) started as a way to teach beginners game programming and game development.
As I created videos, I ran into a problem; if I made a mistake with a YouTube video, it was difficult to correct errors.
@@ -22,4+21,4 @@ I discovered that blogging episodes and having articles that teach on top of my
As I researched blogging platforms, I came across two solutions; however, I chose [Hugo](https://gohugo.io) because it's built with Markdown in mind and simplified my workflow.
In a sense, with [Hugo](https://gohugo.io) programmed the right way, I can focus **more time on planning, creating, and editing**
-my videos and **less time maintaining and fixing** my website.
\ No newline at end of file
+my videos and **less time maintaining and fixing** my website.
@@ -62,7+62,7 @@ The most encouraging result is how quick the site is around the world. Most Toma
---
-This project was such a blast to develop, it’s a real pleasure to put new technologies to good use in production, and to see real performance and usability benefits from them. Even using classic web methods of serving folders with files is fun when you’ve been databasing for a while – there’s something really ‘pure’ about it.
+This project was such a blast to develop, it’s a real pleasure to put new technologies to good use in production, and to see real performance and usability benefits from them. Even using classic web methods of serving folders with files is fun when you’ve been using dynamic systems for a while – there’s something really pure about it.
@@ -17,5+17,4 @@ That site is bookmarked in many browsers, so preserving the URLs was a must. Hug
The lessons learned from this also lead to [disableLanguages](/content-management/multilingual/#disable-a-language) in Hugo `0.34` (a way to turn off languages during translation). And I also registered [this issue](https://github.com/gohugoio/hugo/issues/4463). Once fixed it will make it easier to handle partially translated sites.
-
[^1]: The work on getting the content translated is in progress.
# Link to the site's Hugo source code if public and you can/want to share.
# Remove or leave blank if not needed/wanted.
-
# Add credit to the article author. Leave blank or remove if not needed/wanted.
byline: "[Roboto Studio](https://roboto.studio), Jonathan Alford"
---
-
We wanted to shake the status quo with PHARMASEAL, opting for a fast and scalable website built with Hugo instead of slower monolithic systems the competitors were using.
We had two goals:
**Make it fast**
-We wanted to optimise the site as much as possible, so we opted for using Cloudinary, enabling us to take advantage of on-the-fly image manipulation, and thanks to the sheer speed of static sites, we achieved a perfect optimisation score with Google audits.
+We wanted to optimize the site as much as possible, so we opted for using Cloudinary, enabling us to take advantage of on-the-fly image manipulation, and thanks to the sheer speed of static sites, we achieved a perfect optimization score with Google audits.
Because we're hosting the site through Netlify and our target audience is in America, we are taking advantage of Netlify edge (Their alternative to a CDN). We're talking blazing fast.
@@ -34,4+32,4 @@ We're big fans of simplicity, and that's what we delivered with the Forestry bui
PHARMASEAL have found Forestry CMS combined with HUGO to be so effective at producing fast, purpose driven pages, that we have worked with them to add even more blocks in a scalable, modular fashion.
-**TLDR:** We're blown away with HUGO, the sheer speed, scalability and deployment possibilities with Netlify is the 💣
\ No newline at end of file
+**TLDR:** We're blown away with HUGO, the sheer speed, scalability and deployment possibilities with Netlify is the 💣
**Quiply** is an employee communications app enabling mobile collaboration across an entire organization.
-Our customers get their own branded app enabling them to communicate fast and effectively with all employees, also non-desk and shift workers.
+Our customers get their own branded app enabling them to communicate fast and effectively with all employees, also non-desk and shift workers.
As the Quiply app's build process is based on **Gulp**, we have started to build our company and product website using **Gulp + Hugo** which is super-fast and gives us exactly the flexibility we need.
The `block` keyword allows you to define the outer shell of your pages' one or more master template(s) and then fill in or override portions as necessary.
@@ -26,7+26,7 @@ See [Template Lookup Order](/templates/lookup-order/) for details and examples.
The following defines a simple base template at `_default/baseof.html`. As a default template, it is the shell from which all your pages will be rendered unless you specify another `*baseof.html` closer to the beginning of the lookup order.
-{{< code file="layouts/_default/baseof.html" >}}
+{{< code file=layouts/_default/baseof.html >}}
<!DOCTYPE html>
<html>
<head>
@@ -52,7+52,7 @@ The following defines a simple base template at `_default/baseof.html`. As a def
From the above base template, you can define a [default list template][hugolists]. The default list template will inherit all of the code defined above and can then implement its own `"main"` block from:
-{{< code file="layouts/_default/list.html" >}}
+{{< code file=layouts/_default/list.html >}}
{{ define "main" }}
<h1>Posts</h1>
{{ range .Pages }}
@@ -80,7+80,7 @@ Code that you put outside the block definitions *can* break your layout. This ev
The following shows how you can override both the `"main"` and `"title"` block areas from the base template with code unique to your [default single page template][singletemplate]:
-{{< code file="layouts/_default/single.html" >}}
+{{< code file=layouts/_default/single.html >}}
{{ define "title" }}
<!-- This will override the default value set in baseof.html; i.e., "{{ .Site.Title }}" in the original example-->
Hugo supports loading data from YAML, JSON, XML, and TOML files located in the `data` directory at the root of your Hugo project.
{{< youtube FyPgSuwIMWQ >}}
-## The data folder
+## The data directory
-The `data` folder should store additional data for Hugo to use when generating your site.
+The `data` directory should store additional data for Hugo to use when generating your site.
Data files are not for generating standalone pages. They should supplement content files by:
-- extending the content when the front matter fields grow out of control, or
-- showing a larger dataset in a template (see the example below).
+- Extending the content when the front matter fields grow out of control, or
+- Showing a larger dataset in a template (see the example below).
In both cases, it's a good idea to outsource the data in their (own) files.
@@ -58,7+56,9 @@ The keys in the map created with data templates from data files will be a dot-ch
This is best explained with an example:
-## Example: Jaco Pastorius' Solo Discography
+## Examples
+
+### Jaco Pastorius' Solo Discography
[Jaco Pastorius](https://en.wikipedia.org/wiki/Jaco_Pastorius_discography) was a great bass player, but his solo discography is short enough to use as an example. [John Patitucci](https://en.wikipedia.org/wiki/John_Patitucci) is another bass giant.
@@ -69,7+69,7 @@ The example below is a bit contrived, but it illustrates the flexibility of data
`jacopastorius.toml` contains the content below. `johnpatitucci.toml` contains a similar list:
-For `getCSV`, the one-character-long separator must be placed in the first position followed by the URL. The following is an example of creating an HTML table in a [partial template][partials] from a published CSV:
-The expression `{{ index $r number }}` must be used to output the nth-column from the current row.
-
-### Cache URLs
-
-Each downloaded URL will be cached in the default folder `$TMPDIR/hugo_cache_$USER/`. The variable `$TMPDIR` will be resolved to your system-dependent temporary directory.
+Retrieve remote data using these template functions:
-With the command-line flag `--cacheDir`, you can specify any folder on your system as a caching directory.
-
-You can also set `cacheDir` in the [main configuration file][config].
-
-If you don't like caching at all, you can fully disable caching with the command-line flag `--ignoreCache`.
-
-### Authentication when using REST URLs
-
-Currently, you can only use those authentication methods that can be put into an URL. [OAuth] and other authentication methods are not implemented.
-
-## Load local files
-
-To load local files with `getJSON` and `getCSV`, the source files must reside within Hugo's working directory. The file extension does not matter, but the content does.
-
-It applies the same output logic as above in [Get Remote Data](#get-remote-data).
-
-{{% note %}}
-The local CSV files to be loaded using `getCSV` must be located **outside** the `data` directory.
There is no chance to trigger a [LiveReload] when the content of a URL changes. However, when a *local* file changes (i.e., `data/*` and `themes/<THEME>/data/*`), a LiveReload will be triggered. Symlinks are not supported. Note too that because downloading data takes a while, Hugo stops processing your Markdown files until the data download has been completed.
-{{% warning "URL Data and LiveReload" %}}
+{{% note %}}
If you change any local file and the LiveReload is triggered, Hugo will read the data-driven (URL) content from the cache. If you have disabled the cache (i.e., by running the server with `hugo server --ignoreCache`), Hugo will re-download the content every time LiveReload triggers. This can create *huge* traffic. You may reach API limits quickly.
Homepage is a `Page` and therefore has all the [page variables][pagevars] and [site variables][sitevars] available for use.
@@ -34,7+34,7 @@ See the homepage template below or [Content Organization][contentorg] for more i
The following is an example of a homepage template that uses [partial][partials], [base] templates, and a content file at `content/_index.md` to populate the `{{ .Title }}` and `{{ .Content }}` [page variables][pagevars].
Provide your tracking ID in your configuration file:
-**Google Analytics 4 (gtag.js)**
-{{< code-toggle file="hugo" >}}
-googleAnalytics = "G-MEASUREMENT_ID"
+{{< code-toggle file=hugo >}}
+[services.googleAnalytics]
+ID = "G-MEASUREMENT_ID"
{{</ code-toggle >}}
### Use the Google Analytics template
@@ -53,10+48,17 @@ Hugo also ships with an internal template for [Disqus comments][disqus], a popul
To use Hugo's Disqus template, first set up a single configuration value:
-{{< code-toggle file="hugo" >}}
-disqusShortname = "your-disqus-shortname"
+{{< code-toggle file=hugo >}}
+[services.disqus]
+shortname = 'your-disqus-shortname'
{{</ code-toggle >}}
+Hugo's Disqus template accesses this value with:
+
+```go-html-template
+{{ .Site.Config.Services.Disqus.Shortname }}
+```
+
You can also set the following in the front matter for a given piece of content:
* `disqus_identifier`
@@ -71,15+73,13 @@ To add Disqus, include the following line in the templates where you want your c
{{ template "_internal/disqus.html" . }}
```
-A `.Site.DisqusShortname` variable is also exposed from the configuration.
-
### Conditional loading of Disqus comments
Users have noticed that enabling Disqus comments when running the Hugo web server on `localhost` (i.e. via `hugo server`) causes the creation of unwanted discussions on the associated Disqus account.
You can create the following `layouts/partials/disqus.html`:
-{{< code file="layouts/partials/disqus.html" >}}
+{{< code file=layouts/partials/disqus.html >}}
<div id="disqus_thread"></div>
<script type="text/javascript">
@@ -90,7+90,7 @@ You can create the following `layouts/partials/disqus.html`:
return;
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
- var disqus_shortname = '{{ .Site.DisqusShortname }}';
+ var disqus_shortname = '{{ .Site.Config.Services.Disqus.Shortname }}';
@@ -116,7+116,7 @@ This format is used for Facebook and some other sites.
Hugo's Open Graph template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[params]
title = "My cool site"
images = ["site-feature-image.jpg"]
@@ -125,7+125,7 @@ Hugo's Open Graph template is configured using a mix of configuration variables
series = "series"
{{</ code-toggle >}}
-{{< code-toggle file="content/blog/my-post" >}}
+{{< code-toggle file=content/blog/my-post.md >}}
title = "Post title"
description = "Text about this post"
date = "2006-01-02"
@@ -166,13+166,13 @@ metadata used to attach rich media to Tweets linking to your site.
Hugo's Twitter Card template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[params]
images = ["site-feature-image.jpg"]
description = "Text about my cool site"
{{</ code-toggle >}}
-{{< code-toggle file="content/blog/my-post" >}}
+{{< code-toggle file=content/blog/my-post.md >}}
title = "Post title"
description = "Text about this post"
images = ["post-cover.png"]
@@ -184,11+184,11 @@ If no images are found at all, then an image-less Twitter `summary` card is used
Hugo uses the page title and description for the card's title and description fields. The page summary is used if no description is given.
-The `.Site.Social.twitter` variable is exposed from the configuration as the value for `twitter:site`.
+Set the value of `twitter:site` in your site configuration:
@@ -418,7+415,7 @@ Notice how once we have entered the loop (i.e. `range`), the value of `{{ . }}`
`$` has special significance in your templates. `$` is set to the starting value of `.` ("the dot") by default. This is a [documented feature of Go text/template][dotdoc]. This means you have access to the global context from anywhere. Here is an equivalent example of the preceding code block but now using `$` to grab `.Site.Title` from the global context:
@@ -429,7+426,7 @@ Notice how once we have entered the loop (i.e. `range`), the value of `{{ . }}`
</ul>
{{< /code >}}
-{{% warning "Don't Redefine the Dot" %}}
+{{% note %}}
The built-in magic of `$` would cease to work if someone were to mischievously redefine the special character; e.g. `{{ $ := .Site }}`. *Don't do it.* You may, of course, recover from this mischief by using `{{ $ := . }}` in a global context to reset `$` to its default value.
Here is an example of corresponding code that could be used inside a `toc.html` [partial template][partials]:
-{{< code file="layouts/partials/toc.html" >}}
+{{< code file=layouts/partials/toc.html >}}
{{ if not .Params.notoc }}
<aside>
<header>
@@ -564,7+561,7 @@ You can arbitrarily define as many site-level parameters as you want in your [si
For instance, you might declare the following:
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
params:
copyrighthtml: "Copyright © 2017 John Doe. All Rights Reserved."
twitteruser: "spf13"
@@ -583,7+580,7 @@ Within a footer layout, you might then declare a `<footer>` that is only rendere
An alternative way of writing the "`if`" and then referencing the same value is to use [`with`] instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent:
@@ -134,7+134,7 @@ You do *not* have to create an `_index.md` file for every list page (i.e. sectio
Using this same `layouts/_default/list.html` template and applying it to the `quotes` section above will render the following output. Note that `quotes` does not have an `_index.md` file to pull from:
@@ -161,7+161,7 @@ The default behavior of Hugo is to pluralize list titles; hence the inflection o
This list template has been modified slightly from a template originally used in [spf13.com](https://spf13.com/). It makes use of [partial templates][partials] for the chrome of the rendered page rather than using a [base template][base]. The examples that follow also use the [content view templates][views] `li.html` or `summary.html`.
-{{< code file="layouts/section/posts.html" >}}
+{{< code file=layouts/section/posts.html >}}
{{ partial "header.html" . }}
{{ partial "subheader.html" . }}
<main>
@@ -180,7+180,7 @@ This list template has been modified slightly from a template originally used in
@@ -194,374+194,29 @@ This list template has been modified slightly from a template originally used in
{{ end }}
{{< /code >}}
-## Order content
-
-Hugo lists render the content based on metadata you provide in [front matter]. In addition to sane defaults, Hugo also ships with multiple methods to make quick work of ordering content inside list templates:
-
-### Default: Weight > Date > LinkTitle > FilePath
- <!-- ranges through content in ascending order according to the "linktitle" field in front matter. If a "linktitle" field is not set, the range will start with content that only has a "title" field and use that value for .LinkTitle -->
- <time>{{ .Date.Format "Mon, Jan 2, 2006" }}</time>
- </li>
- {{ end }}
-</ul>
-{{< /code >}}
-
-### By page parameter
-
-Order based on the specified front matter parameter. Content that does not have the specified front matter field will use the site's `.Site.Params` default. If the parameter is not found at all in some entries, those entries will appear together at the end of the ordering.
-<!-- Groups content according to content section. The ".Key" in this instance will be the section's title. -->
-{{ range .Pages.GroupBy "Section" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-In the above example, you may want `{{ .Title }}` to point the `title` field you have added to your `_index.md` file instead. You can access this value using the [`.GetPage` function][getpage]:
-<!-- Groups content by month according to the "date" field in front matter -->
-{{ range .Pages.GroupByDate "2006-01" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-{{< new-in "0.97.0" >}} `GroupByDate` accepts the same time layouts as in [`time.Format`] and the `.Key` in the result will be localized for the current language.
-<!-- Groups content by month according to the "publishDate" field in front matter -->
-{{ range .Pages.GroupByPublishDate "2006-01" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .PublishDate.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-{{< new-in "0.97.0" >}} `GroupByDate` accepts the same time layouts as in [`time.Format`] and the `.Key` in the result will be localized for the current language.
-<!-- Groups content by month according to the "expiryDate" field in front matter -->
-{{ range .Pages.GroupByExpiryDate "2006-01" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .ExpiryDate.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-{{< new-in "0.97.0" >}} `GroupByDate` accepts the same time layouts as in [`time.Format`] and the `.Key` in the result will be localized for the current language.
-<!-- Groups content by month according to the "lastMod" field in front matter -->
-{{ range .Pages.GroupByLastmod "2006-01" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .Lastmod.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-{{< new-in "0.97.0" >}} `GroupByDate` accepts the same time layouts as in [`time.Format`] and the `.Key` in the result will be localized for the current language.
-<!-- Groups content according to the "param_key" field in front matter -->
-{{ range .Pages.GroupByParam "param_key" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
- {{ end }}
-{{< /code >}}
-
-### By page parameter in date format
-
-The following template takes grouping by `date` a step further and uses Go's layout string. See the [`Format` function] for more examples of how to use Go's layout string to format dates in Hugo.
-<!-- Groups content by month according to the "param_key" field in front matter -->
-{{ range .Pages.GroupByParamDate "param_key" "2006-01" }}
- <h3>{{ .Key }}</h3>
- <ul>
- {{ range .Pages }}
- <li>
- <a href="{{ .Permalink }}">{{ .Title }}</a>
- <div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
- </li>
- {{ end }}
- </ul>
-{{ end }}
-{{< /code >}}
-
-### Reverse key order
-
-Ordering of groups is performed by keys in alphanumeric order (A–Z, 1–100) and in reverse chronological order (i.e., with the newest first) for dates.
-
-While these are logical defaults, they are not always the desired order. There are two different syntaxes to change Hugo's default ordering for groups, both of which work the same way.
-
-#### 1. Adding the reverse method
-
-```go-html-template
-{{ range (.Pages.GroupBy "Section").Reverse }}
-```
-
-```go-html-template
-{{ range (.Pages.GroupByDate "2006-01").Reverse }}
-```
-
-#### 2. Providing the alternate direction
-
-```go-html-template
-{{ range .Pages.GroupByDate "2006-01" "asc" }}
-```
-
-```go-html-template
-{{ range .Pages.GroupBy "Section" "desc" }}
-```
-
-### Order within groups
-
-Because Grouping returns a `{{ .Key }}` and a slice of pages, all the ordering methods listed above are available.
-
-Here is the ordering for the example that follows:
-
-1. Content is grouped by month according to the `date` field in front matter.
-2. Groups are listed in ascending order (i.e., the oldest groups first)
-3. Pages within each respective group are ordered alphabetically according to the `title`.
@@ -86,7+86,7 @@ Regardless of how you [define menu entries], an entry associated with a page has
This simplistic example renders a page parameter named `version` next to each entry's `name`. Code defensively using `with` or `if` to handle entries where (a) the entry points to an external resource, or (b) the `version` parameter is not defined.
-{{< code file="layouts/_default/single.html" >}}
+{{< code file=layouts/_default/single.html >}}
{{- range site.Menus.main }}
<a href="{{ .URL }}">
{{ .Name }}
@@ -108,7+108,7 @@ When you define menu entries [in site configuration] or [in front matter], you c
This simplistic example renders a `class` attribute for each anchor element. Code defensively using `with` or `if` to handle entries where `params.class` is not defined.
-{{< code file="layouts/partials/menu.html" >}}
+{{< code file=layouts/partials/menu.html >}}
{{- range site.Menus.main }}
<a {{ with .Params.class -}} class="{{ . }}" {{ end -}} href="{{ .URL }}">
{{ .Name }}
@@ -128,5+128,5 @@ Hugo provides two methods to localize your menu entries. See [multilingual].
[localize the menu entries]: /content-management/multilingual/#menus
[menu entry defined in front matter]: /content-management/menus/#example-front-matter
[menu entry defined in site configuration]: /content-management/menus/#example-site-configuration
-[menu variables and methods]: /variables/menus/
+[menu variables and methods]: /variables/menu-entry/
description: Hugo can output content in multiple formats, including calendar events, e-book formats, Google AMP, and JSON search indexes, or any custom text format.
This page describes how to properly configure your site with the media types and output formats, as well as where to create your templates for your custom outputs.
@@ -31,7+31,7 @@ This is the full set of built-in media types in Hugo:
To add or modify a media type, define it in a `mediaTypes` section in your [site configuration], either for all sites or for a given language.
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[mediaTypes]
[mediaTypes."text/enriched"]
suffixes = ["enr"]
@@ -43,7+43,7 @@ The above example adds one new media type, `text/enriched`, and changes the suff
**Note:** these media types are configured for **your output formats**. If you want to redefine one of Hugo's default output formats (e.g. `HTML`), you also need to redefine the media type. So, if you want to change the suffix of the `HTML` output format from `html` (default) to `htm`:
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[mediaTypes]
[mediaTypes."text/html"]
suffixes = ["htm"]
@@ -53,7+53,9 @@ The above example adds one new media type, `text/enriched`, and changes the suff
mediaType = "text/html"
{{</ code-toggle >}}
-**Note** that for the above to work, you also need to add an `outputs` definition in your site configuration.
+{{% note %}}
+For the above to work, you also need to add an `outputs` definition in your site configuration.
+{{% /note %}}
## Output format definitions
@@ -69,7+71,7 @@ This is the full set of Hugo's built-in output formats:
To add or modify an output format, define it in an `outputFormats` section in your site's [configuration file](/getting-started/configuration/), either for all sites or for a given language.
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
[outputFormats.MyEnrichedFormat]
mediaType = "text/enriched"
baseName = "myindex"
@@ -83,40+85,40 @@ The above example is fictional, but if used for the homepage on a site with `bas
The following is the full list of configuration options for output formats and their default values:
-`name`
+name
: the output format identifier. This is used to define what output format(s) you want for your pages.
-`mediaType`
+mediaType
: this must match the `Type` of a defined media type.
-`path`
+path
: sub path to save the output files.
-`baseName`
+baseName
: the base file name for the list file names (homepage, etc.). **Default:** `index`.
-`rel`
+rel
: can be used to create `rel` values in `link` tags. **Default:** `alternate`.
-`protocol`
+protocol
: will replace the "http://" or "https://" in your `baseURL` for this output format.
-`isPlainText`
+isPlainText
: use Go's plain text templates parser for the templates. **Default:** `false`.
-`isHTML`
+isHTML
: used in situations only relevant for `HTML`-type formats; e.g., page aliases. **Default:** `false`.
-`noUgly`
+noUgly
: used to turn off ugly URLs If `uglyURLs` is set to `true` in your site. **Default:** `false`.
-`notAlternative`
+notAlternative
: enable if it doesn't make sense to include this format in an `AlternativeOutputFormats` format listing on `Page` (e.g., with `CSS`). Note that we use the term _alternative_ and not _alternate_ here, as it does not necessarily replace the other format. **Default:** `false`.
-`permalinkable`
+permalinkable
: make `.Permalink` and `.RelPermalink` return the rendering Output Format rather than main ([see below](#link-to-output-formats)). This is enabled by default for `HTML` and `AMP`. **Default:** `false`.
-`weight`
+weight
: Setting this to a non-zero value will be used as the first sort criteria.
The real power of Hugo pagination shines when combined with the [`where`] function and its SQL-like operators: [`first`], [`last`], and [`after`]. You can even [order the content][lists] the way you've become used to with Hugo.
@@ -18,10+18,10 @@ The real power of Hugo pagination shines when combined with the [`where`] functi
Pagination can be configured in your [site configuration][configuration]:
-`paginate`
+paginate
: default = `10`. This setting can be overridden within the template.
-`paginatePath`
+paginatePath
: default = `page`. Allows you to set a different path for your pagination pages.
Setting `paginate` to a positive value will split the list pages for the homepage, sections and taxonomies into chunks of that size. But note that the generation of the pagination pages for sections, taxonomies and homepage is *lazy* --- the pages will not be created if not referenced by a `.Paginator` (see below).
@@ -78,7+78,7 @@ The following example shows how to create `.Paginator` before its used:
-The `partialCached` template function provides significant performance gains for complex templates that don't need to be re-rendered on every invocation. See[details][partialcached].
+The `partialCached` template function provides significant performance gains for complex templates that don't need to be re-rendered on every invocation. See [details][partialcached].
## Examples
@@ -136,7+136,7 @@ The `partialCached` template function provides significant performance gains for
The following `header.html` partial template is used for [spf13.com](https://spf13.com/):
@@ -23,7+23,7 @@ The hook kinds currently supported are:
* `image`
* `link`
* `heading`
-* `codeblock`{{< new-in "0.93.0" >}}
+* `codeblock`{{< new-in 0.93.0 >}}
You can define [Output-Format-](/templates/output-formats) and [language-](/content-management/multilingual/)specific templates if needed. Your `layouts` folder may look like this:
: Returns true if this is a standalone image and the configuration option [markup.goldmark.parser.wrapStandAloneImageWithinParagraph](/getting-started/configuration-markup/#goldmark) is disabled.
-Ordinal {{< new-in "0.108.0" >}}
+Ordinal {{< new-in 0.108.0 >}}
: Zero-based ordinal for all the images in the current document.
By default, when you build your site, Hugo generates RSS feeds for home, section, taxonomy, and term pages. Control feed generation in your site configuration. For example, to generate feeds for home and section pages, but not for taxonomy and term pages:
@@ -28,7+29,7 @@ Hugo's built-in shortcodes cover many common, but not all, use cases. Luckily, H
To create a shortcode, place an HTML template in the `layouts/shortcodes` directory of your [source organization]. Consider the file name carefully since the shortcode name will mirror that of the file but without the `.html` extension. For example, `layouts/shortcodes/myshortcode.html` will be called with either `{{</* myshortcode /*/>}}` or `{{%/* myshortcode /*/%}}`.
-You can organize your shortcodes in subfolders, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g:
+You can organize your shortcodes in subdirectories, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g:
```go-html-template
{{</* boxes/square */>}}
@@ -117,13+118,13 @@ Any shortcode that refers to `.Inner` must be closed or self-closed.
The `.Params` variable in shortcodes contains the list parameters passed to shortcode for more complicated use cases. You can also access higher-scoped parameters with the following logic:
-`$.Params`
+$.Params
: these are the parameters passed directly into the shortcode declaration (e.g., a YouTube video ID)
-`$.Page.Params`
+$.Page.Params
: refers to the page's parameters; the "page" in this case refers to the content file in which the shortcode is declared (e.g., a `shortcode_color` field in a content's front matter could be accessed via `$.Page.Params.shortcode_color`).
-`$.Page.Site.Params`
+$.Page.Site.Params
: refers to global variables as defined in your [site's configuration file][config].
#### `.IsNamedParams`
@@ -172,7+173,7 @@ Let's assume you would like to keep mentions of your copyright year current in y
@@ -207,13+208,13 @@ Would load the template at `/layouts/shortcodes/youtube.html`:
Let's say you want to create your own `img` shortcode rather than use Hugo's built-in [`figure` shortcode][figure]. Your goal is to be able to call the shortcode as follows in your content files:
@@ -318,7+319,7 @@ The following example is contrived but demonstrates the concept. Assume you have
You also have an `img` shortcode with a single named `src` parameter that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`:
@@ -349,9+350,9 @@ This will output the following HTML. Note how the first two `img` shortcodes inh
## Error handling in shortcodes
-Use the [errorf](/functions/fmt/errorf) template func and [.Position](/variables/shortcodes/) variable to get useful error messages in shortcodes:
+Use the [errorf](/functions/fmt/errorf) template func and [.Position](/variables/shortcode/) variable to get useful error messages in shortcodes:
-```bash
+```sh
{{ with .Get "name" }}
{{ else }}
{{ errorf "missing value for parameter 'name': %s" .Position }}
@@ -360,21+361,17 @@ Use the [errorf](/functions/fmt/errorf) template func and [.Position](/variables
When the above fails, you will see an `ERROR` log similar to the below:
-```bash
+```sh
ERROR 2018/11/07 10:05:55 missing value for parameter name: "/Users/bep/dev/go/gohugoio/hugo/docs/content/en/variables/shortcodes.md:32:1"
```
-## More shortcode examples
-
-More shortcode examples can be found in the [shortcodes directory for spf13.com][spfscs] and the [shortcodes directory for the Hugo docs][docsshortcodes].
-
## Inline shortcodes
You can also implement your shortcodes inline -- e.g. where you use them in the content file. This can be useful for scripting that you only need in one place.
This feature is disabled by default, but can be enabled in your site configuration:
-{{< code-toggle file="hugo" >}}
+{{< code-toggle file=hugo >}}
enableInlineShortcodes = true
{{< /code-toggle >}}
@@ -382,7+379,7 @@ It is disabled by default for security reasons. The security model used by Hugo'
And once enabled, you can do this in your content files:
- ```go-text-template
+ ```go-html-template
{{</* time.inline */>}}{{ now }}{{</* /time.inline */>}}
```
@@ -394,7+391,7 @@ This means that the current page can be accessed via `.Page.Title` etc. This als
The same inline shortcode can be reused later in the same content file, with different parameters if needed, using the self-closing syntax:
- ```go-text-template
+ ```go-html-template
{{</* time.inline /*/>}}
```
@@ -408,8+405,8 @@ The same inline shortcode can be reused later in the same content file, with dif
@@ -24,7+24,7 @@ Content pages are of the type `page` and will therefore have all the [page varia
This single page template makes use of Hugo [base templates], the [`.Format` function] for dates, the [`.WordCount` page variable][pagevars], and ranges through the single content's specific [taxonomies][pagetaxonomy]. [`with`] is also used to check whether the taxonomies are set in the front matter.
-{{< code file="layouts/posts/single.html" >}}
+{{< code file=layouts/posts/single.html >}}
{{ define "main" }}
<section id="main">
<h1 id="title">{{ .Title }}</h1>
@@ -38,7+38,7 @@ This single page template makes use of Hugo [base templates], the [`.Format` fun
<div>
<section>
<h4 id="date"> {{ .Date.Format "Mon Jan 2, 2006" }} </h4>
- <h5 id="wordcount"> {{ .WordCount }} Words</h5>
+ <h5 id="wordcount"> {{ .WordCount }} Words</h5>
</section>
{{ with .GetTerms "topics" }}
<ul id="topics">
@@ -57,10+57,10 @@ This single page template makes use of Hugo [base templates], the [`.Format` fun
description: Hugo provides built-in sitemap templates.
categories: [templates]
-keywords: [sitemap, xml, templates]
+keywords: [sitemap,xml,templates]
menu:
docs:
parent: templates
weight: 170
weight: 170
-aliases: [/layout/sitemap/,/templates/sitemap/]
toc: true
+aliases: [/layout/sitemap/,/templates/sitemap/]
---
## Overview
@@ -27,7+27,7 @@ With a multilingual project, Hugo generates:
Set the default values for [change frequency] and [priority], and the name of the generated file, in your site configuration.
-{{< code-toggle config="sitemap" />}}
+{{< code-toggle config=sitemap />}}
changefreq
: How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. Default is `""` (change frequency omitted from rendered sitemap).
-<!-- NOTE! Check on https://github.com/gohugoio/hugo/issues/2826 for shifting of terms' pages to .Data.Pages AND
-https://discourse.gohugo.io/t/how-to-specify-category-slug/4856/15 for original discussion.-->
-
Hugo includes support for user-defined groupings of content called **taxonomies**. Taxonomies are classifications that demonstrate logical relationships between content. See [Taxonomies under Content Management](/content-management/taxonomies) if you are unfamiliar with how Hugo leverages this powerful feature.
Hugo provides multiple ways to use taxonomies throughout your project templates:
@@ -111,15+108,13 @@ If you need to display custom metadata for each taxonomy term, you will need to
@@ -311,19+300,18 @@ This example will list all taxonomies and their terms, as well as all the conten
Because taxonomies are lists, the [`.GetPage` function][getpage] can be used to get all the pages associated with a particular taxonomy term using a terse syntax. The following ranges over the full list of tags on your site and links to each of the individual taxonomy pages for each term without having to use the more fragile URL construction of the ["List All Site Tags" example above](#example-list-all-site-tags):
-description: You can use Go templates' `printf` function to debug your Hugo templates. These snippets provide a quick and easy visualization of the variables available to you in different contexts.
-categories: [templates]
-keywords: [debugging,troubleshooting]
-menu:
- docs:
- parent: templates
- weight: 240
-weight: 240
----
-
-Here are some snippets you can add to your template to answer some common questions.
-
-These snippets use the `printf` function available in all Go templates. This function is an alias to the Go function, [fmt.Printf](https://pkg.go.dev/fmt).
-
-## What variables are available in this context?
-
-You can use the template syntax, `$.`, to get the top-level template context from anywhere in your template. This will print out all the values under, `.Site`.
-
-```go-html-template
-{{ printf "%#v" $.Site }}
-```
-
-This will print out the value of `.Permalink`:
-
-```go-html-template
-{{ printf "%#v" .Permalink }}
-```
-
-This will print out a list of all the variables scoped to the current context
-(`.`, aka ["the dot"][tempintro]).
-
-```go-html-template
-{{ printf "%#v" . }}
-```
-
-When developing a [homepage], what does one of the pages you're looping through look like?
-
-```go-html-template
-{{ range .Pages }}
- {{/* The context, ".", is now each one of the pages as it goes through the loop */}}
- {{ printf "%#v" . }}
-{{ end }}
-```
-
-In some cases it might be more helpful to use the following snippet on the current context to get a pretty printed view of what you're able to work with:
-
-```go-html-template
-<pre>{{ . | jsonify (dict "indent" " ") }}</pre>
-```
-
-Note that Hugo will throw an error if you attempt to use this construct to display context that includes a page collection (e.g., the context passed to home, section, taxonomy, and term templates).
-
-## Why am I showing no defined variables?
-
-Check that you are passing variables in the `partial` function:
-
-```go-html-template
-{{ partial "header.html" }}
-```
-
-This example will render the header partial, but the header partial will not have access to any contextual variables. You need to pass variables explicitly. For example, note the addition of ["the dot"][tempintro].
-
-```go-html-template
-{{ partial "header.html" . }}
-```
-
-The dot (`.`) is considered fundamental to understanding Hugo templating. For more information, see [Introduction to Hugo Templating][tempintro].
@@ -36,7+36,6 @@ To create a new view, create a template in each of your different content type d
Hugo also has support for a default content template to be used in the event that a specific content view template has not been provided for that type. Content views can also be defined in the `_default` directory and will work the same as list and single templates who eventually trickle down to the `_default` directory as a matter of the lookup order.
-
```txt
▾ layouts/
▾ _default/
@@ -62,7+61,7 @@ The following example demonstrates how to use content views inside your [list te
In this example, `.Render` is passed into the template to call the [render function][render]. `.Render` is a special function that instructs content to render itself with the view template provided as the first argument. In this case, the template is going to render the `summary.html` view that follows:
-{{< code file="layouts/_default/list.html" >}}
+{{< code file=layouts/_default/list.html >}}
<main id="main">
<div>
<h1 id="title">{{ .Title }}</h1>
@@ -77,15+76,15 @@ In this example, `.Render` is passed into the template to call the [render funct
Hugo will pass the entire page object to the following `summary.html` view template. (See [Page Variables][pagevars] for a complete list.)
@@ -94,9+93,9 @@ Hugo will pass the entire page object to the following `summary.html` view templ
Continuing on the previous example, we can change our render function to use a smaller `li.html` view by changing the argument in the call to the `.Render` function (i.e., `{{ .Render "li" }}`).
-description: The Hugo community uses a wide range of preferred tools and has developed plug-ins for some of the most popular text editors to help automate parts of your workflow.
+description: The Hugo community uses a wide range of tools and has developed plugins for some of the most popular text editors to help automate parts of your workflow.
categories: [developer tools]
-keywords: [editor, plug-ins]
+keywords: [editor,plugin]
menu:
docs:
parent: developer-tools
weight: 20
weight: 20
+toc: true
---
-## Sublime Text
+## Visual Studio Code
-* [Hugofy](https://github.com/akmittal/Hugofy). Hugofy is a plugin for Sublime Text 3 to make life easier to use Hugo static site generator.
-* [Hugo Snippets](https://packagecontrol.io/packages/Hugo%20Snippets). Hugo Snippets is a useful plugin for adding automatic snippets to Sublime Text 3.
+: Once you go for a static site, you need to think about how you are going to manage your articles. Front matter is a tool that helps you maintain the metadata/front matter of your articles like: creation date, modified date, slug, tile, SEO check, and more.
+: Hugo Helper is a plugin for Visual Studio Code that has some useful commands for Hugo. The source code can be found [here](https://github.com/rusnasonov/vscode-hugo).
+
+[Hugo Language and Syntax Support](https://marketplace.visualstudio.com/items?itemName=budparr.language-hugo-vscode)
+: Hugo Language and Syntax Support is a Visual Studio Code plugin for Hugo syntax highlighting and snippets. The source code can be found [here](https://github.com/budparr/language-hugo-vscode).
-* [Front Matter](https://marketplace.visualstudio.com/items?itemName=eliostruyf.vscode-front-matter). Once you go for a static site, you need to think about how you are going to manage your articles. Front matter is a tool that helps you maintain the metadata/front matter of your articles like: creation date, modified date, slug, tile, SEO check, and many more...
-* [Hugo Helper](https://marketplace.visualstudio.com/items?itemName=rusnasonov.vscode-hugo). Hugo Helper is a plugin for Visual Studio Code that has some useful commands for Hugo. The source code can be found [here](https://github.com/rusnasonov/vscode-hugo).
-* [Hugo Language and Syntax Support](https://marketplace.visualstudio.com/items?itemName=budparr.language-hugo-vscode). Hugo Language and Syntax Support is a Visual Studio Code plugin for Hugo syntax highlighting and snippets. The source code can be found [here](https://github.com/budparr/language-hugo-vscode).
-* [Hugo Themer](https://marketplace.visualstudio.com/items?itemName=eliostruyf.vscode-hugo-themer). Hugo Themer is an extension to help you while developing themes. It allows you to easily navigate through your theme files.
-* [Hugofy](https://marketplace.visualstudio.com/items?itemName=akmittal.hugofy). Hugofy is a plugin for Visual Studio Code to "make life easier" when developing with Hugo. The source code can be found [here](https://github.com/akmittal/hugofy-vscode).
-* [Prettier Plugin for Go Templates](https://github.com/NiklasPor/prettier-plugin-go-template). Format Hugo templates using this [Prettier](https://prettier.io/) plugin. See [installation instructions](https://discourse.gohugo.io/t/38403).
-* [Syntax Highlighting for Hugo Shortcodes](https://marketplace.visualstudio.com/items?itemName=kaellarkin.hugo-shortcode-syntax). This extension adds some syntax highlighting for Shortcodes, making visual identification of individual pieces easier.
+: Hugofy is a plugin for Visual Studio Code to "make life easier" when developing with Hugo. The source code can be found [here](https://github.com/akmittal/hugofy-vscode).
+
+[Prettier Plugin for Go Templates](https://github.com/NiklasPor/prettier-plugin-go-template)
+: Format Hugo templates using this [Prettier](https://prettier.io/) plugin. See [installation instructions](https://discourse.gohugo.io/t/38403).
+
+[Syntax Highlighting for Hugo Shortcodes](https://marketplace.visualstudio.com/items?itemName=kaellarkin.hugo-shortcode-syntax)
+: This extension adds some syntax highlighting for Shortcodes, making visual identification of individual pieces easier.
## Emacs
-* [emacs-easy-hugo](https://github.com/masasam/emacs-easy-hugo). Emacs major mode for managing hugo blogs. Note that Hugo also supports [Org-mode][formats].
-* [ox-hugo.el](https://ox-hugo.scripter.co). Native Org-mode exporter that exports to Blackfriday Markdown with Hugo front-matter. `ox-hugo` supports two common Org blogging flows --- exporting multiple Org subtrees in a single file to multiple Hugo posts, and exporting a single Org file to a single Hugo post. It also leverages the Org tag and property inheritance features. See [*Why ox-hugo?*](https://ox-hugo.scripter.co/doc/why-ox-hugo/) for more.
+: Emacs major mode for managing hugo blogs. Note that Hugo also supports [Org-mode][formats].
+
+[ox-hugo.el](https://ox-hugo.scripter.co)
+: Native Org-mode exporter that exports to Blackfriday Markdown with Hugo front-matter. `ox-hugo` supports two common Org blogging flows --- exporting multiple Org subtrees in a single file to multiple Hugo posts, and exporting a single Org file to a single Hugo post. It also leverages the Org tag and property inheritance features. See [*Why ox-hugo?*](https://ox-hugo.scripter.co/doc/why-ox-hugo/) for more.
+
+## Sublime Text
+
+[Hugofy](https://github.com/akmittal/Hugofy)
+: Hugofy is a plugin for Sublime Text 3 to make life easier to use Hugo static site generator.
+description: Do you prefer a graphical user interface over a text editor? Give these front-ends a try.
+categories: [developer tools]
+keywords: [frontend, gui]
+menu:
+ docs:
+ parent: developer-tools
+ weight: 30
+weight: 30
+toc: true
+aliases: [/tools/frontends/]
+---
+
+## Commercial
+
+[CloudCannon](https://cloudcannon.com/hugo-cms/)
+: The intuitive Git-based CMS for your Hugo website. CloudCannon syncs changes from your Git repository and pushes content changes back, so your development and content teams are always in sync. Edit all of your content on the page with visual editing, build entire pages with reusable custom components and then publish confidently.
+
+[DatoCMS](https://www.datocms.com)
+: DatoCMS is a fully customizable administrative area for your static websites. Use your favorite website generator, let your clients publish new content independently, and the host the site anywhere you like.
+
+## Open source
+
+[Decap CMS](https://decapcms.org/)
+: Decap CMS is an open-source, serverless solution for managing Git based content in static sites, and it works on any platform that can host static sites. A [Hugo/Decap CMS starter](https://github.com/decaporg/one-click-hugo-cms) is available to get new projects running quickly.
+: Sveltia CMS is a drop-in replacement for Decap CMS which is built from the ground up with powerful and performant modern UI library Svelte. Sveltia CMS incorporates i18n into every corner of the product, while striving to radically improve UX, performance and productivity.
-description: Do you prefer a graphical user interface over a text editor? Give these frontends a try.
-categories: [developer tools]
-keywords: [frontend, gui]
-menu:
- docs:
- parent: developer-tools
- weight: 30
-weight: 30
----
-
-- [enwrite](https://github.com/zzamboni/enwrite). Enwrite enables evernote-powered, statically generated blogs and websites. Now posting to your blog or updating your website is as easy as writing a new note in Evernote!
-- [Lipi](https://github.com/SohanChy/Lipi). Lipi is a native GUI frontend written in Java to manage your Hugo websites.
-- [Decap CMS (formerly Netlify CMS)](https://decapcms.org/). Decap CMS is an open source, serverless solution for managing Git based content in static sites, and it works on any platform that can host static sites. A [Hugo/Decap CMS starter](https://github.com/decaporg/one-click-hugo-cms) is available to get new projects running quickly.
-- [Hokus CMS](https://github.com/julianoappelklein/hokus). Hokus CMS is an open source, multi-platform, easy to use, desktop application for Hugo. Build from simple to complex user interfaces for Hugo websites by choosing from a dozen ready-to-use components — all for free, with no vendor lock-in.
-
-## Commercial services
-
-- [DATOCMS](https://www.datocms.com) DatoCMS is a fully customizable administrative area for your static websites. Use your favorite website generator, let your clients publish new content independently, and the host the site anywhere you like.
-- [CloudCannon](https://cloudcannon.com/hugo-cms/). The intuitive Git-based CMS for your Hugo website. CloudCannon syncs changes from your Git repository and pushes content changes back, so your development and content teams are always in sync. Edit all of your content on the page with visual editing, build entire pages with reusable custom components and then publish confidently.
This section highlights some projects around Hugo that are independently developed. These tools try to extend the functionality of our static site generator or help you to get started.
-{{% note %}}
-Do you know or maintain a similar project around Hugo? Feel free to open a [pull request](https://github.com/gohugoio/hugoDocs/pulls) on GitHub if you think it should be added.
-{{% /note %}}
-
Take a look at this list of migration tools if you currently use other blogging tools like Jekyll or WordPress but intend to switch to Hugo instead. They'll take care to export your content into Hugo-friendly formats.
## Jekyll
-Alternatively, you can use the new [Jekyll import command](/commands/hugo_import_jekyll/).
+Alternatively, you can use the [Jekyll import command](/commands/hugo_import_jekyll/).
-- [JekyllToHugo](https://github.com/fredrikloch/JekyllToHugo) - A Small script for converting Jekyll blog posts to a Hugo site.
-- [ConvertToHugo](https://github.com/coderzh/ConvertToHugo) - Convert your blog from Jekyll to Hugo.
-- [octohug](https://github.com/codebrane/octohug) - Octopress to Hugo migrator.
+[octohug](https://github.com/codebrane/octohug)
+: Octopress to Hugo migrator.
## DokuWiki
-- [dokuwiki-to-hugo](https://github.com/wgroeneveld/dokuwiki-to-hugo) - Migrates your DokuWiki source pages from [DokuWiki syntax](https://www.dokuwiki.org/wiki:syntax) to Hugo Markdown syntax. Includes extra's like the TODO plugin. Written with extensibility in mind using python 3. Also generates a TOML header for each page. Designed to copypaste the wiki directory into your /content directory.
+: Migrates your DokuWiki source pages from [DokuWiki syntax](https://www.dokuwiki.org/wiki:syntax) to Hugo Markdown syntax. Includes extra's like the TODO plugin. Written with extensibility in mind using python 3. Also generates a TOML header for each page. Designed to copypaste the wiki directory into your /content directory.
## WordPress
-- [wordpress-to-hugo-exporter](https://github.com/SchumacherFM/wordpress-to-hugo-exporter) - A one-click WordPress plugin that converts all posts, pages, taxonomies, metadata, and settings to Markdown and YAML which can be dropped into Hugo. (Note: If you have trouble using this plugin, you can [export your site for Jekyll](https://wordpress.org/plugins/jekyll-exporter/) and use Hugo's built in Jekyll converter listed above.)
-- [blog2md](https://github.com/palaniraja/blog2md) - Works with [exported xml](https://en.support.wordpress.com/export/) file of your free YOUR-TLD.wordpress.com website. It also saves approved comments to `YOUR-POST-NAME-comments.md` file along with posts.
-- [wordhugopress](https://github.com/nantipov/wordhugopress) - A small utility written in Java, exports the entire WordPress site from the database and resource (e.g. images) files stored locally or remotely. Therefore, migration from the backup files is possible. Supports merging of the multiple WordPress sites into a single Hugo one.
+: A one-click WordPress plugin that converts all posts, pages, taxonomies, metadata, and settings to Markdown and YAML which can be dropped into Hugo. (Note: If you have trouble using this plugin, you - \s-\scan [export your site for Jekyll](https://wordpress.org/plugins/jekyll-exporter/) and use Hugo's built in Jekyll converter listed above.)
+
+[blog2md](https://github.com/palaniraja/blog2md)
+: Works with [exported xml](https://en.support.wordpress.com/export/) file of your free YOUR-TLD.wordpress.com website. It also saves approved comments to `YOUR-POST-NAME-comments.md` file along with posts.
+: A small utility written in Java, exports the entire WordPress site from the database and resource (e.g. images) files stored locally or remotely. Therefore, migration from the backup files is possible. Supports merging of the multiple WordPress sites into a single Hugo one.
## Medium
-- [medium2md](https://github.com/gautamdhameja/medium-2-md) - A simple Medium to Hugo exporter able to import stories in one command, including front matter.
-- [medium-to-hugo](https://github.com/bgadrian/medium-to-hugo) - CLI tool written in Go to export medium posts into a Hugo compatible Markdown format. Tags and images are included. All images will be downloaded locally and linked appropriately.
+: CLI tool written in Go to export medium posts into a Hugo compatible Markdown format. Tags and images are included. All images will be downloaded locally and linked appropriately.
## Tumblr
-- [tumblr-importr](https://github.com/carlmjohnson/tumblr-importr) - An importer that uses the Tumblr API to create a Hugo static site.
-- [tumblr2hugomarkdown](https://github.com/Wysie/tumblr2hugomarkdown) - Export all your Tumblr content to Hugo Markdown files with preserved original formatting.
-- [Tumblr to Hugo](https://github.com/jipiboily/tumblr-to-hugo) - A migration tool that converts each of your Tumblr posts to a content file with a proper title and path. Furthermore, "Tumblr to Hugo" creates a CSV file with the original URL and the new path on Hugo, to help you setup the redirections.
+: Export all your Tumblr content to Hugo Markdown files with preserved original formatting.
+
+[Tumblr to Hugo](https://github.com/jipiboily/tumblr-to-hugo)
+: A migration tool that converts each of your Tumblr posts to a content file with a proper title and path. Furthermore, "Tumblr to Hugo" creates a CSV file with the original URL and the new path on Hugo, to help you setup the redirections.
## Drupal
-- [drupal2hugo](https://github.com/danapsimer/drupal2hugo) - Convert a Drupal site to Hugo.
-- [hugojoomla](https://github.com/davetcc/hugojoomla) - This utility written in Java takes a Joomla database and converts all the content into Markdown files. It changes any URLs that are in Joomla's internal format and converts them to a suitable form.
+: This utility written in Java takes a Joomla database and converts all the content into Markdown files. It changes any URLs that are in Joomla's internal format and converts them to a suitable form.
## Blogger
-- [blogimport](https://github.com/natefinch/blogimport) - A tool to import from Blogger posts to Hugo.
-- [blogger-to-hugo](https://pypi.org/project/blogger-to-hugo/) - Another tool to import Blogger posts to Hugo. It also downloads embedded images so they will be stored locally.
-- [blog2md](https://github.com/palaniraja/blog2md) - Works with [exported xml](https://support.google.com/blogger/answer/41387?hl=en) file of your YOUR-TLD.blogspot.com website. It also saves comments to `YOUR-POST-NAME-comments.md` file along with posts.
-- [BloggerToHugo](https://github.com/huanlin/blogger-to-hugo) - Yet another tool to import Blogger posts to Hugo. For Windows platform only, and .NET Framework 4.5 is required. See README.md before using this tool.
+: Another tool to import Blogger posts to Hugo. It also downloads embedded images so they will be stored locally.
+
+[blog2md](https://github.com/palaniraja/blog2md)
+: Works with [exported xml](https://support.google.com/blogger/answer/41387?hl=en) file of your YOUR-TLD.blogspot.com website. It also saves comments to `YOUR-POST-NAME-comments.md` file along with posts.
+: Yet another tool to import Blogger posts to Hugo. For Windows platform only, and .NET Framework 4.5 is required. See README.md before using this tool.
## Contentful
-- [contentful-hugo](https://github.com/ModiiMedia/contentful-hugo) - A tool to create content-files for Hugo from content on [Contentful](https://www.contentful.com/).
+: A tool to create content-files for Hugo from content on [Contentful](https://www.contentful.com/).
## BlogML
-- [BlogML2Hugo](https://github.com/jijiechen/BlogML2Hugo) - A tool that helps you convert BlogML xml file to Hugo Markdown files. Users need to take care of links to attachments and images by themselves. This helps the blogs that export BlogML files (e.g. BlogEngine.NET) transform to hugo sites easily.
+: A tool that helps you convert BlogML xml file to Hugo Markdown files. Users need to take care of links to attachments and images by themselves. This helps the blogs that export BlogML files (e.g. BlogEngine.NET) transform to hugo sites easily.
description: Some interesting projects developed by the Hugo community that don't quite fit into our other developer tool categories.
categories: [developer tools]
-keywords: [frontend,gui]
+keywords: [frontend,gui]
menu:
docs:
parent: developer-tools
@@ -17,7+17,7 @@ And for all the other small things around Hugo:
- [flickr-hugo-embed](https://github.com/nikhilm/flickr-hugo-embed) prints shortcodes to embed a set of images from an album on Flickr into Hugo.
- [hugo-openapispec-shortcode](https://github.com/tenfourty/hugo-openapispec-shortcode) A shortcode that allows you to include [Open API Spec](https://openapis.org) (formerly known as Swagger Spec) in a page.
- [HugoPhotoSwipe](https://github.com/GjjvdBurg/HugoPhotoSwipe) makes it easy to create image galleries using PhotoSwipe.
-- [Hugo SFTP Upload](https://github.com/thomasmey/HugoSftpUpload) Syncs the local build of your Hugo website with your remote webserver via SFTP.
+- [Hugo SFTP Upload](https://github.com/thomasmey/HugoSftpUpload) Syncs the local build of your Hugo website with your remote webserver via SFTP.
- [Emacs Easy Hugo](https://github.com/masasam/emacs-easy-hugo) Emacs package for writing blog posts in markdown or org-mode and building your site with Hugo.
- [JAMStack Themes](https://jamstackthemes.dev/ssg/hugo/). JAMStack themes is a collection of site themes filterable by static site generator and supported CMS to help build CMS-connected sites using Hugo (linking to Hugo-specific themes).
- [plausible-hugo](https://github.com/divinerites/plausible-hugo). Easy Hugo integration for Plausible Analytics, a simple, open-source, lightweight and privacy-friendly web analytics alternative to Google Analytics.
A static website with a dynamic search function? Yes, Hugo provides an alternative to embeddable scripts from Google or other search engines for static websites. Hugo allows you to provide your visitors with a custom search function by indexing your content files directly.
-* [GitHub Gist for Hugo Workflow](https://gist.github.com/sebz/efddfc8fdcb6b480f567). This gist contains a simple workflow to create a search index for your static website. It uses a simple Grunt script to index all your content files and [lunr.js](https://lunrjs.com/) to serve the search results.
+## Open source
-* [hugo-lunr](https://www.npmjs.com/package/hugo-lunr). A simple way to add site search to your static Hugo site using [lunr.js](https://lunrjs.com/). Hugo-lunr will create an index file of any HTML and Markdown documents in your Hugo project.
-* [hugo-lunr-zh](https://www.npmjs.com/package/hugo-lunr-zh). A bit like Hugo-lunr, but Hugo-lunr-zh can help you separate the Chinese keywords.
-* [GitHub Gist for Fuse.js integration](https://gist.github.com/eddiewebb/735feb48f50f0ddd65ae5606a1cb41ae). This gist demonstrates how to leverage Hugo's existing build time processing to generate a searchable JSON index used by [Fuse.js](https://fusejs.io/) on the client-side. Although this gist uses Fuse.js for fuzzy matching, any client-side search tool capable of reading JSON indexes will work. Does not require npm, grunt or other build-time tools except Hugo!
-* [hugo-search-index](https://www.npmjs.com/package/hugo-search-index). A library containing Gulp tasks and a prebuilt browser script that implements search. Gulp generates a search index from project markdown files.
-* [hugofastsearch](https://gist.github.com/cmod/5410eae147e4318164258742dd053993). A usability and speed update to "GitHub Gist for Fuse.js integration" — global, keyboard-optimized search.
-* [JS & Fuse.js tutorial](https://makewithhugo.com/add-search-to-a-hugo-site/) A simple client-side search solution, using FuseJS (does not require jQuery).
-* [Pagefind](https://github.com/cloudcannon/pagefind). A fully static search library that aims to perform well on large sites, while using as little of your users' bandwidth as possible.
-* [Hugo Lyra](https://github.com/paolomainardi/hugo-lyra). Hugo-Lyra is a JavaScript module to integrate [Lyra](https://github.com/LyraSearch/lyra) into a Hugo website. It contains the server-side part to generate the index and the client-side library (optional) to bootstrap the search engine easily.
+: A fully static search library that aims to perform well on large sites, while using as little of your users' bandwidth as possible.
-## Commercial search services
+[GitHub Gist for Hugo Workflow](https://gist.github.com/sebz/efddfc8fdcb6b480f567)
+: This gist contains a simple workflow to create a search index for your static website. It uses a simple Grunt script to index all your content files and [lunr.js](https://lunrjs.com/) to serve the search results.
-* [Algolia](https://www.algolia.com/)'s Search API makes it easy to deliver a great search experience in your apps and websites. Algolia Search provides hosted full-text, numerical, faceted, and geolocalized search.
-* [Bonsai](https://www.bonsai.io) is a fully-managed hosted Elasticsearch service that is fast, reliable, and simple to set up. Easily ingest your docs from Hugo into Elasticsearch following [this guide from the docs](https://docs.bonsai.io/hc/en-us/articles/13929190788756-Hugo).
-* [ExpertRec](https://www.expertrec.com/) is a hosted search-as-a-service solution that is fast and scalable. Set-up and integration is extremely easy and takes only a few minutes. The search settings can be modified without coding using a dashboard.
+: A simple way to add site search to your static Hugo site using [lunr.js](https://lunrjs.com/). Hugo-lunr will create an index file of any HTML and Markdown documents in your Hugo project.
+: A bit like Hugo-lunr, but Hugo-lunr-zh can help you separate the Chinese keywords.
+
+[GitHub Gist for Fuse.js integration](https://gist.github.com/eddiewebb/735feb48f50f0ddd65ae5606a1cb41ae)
+: This gist demonstrates how to leverage Hugo's existing build time processing to generate a searchable JSON index used by [Fuse.js](https://fusejs.io/) on the client-side. Although this gist uses Fuse.js for fuzzy matching, any client-side search tool capable of reading JSON indexes will work. Does not require npm, grunt or other build-time tools except Hugo!
+: Hugo-Lyra is a JavaScript module to integrate [Lyra](https://github.com/LyraSearch/lyra) into a Hugo website. It contains the server-side part to generate the index and the client-side library (optional) to bootstrap the search engine easily.
+
+## Commercial
+
+[Algolia](https://www.algolia.com/)
+: Algolia's Search API makes it easy to deliver a great search experience in your apps and websites. Algolia Search provides hosted full-text, numerical, faceted, and geolocalized search.
+
+[Bonsai](https://www.bonsai.io)
+: Bonsai is a fully-managed hosted Elasticsearch service that is fast, reliable, and simple to set up. Easily ingest your docs from Hugo into Elasticsearch following [this guide from the docs](https://docs.bonsai.io/hc/en-us/articles/13929190788756-Hugo).
+
+[ExpertRec](https://www.expertrec.com/)
+: ExpertRec is a hosted search-as-a-service solution that is fast and scalable. Set-up and integration is extremely easy and takes only a few minutes. The search settings can be modified without coding using a dashboard.
+description: Run this audit before deploying your production site.
+categories: [troubleshooting]
+keywords: []
+menu:
+ docs:
+ parent: troubleshooting
+ weight: 20
+weight: 20
+---
+
+There are several conditions that can produce errors in your published site which are not detected during the build. Run this audit before your final build.
+
+{{< code copy=true >}}
+HUGO_MINIFY_TDEWOLFF_HTML_KEEPCOMMENTS=true HUGO_ENABLEMISSINGTRANSLATIONPLACEHOLDERS=true hugo && grep -inorE "<\!-- raw HTML omitted -->|ZgotmplZ|\[i18n\]|\(<nil>\)|(<nil>)|hahahugo" public/
+: Retain HTML comments even if minification is enabled. This takes precedence over `minify.tdewolff.html.keepComments` in the site configuration. If you minify without keeping HTML comments when performing this audit, you will not be able to detect when raw HTML has been omitted.
+
+`HUGO_ENABLEMISSINGTRANSLATIONPLACEHOLDERS=true`
+: Show a placeholder instead of the default value or an empty string if a translation is missing. This takes precedence over `enableMissingTranslationPlaceholders` in the site configuration.
+
+### Grep options
+
+`-i, --ignore-case`
+: Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other.
+
+`-n, --line-number`
+: Prefix each line of output with the 1-based line number within its input file.
+
+`-o, --only-matching`
+: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
+
+`-r, --recursive`
+: Read all files under each directory, recursively, following symbolic links only if they are on the command line.
+
+`-E, --extended-regexp`
+: Interpret PATTERNS as extended regular expressions.
+
+### Patterns
+
+`<!-- raw HTML omitted -->`
+: By default, Hugo strips raw HTML from your markdown prior to rendering, and leaves this HTML comment in its place.
+
+`ZgotmplZ`
+: ZgotmplZ is a special value that indicates that unsafe content reached a CSS or URL context at runtime. See [details].
+
+[details]: https://pkg.go.dev/html/template
+
+`[i18n]`
+: This is the placeholder produced instead of the default value or an empty string if a translation is missing.
+
+`(<nil>)`
+: This string will appear in the rendered HTML when passing a nil value to the `printf` function.
+
+`(<nil>)`
+: Same as above when the value returned from the `printf` function has not been passed through `safeHTML`.
+
+`HAHAHUGO`
+: Under certain conditions a rendered shortcode may include all or a portion of the string HAHAHUGOSHORTCODE in either uppercase or lowercase. This is difficult to detect in all circumstances, but a case-insensitive search of the output for `HAHAHUGO` is likely to catch the majority of cases without producing false positives.
-description: Solutions to some common Hugo problems.
+linkTitle: FAQs
+description: These questions are frequently asked by new users.
categories: [troubleshooting]
+keywords: [faq]
menu:
docs:
parent: troubleshooting
- weight: 20
-weight: 20
-keywords: [faqs]
-toc: true
-aliases: [/faq/]
+ weight: 70
+weight: 70
+# Use level 6 headings for each question.
---
-{{% note %}}
-**Note:** The answers/solutions presented below are short, and may not be enough to solve your problem. Visit [Hugo Discourse](https://discourse.gohugo.io/) and use the search. It that does not help, start a new topic and ask your questions.
-{{% /note %}}
+Hugo’s [forum] is an active community of users and developers who answer questions, share knowledge, and provide examples. A quick search of over 20,000 topics will often answer your question. Please be sure to read about [requesting help] before asking your first question.
+
+These are just a few of the questions most frequently asked by new users.
+
+###### An error message indicates that a feature is not available. Why?
+
+Hugo is available in two editions: standard and extended. With the extended edition you can (a) encode to the WebP format when processing images, and (b) transpile Sass to CSS using the embedded LibSass transpiler. The extended edition is not required to use the Dart Sass transpiler.
+
+When you attempt to perform either of the operations above with the standard edition, Hugo throws this error:
+
+```go-html-template
+Error: this feature is not available in your current Hugo version
+```
+
+To resolve, uninstall the standard edition, then install the extended edition. See the [installation] section for details.
+
+###### Why do I see "Page Not Found" when visiting the home page?
+
+In the content/_index.md file:
-## I can't see my content
+ - Is `draft` set to `true`?
+ - Is the `date` in the future?
+ - Is the `publishDate` in the future?
+ - Is the `expiryDate` in the past?
-Is your Markdown file [in draft mode](/content-management/front-matter/#front-matter-variables)? When testing, run `hugo server` with the `-D` or `--buildDrafts` [switch](/getting-started/usage/#draft-future-and-expired-content).
+If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`.
-Is your Markdown file part of a [leaf bundle](/content-management/page-bundles/)? If there is an `index.md` file in the same or any parent directory then other Markdown files will not be rendered as individual pages.
+###### Why is a given section not published?
-## Can I set configuration variables via OS environment?
+In the content/section/_index.md file:
-Yes you can! See [Configure with Environment Variables](/getting-started/configuration/#configure-with-environment-variables).
+ - Is `draft` set to `true`?
+ - Is the `date` in the future?
+ - Is the `publishDate` in the future?
+ - Is the `expiryDate` in the past?
-## How do I schedule posts?
+If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`.
-1. Set `publishDate` in the page [front matter](/content-management/front-matter/) to a datetime in the future. If you want the creation and publication datetime to be the same, it's also sufficient to only set `date`[^date-hierarchy].
-2. Build and publish at intervals.
+###### Why is a given page not published?
-How to automate the "publish at intervals" part depends on your situation:
+In the content/section/page.md file, or in the content/section/page/index.md file:
-* If you deploy from your own PC/server, you can automate with [Cron](https://en.wikipedia.org/wiki/Cron) or similar.
-* If your site is hosted on a service similar to [Netlify](https://www.netlify.com/) you can:
- * Use a service such as [ifttt](https://ifttt.com/date_and_time) to schedule the updates; or
- * Set up a deploy hook which you can run with a cron service to deploy your site at intervals, such as [cron-job.org](https://cron-job.org/) (both Netlify and Cloudflare Pages support deploy hooks)
+ - Is `draft` set to `true`?
+ - Is the `date` in the future?
+ - Is the `publishDate` in the future?
+ - Is the `expiryDate` in the past?
-Also see this Twitter thread:
+If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`.
+###### Why can't I see any of a page's descendants?
-[^date-hierarchy]: See [Configure Dates](/getting-started/configuration/#configure-dates) for the order in which the different date variables are complemented by each other when not explicitly set.
+You may have an index.md file instead of an _index.md file. See [details](/content-management/page-bundles/).
-## Can I use the latest Hugo version on Netlify?
+###### What is the difference between an index.md file and an _index.md file?
-[Yes you can](/hosting-and-deployment/hosting-on-netlify/#configure-hugo-version-in-netlify)!.
+A directory with an index.md file is a [leaf bundle]. A directory with an _index.md file is a [branch bundle]. See [details](/content-management/page-bundles/).
-## I get "... this feature is not available in your current Hugo version"
-If you process `SCSS` or `Sass` to `CSS` in your Hugo project with `libsass` as the transpiler or if you convert images to the `webp` format, you need the Hugo `extended` version, or else you may see an error message similar to the below:
+###### Why is my partial template not rendered as expected? {#foo}
-```bash
-error: failed to transform resource: TOCSS: failed to transform "scss/main.scss" (text/x-scss): this feature is not available in your current Hugo version
+You may have neglected to pass the required [context] when calling the partial. For example:
+
+```go-html-template
+{{/* incorrect */}}
+{{ partial "_internal/pagination.html" }}
+
+{{/* correct */}}
+{{ partial "_internal/pagination.html" . }}
```
-We release two set of binaries for technical reasons. The extended version is not what you get by default for some installation methods. On the [release page](https://github.com/gohugoio/hugo/releases), look for archives with `extended` in the name. To build `hugo-extended`, use `go install --tags extended`
+###### In a template, what's the difference between `:=` and `=` when assigning values to variables?
+
+Use `:=` to initialize a variable, and use `=` to assign a value to a variable that has been previously initialized. See [details](https://pkg.go.dev/text/template#hdr-Variables).
+
+###### When I paginate a list page, why is the page collection not filtered as specified?
+
+You are probably invoking the [`Paginate`] or [`Paginator`] method more than once on the same page. See [details](/templates/pagination/#list-paginator-pages).
+
+###### Why are there two ways to call a shortcode?
+
+Use the `{{%/* shortcode */%}}` notation if the shortcode template, or the content between the opening and closing shortcode tags, contains markdown. Otherwise use the\
+###### Why am I seeing inconsistent output from one build to the next?
+
+The most common causes are page collisions (publishing two pages to the same path) and the effects of concurrency. Use the `--printPathWarnings` command line flag to check for page collisions, and create a topic on the [forum] if you suspect concurrency problems.
+
+###### Which page methods trigger content rendering?
+
+The following methods on a `Page` object triggering content rendering: `Content`, `FuzzyWordCount`, `Len`, `Plain`, `PlainWords`, `ReadingTime`, `Summary`, `Truncated`, and `WordCount`.
+
+{{% note %}}
+For other questions please visit the [forum]. A quick search of over 20,000 topics will often answer your question. Please be sure to read about [requesting help] before asking your first question.
+Hugo will throw an error if you attempt to use the construct above to display context that includes a page collection. For example, in a home page template, this will fail:
+
+`{{ jsonify (dict "indent" " ") . }}`
+{{% /note %}}
+
+Use the [`debug.Dump`] function to inspect data types:
+
+```go-html-template
+<pre>{{ debug.Dump .Params }}</pre>
+```
+
+```text
+maps.Params{
+ "date": time.Time{},
+ "draft": false,
+ "iscjklanguage": false,
+ "lastmod": time.Time{},
+ "publishdate": time.Time{},
+ "tags": []string{
+ "foo",
+ "bar",
+ },
+ "title": "My first post",
+}
+```
+
+Use the [`printf`] function (render) or [`warnf`] function (log to console) to inspect simple data structures. The layout string below displays both value and data type.
+description: Enable logging to inspect events while building your site.
+categories: [troubleshooting]
+keywords: []
+menu:
+ docs:
+ parent: troubleshooting
+ weight: 30
+weight: 30
+toc: true
+---
+
+## Command line
+
+Enable console logging with the `--logLevel` command line flag.
+
+Hugo has four logging levels:
+
+error
+: Display error messages only.
+
+```sh
+hugo --logLevel error
+```
+
+warn
+: Display warning and error messages.
+
+```sh
+hugo --logLevel warn
+```
+
+info
+: Display information, warning, and error messages.
+
+```sh
+hugo --logLevel info
+```
+
+debug
+: Display debug, information, warning, and error messages.
+
+```sh
+hugo --logLevel debug
+```
+
+{{% note %}}
+If you do not specify a logging level with the `--logLevel` flag, warnings and errors are always displayed.
+{{% /note %}}
+
+## Template functions
+
+You can also use template functions to print warnings or errors to the console. These functions are typically used to report data validation errors, missing files, etc.
+description: Use template metrics and timers to identify opportunities to improve performance.
+categories: [troubleshooting]
+keywords: []
+menu:
+ docs:
+ parent: troubleshooting
+ weight: 60
+weight: 60
+toc: true
+aliases: [/troubleshooting/build-performance/]
+---
+
+## Template metrics
+
+Hugo is fast, but inefficient templates impede performance. Enable template metrics to determine which templates take the most time, and to identify caching opportunties:
+
+```sh
+hugo --templateMetrics --templateMetricsHints
+```
+
+The result will look something like this:
+
+```text
+Template Metrics:
+
+ cumulative average maximum cache percent cached total
+: The cumulative time spent executing the template.
+
+average duration
+: The average time spent executing the template.
+
+maximum duration
+: The maximum time spent executing the template.
+
+cache potential
+: Displayed as a percentage, any partial template with a 100% cache potential should be called with the [`partialCached`] function instead of the [`partial`] function. See the [caching](#caching) section below.
+
+percent cached
+: The number of times the rendered templated was cached divided by the number of times the template was executed.
+
+cached count
+: The number of times the rendered templated was cached.
+
+total count
+: The number of times the template was executed.
+
+template
+: The path to the template, relative to the layouts directory.
+Hugo builds pages in parallel where multiple pages are generated simultaneously. Because of this parallelism, the sum of "cumulative duration" values is usually greater than the actual time it takes to build a site.
+{{% /note %}}
+
+## Caching
+
+Some partial templates such as sidebars or menus are executed many times during a site build. Depending on the content within the partial template and the desired output, the template may benefit from caching to reduce the number of executions. The [`partialCached`] template function provides caching capabilities for partial templates.
+
+{{% note %}}
+Note that you can create cached variants of each partial by passing additional parameters to `partialCached` beyond the initial context. See the `partialCached` documentation for more details.
+{{% /note %}}
+
+## Timers
+
+Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottle necks in templates. See [details](/functions/debug/timer/).
+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.
+We are making an effort to unify our [terminology], and to use these terms consistently throughout the documentation.
+
+Historically, we have inconsistently referred to the items on this page as [functions], [parameters], [variables], or [methods]. They are not functions, parameters, or variables; they are methods.
+
+This page will remain in place as readers become familiar with the unified terminology. See the [methods section] for a list of methods by [object], or the [methods quick reference guide].
-description: Get the last Git revision information for every content file.
-categories: [variables and parameters]
-keywords: [git]
+description: Retrieve Git information related to the last commit of any page.
+categories: [variables]
+keywords: []
menu:
docs:
parent: variables
- weight: 70
-weight: 70
+ weight: 30
+weight: 30
aliases: [/extras/gitinfo/]
---
-{{% note %}}
-Hugo's Git integrations should be fairly performant but *can* increase your build time. This will depend on the size of your Git history.
-{{% /note %}}
+{{% include "variables/_common/consistent-terminology.md" %}}
-## `.GitInfo` prerequisites
+To retrieve Git information related to the last commit of any page, see the documentation for the [`GitInfo`] method on a `Page` object.
-1. The Hugo site must be in a Git-enabled directory.
-2. The Git executable must be installed and in your system `PATH`.
-3. The `.GitInfo` feature must be enabled in your Hugo project by passing `--enableGitInfo` flag on the command line or by setting `enableGitInfo` to `true` in your [site's configuration file][configuration].
-
-## The `.GitInfo` object
-
-The `GitInfo` object contains the following fields:
-
-.AbbreviatedHash
-: the abbreviated commit hash (e.g., `866cbcc`)
-
-.AuthorName
-: the author's name, respecting [`.mailmap`](https://git-scm.com/docs/gitmailmap)
-
-.AuthorEmail
-: the author's email address, respecting [`.mailmap`](https://git-scm.com/docs/gitmailmap)
-
-.AuthorDate
-: the author date
-
-.Hash
-: the commit hash (e.g., `866cbccdab588b9908887ffd3b4f2667e94090c3`)
-
-.Subject
-: commit message subject (e.g., `tpl: Add custom index function`)
-
-## `.Lastmod`
-
-If the `.GitInfo` feature is enabled, `.Lastmod` (on `Page`) is fetched from Git i.e. `.GitInfo.AuthorDate`. This behavior can be changed by adding your own [front matter configuration for dates](/getting-started/configuration/#configure-front-matter).
-
-[configuration]: /getting-started/configuration/
-
-## Hosting considerations
-
-On the site host, your repository must be "deep-cloned," so the returned `.GitInfo` data will be accurate. Otherwise, your site may display only data from your latest commit. Where it's not possible to configure a host's cloning depth, you must handle this through CI/CD (*e.g.*, a GitHub Action or GitLab CI/CD). See the following table:
-
-| Hosting service | Clone depth | Configurable? |
-[^CFP]: To configure a Cloudflare Pages site for deep cloning, preface the site's normal Hugo build command with `git fetch --unshallow &&` (*e.g.*, `git fetch --unshallow && hugo`).
-
-[^GHP]: You can configure the GitHub Action to do a deep clone by specifying `fetch-depth: 0` in the applicable "checkout" step of your workflow file, as shown in the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-github/#procedure).
-
-[^GLP]: You can configure the GitLab Runner's clone depth [as explained in the GitLab documentation](https://docs.gitlab.com/ee/ci/large_repositories/#shallow-cloning); see also the Hugo documentation's [example workflow file](https://gohugo.io/hosting-and-deployment/hosting-on-gitlab/#configure-gitlab-cicd).
-description: Use these variables and methods in your menu templates.
-categories: [variables and parameters]
-keywords: [menus]
-menu:
- docs:
- parent: variables
- weight: 50
-weight: 50
-aliases: [/variables/menu/]
----
-
-## Variables
-
-After [defining menu entries], access their properties in [menu templates] with these variables.
-
-.Children
-: (`menu`) A collection of child menu entries, if any, under the current menu entry.
-
-.Identifier
-: (`string`) The `identifier` property of the menu entry. If you define the menu entry [automatically], the page's `.Section`.
-
-.KeyName
-: (`string`) The `identifier` property of the menu entry, else the `name` property.
-
-.Menu
-: (`string`) The identifier of the menu that contains the menu entry.
-
-.Name
-: (`string`) The `name` property of the menu entry.
-
-- If you define the menu entry [automatically], the page's `.LinkTitle`, else the page's `.Title`.
-- If you define the menu [in front matter] or [in site configuration], falls back to the page's `.LinkTitle`, then to the page's `.Title`.
-
-.Page
-: (`page`) A reference to the page associated with the menu entry.
-
-<!-- This provides no value when rendering menu. Omitting to avoid confusion.
-.PageRef
-: (`string`) The `pageRef` property of the menu entry.
--->
-
-.Params
-: (`map`) The `params` property of the menu entry.
-
-.Parent
-: (`string`) The `parent` property of the menu entry.
-
-.Post
-: (`template.HTML`) The `post` property of the menu entry.
-
-.Pre
-: (`template.HTML`) The `pre` property of the menu entry.
-
-.Title
-: (`string`) The `title` property of the menu entry.
-
-- If you define the menu entry [automatically], the page's `.LinkTitle`, else the page's `.Title`.
-- If you define the menu [in front matter] or [in site configuration], falls back to the page's `.LinkTitle`, then to the page's `.Title`.
-
-.URL
-: (`string`) The `.RelPermalink` of the page associated with the menu entry. For menu entries pointing to external resources, the `url` property of the menu entry.
-
-.Weight
-: (`int`) The `weight` property of the menu entry.
-
-- If you define the menu entry [automatically], the page's `.Weight`.
-- If you define the menu [in front matter] or [in site configuration], falls back to the page's `.Weight`.
-
-## Methods
-
-.HasChildren
-: (`bool`) Returns `true` if `.Children` is non-nil.
-
-.IsEqual
-: (`bool`) Returns `true` if the compared menu entries represent the same menu entry.
-
-.IsSameResource
-: (`bool`) Returns `true` if the compared menu entries point to the same resource.
-
-.Page.HasMenuCurrent
-: (`bool`) Use this method to determine ancestors of the active menu entry. See [details](/functions/hasmenucurrent/).
-
-.Page.IsMenuCurrent
-: (`bool`) Use this method to determine the active menu entry. See [details](/functions/ismenucurrent/).
-description: Page-level variables are defined in a content file's front matter, derived from the content's file location, or extracted from the content body itself.
-categories: [variables and parameters]
-keywords: [pages]
+description: Use these methods with a Page object.
+categories: [variables]
+keywords: []
menu:
docs:
parent: variables
- weight: 20
-weight: 20
+ weight: 50
+weight: 50
toc: true
---
-The following is a list of page-level variables. Many of these will be defined in the front matter, derived from file location, or extracted from the content itself.
+{{% include "variables/_common/consistent-terminology.md" %}}
-## Page variables
+## All methods
-.AlternativeOutputFormats
-: Contains all alternative formats for a given page; this variable is especially useful `link rel` list in your site's `<head>`. (See [Output Formats](/templates/output-formats/).)
-: The date associated with the page. By default, this is the front matter `date` value. See [configuring dates] for a description of fallback values and precedence. See also `.ExpiryDate`, `.Lastmod`, and `.PublishDate`.
+Use these methods with your multilingual projects.
-: A boolean, `true` if the content is marked as a draft in the front matter.
+## Navigation
-.ExpiryDate
-: The date on which the content is scheduled to expire. By default, this is the front matter `expiryDate` value. See [configuring dates] for a description of fallback values and precedence. See also `.Date`, `.Lastmod`, and `.PublishDate`.
+Use these methods to create navigation links between pages.
-.File
-: Filesystem-related data for this content file. See also [File Variables].
-
-.Fragments
-: Fragments returns the fragments for this page. See [Page Fragments](#page-fragments).
-
-.FuzzyWordCount
-: The approximate number of words in the content.
-
-.IsHome
-: `true` in the context of the [homepage](/templates/homepage/).
-
-.IsNode
-: Always `false` for regular content pages.
-
-.IsPage
-: Always `true` for regular content pages.
-
-.IsSection
-: `true` if [`.Kind`](/templates/section-templates/#page-kinds) is `section`.
-
-.IsTranslated
-: `true` if there are translations to display.
-
-.Keywords
-: The meta keywords for the content.
-
-.Kind
-: The page's *kind*. Possible return values are `page`, `home`, `section`, `taxonomy`, or `term`. Note that there are also `RSS`, `sitemap`, `robotsTXT`, and `404` kinds, but these are only available during the rendering of each of these respective page's kind and therefore *not* available in any of the `Pages` collections.
-
-.Language
-: A language object that points to the language's definition in the site configuration. `.Language.Lang` gives you the language code.
-
-.Lastmod
-: The date on which the content was last modified. By default, if `enableGitInfo` is `true` in your site configuration, this is the Git author date, otherwise the front matter `lastmod` value. See [configuring dates] for a description of fallback values and precedence. See also `.Date`,`ExpiryDate`, `.PublishDate`, and [`.GitInfo`][gitinfo].
-
-.LinkTitle
-: Access when creating links to the content. If set, Hugo will use the `linktitle` from the front matter before `title`.
-
-.Next
-: Points up to the next regular page (sorted by Hugo's [default sort](/templates/lists#default-weight--date--linktitle--filepath)). Example: `{{ with .Next }}{{ .Permalink }}{{ end }}`. Calling `.Next` from the first page returns `nil`.
-
-.NextInSection
-: Points up to the next regular page below the same top level section (e.g. in `/blog`)). Pages are sorted by Hugo's [default sort](/templates/lists#default-weight--date--linktitle--filepath). Example: `{{ with .NextInSection }}{{ .Permalink }}{{ end }}`. Calling `.NextInSection` from the first page returns `nil`.
-
-.OutputFormats
-: Contains all formats, including the current format, for a given page. Can be combined the with [`.Get` function](/functions/get/) to grab a specific format. (See [Output Formats](/templates/output-formats/).)
-
-.Permalink
-: The Permanent link for this page; see [Permalinks](/content-management/urls/)
-
-.Plain
-: The Page content stripped of HTML tags and presented as a string. You may need to pipe the result through the [`htmlUnescape`](/functions/transform/htmlunescape) function when rendering this value with the HTML [output format](/templates/output-formats#output-format-definitions).
-
-.PlainWords
-: The slice of strings that results from splitting .Plain into words, as defined in Go's [strings.Fields](https://pkg.go.dev/strings#Fields).
-
-.Prev
-: Points down to the previous regular page(sorted by Hugo's [default sort](/templates/lists#default-weight--date--linktitle--filepath)). Example: `{{ if .Prev }}{{ .Prev.Permalink }}{{ end }}`. Calling `.Prev` from the last page returns `nil`.
-
-.PrevInSection
-: Points down to the previous regular page below the same top level section (e.g. `/blog`). Pages are sorted by Hugo's [default sort](/templates/lists#default-weight--date--linktitle--filepath). Example: `{{ if .PrevInSection }}{{ .PrevInSection.Permalink }}{{ end }}`. Calling `.PrevInSection` from the last page returns `nil`.
-
-.PublishDate
-: The date on which the content was or will be published. By default, this is the front matter `publishDate` value. See [configuring dates] for a description of fallback values and precedence. See also `.Date`, `.ExpiryDate`, and `.Lastmod`.
-
-.RawContent
-: Raw markdown content without the front matter. Useful with [remarkjs.com](
-https://remarkjs.com)
-
-.RenderShortcodes
-: See [Render Shortcodes](#rendershortcodes).
-
-.ReadingTime
-: The estimated time, in minutes, it takes to read the content.
-
-.Resources
-: Resources such as images and CSS that are associated with this page
-
-.Ref
-: Returns the permalink for a given reference (e.g., `.Ref "sample.md"`). `.Ref` does *not* handle in-page fragments correctly. See [Cross References](/content-management/cross-references/).
-
-.RelPermalink
-: The relative permanent link for this page.
-
-.RelRef
-: Returns the relative permalink for a given reference (e.g., `RelRef
-"sample.md"`). `.RelRef` does *not* handle in-page fragments correctly. See [Cross References](/content-management/cross-references/).
-
-.Site
-: See [Site Variables](/variables/site/).
-
-.Sites
-: Returns all sites (languages). A typical use case would be to link back to the main language: `<a href="{{ .Sites.First.Home.RelPermalink }}">...</a>`.
-
-.Sites.First
-: Returns the site for the first language. If this is not a multilingual setup, it will return itself.
-
-.Summary
-: A generated summary of the content for easily showing a snippet in a summary view. The breakpoint can be set manually by inserting <code><!--more--></code> at the appropriate place in the content page, or the summary can be written independent of the page text. See [Content Summaries](/content-management/summaries/) for more details.
-
-.TableOfContents
-: The rendered [table of contents](/content-management/toc/) for the page.
-
-.Title
-: The title for this page.
-
-.Translations
-: A list of translated versions of the current page. See [Multilingual Mode](/content-management/multilingual/) for more information.
-
-.TranslationKey
-: The key used to map language translations of the current page. See [Multilingual Mode](/content-management/multilingual/) for more information.
-
-.Truncated
-: A boolean, `true` if the `.Summary` is truncated. Useful for showing a "Read more..." link only when necessary. See [Summaries](/content-management/summaries/) for more information.
-
-.Type
-: The [content type](/content-management/types/) of the content (e.g., `posts`).
-
-.Weight
-: Assigned weight (in the front matter) to this content, used in sorting.
-List pages receive the following page collections in [context](/getting-started/glossary/#context):
-
-.Pages
-: Regular pages within the current section (not recursive), and section pages for immediate descendant sections (not recursive).
-
-.RegularPages
-: Regular pages within the current section (not recursive).
-
-.RegularPagesRecursive
-: Regular pages within the current section, and regular pages within all descendant sections.
-
-## Writable page-scoped variables
-
-[.Scratch][scratch]
-: Returns a Scratch to store and manipulate data. In contrast to the [`.Store`][store] method, this scratch is reset on server rebuilds.
-
-[.Store][store]
-: Returns a Scratch to store and manipulate data. In contrast to the [`.Scratch`][scratch] method, this scratch is not reset on server rebuilds.
-
-## Section variables and methods
-
-Also see [Sections](/content-management/sections/).
-
-.CurrentSection
-: The page's current section. The value can be the page itself if it is a section or the homepage.
-
-.FirstSection
-: The page's first section below root, e.g. `/docs`, `/blog` etc.
-
-.InSection $anotherPage
-: Whether the given page is in the current section.
-
-.IsAncestor $anotherPage
-: Whether the current page is an ancestor of the given page.
-
-.IsDescendant $anotherPage
-: Whether the current page is a descendant of the given page.
-
-.Parent
-: A section's parent section or a page's section.
-
-.Section
-: The [section](/content-management/sections/) this content belongs to. **Note:** For nested sections, this is the first path element in the directory, for example, `/blog/funny/mypost/ => blog`.
-
-.Sections
-: The [sections](/content-management/sections/) below this content.
-
-## Page fragments
-
-{{< new-in "0.111.0" >}}
-
-The `.Fragments` method returns a list of fragments for the current page.
-
-.Headings
-: A recursive list of headings for the current page. Can be used to generate a table of contents.
-
-{{< todo >}}add .Headings toc example{{< /todo >}}
-
-.Identifiers
-: A sorted list of identifiers for the current page. Can be used to check if a page contains a specific identifier or if a page contains duplicate identifiers:
-
-```go-html-template
-{{ if .Fragments.Identifiers.Contains "my-identifier" }}
- <p>Page contains identifier "my-identifier"</p>
-{{ end }}
-
-{{ if gt (.Fragments.Identifiers.Count "my-identifier") 1 }}
-: Holds a map of headings for the current page. Can be used to start the table of contents from a specific heading.
-
-Also see the [Go Doc](https://pkg.go.dev/github.com/gohugoio/hugo@v0.111.0/markup/tableofcontents#Fragments) for the return type.
-
-### Fragments in hooks and shortcodes
-
-`.Fragments` are safe to call from render hooks, even on the page you're on (`.Page.Fragments`). For shortcodes we recommend that all `.Fragments` usage is nested inside the `{{</**/>}}` shortcode delimiter (`{{%/**/%}}` takes part in the ToC creation so it's easy to end up in a situation where you bite yourself in the tail).
-
-## The `.RenderShortcodes` method {#rendershortcodes}
-
-{{< new-in "0.117.0" >}} This renders all the shortcodes in the content, preserving the surrounding markup (e.g. Markdown) as is.
-
-The common use case this is to composing a page from multiple content files while preserving a global context for table of contents and foot notes.
-
-This method is most often used in shortcode templates. A simple example of shortcode template including content from another page would look like:
-
-```go-html-template
-{{ $p := site.GetPage (.Get 0) }}
-{{ $p.RenderShortcodes }}
-```
-
-In the above it's important to understand and the difference between the two delimiters used when including a shortcode:
-
-* `{{</* myshortcode */>}}` tells Hugo that the rendered shortcode does not need further processing (e.g. it's HTML).
-* `{{%/* myshortcode */%}}` tells Hugo that the rendered shortcode needs further processing (e.g. it's Markdown).
-
-The latter is what you want to use for the include shortcode outlined above:
-
-```md
-## Mypage
-{{%/* include "mypage" */%}}
-``````
-
-
-Also see [Use Shortcodes](/content-management/shortcodes/#use-shortcodes).
-
-## Page-level params
-
-Any other value defined in the front matter in a content file, including taxonomies, will be made available as part of the `.Params` variable.
-With the above front matter, the `tags` and `categories` taxonomies are accessible via the following:
-
-* `.Params.tags`
-* `.Params.categories`
-
-The `.Params` variable is particularly useful for the introduction of user-defined front matter fields in content files. For example, a Hugo website on book reviews could have the following front matter:
-These fields would then be accessible to via `.Params.affiliatelink` and `.Params.recommendedby`.
-
-```go-html-template
-<h3><a href="{{ .Params.affiliatelink }}">Buy this book</a></h3>
-<p>It was recommended by {{ .Params.recommendedby }}.</p>
-```
-
-This template would render as follows:
-
-```html
-<h3><a href="http://www.my-book-link.here">Buy this book</a></h3>
-<p>It was recommended by my Mother.</p>
-```
-
-{{% note %}}
-See [Archetypes](/content-management/archetypes/) for consistency of `Params` across pieces of content.
-{{% /note %}}
-
-### The `.Param` method
+Range through these collections when rendering lists on [section] pages, [taxonomy] pages, [term] pages, and the home page.
-In Hugo, you can declare parameters in individual pages and globally for your entire website. A common use case is to have a general value for the site parameter and a more specific value for some of the pages (i.e., a header image):
-The `.Param` method provides a way to resolve a single value according to it's definition in a page parameter (i.e. in the content's front matter) or a site parameter (i.e., in your site configuration).
+## Parameters
-### Access nested fields in front matter
+Use these methods to access page parameters.
-When front matter contains nested fields like the following:
-description: Pages is the core page collection in Hugo and has many useful methods.
-categories: [variables and parameters]
-keywords: [pages]
+title: Pages variables
+description: Use these methods with a collection of Page objects.
+categories: [variables]
+keywords: []
menu:
docs:
parent: variables
- weight: 21
-weight: 21
-aliases: [/pages]
+ weight: 60
+weight: 60
toc: true
+aliases: [/variables/site-variables/]
---
-Also see [List templates](/templates/lists) for an overview of sort methods.
+{{% include "variables/_common/consistent-terminology.md" %}}
-## .Next PAGE
+## All methods
-`.Next` and `.Prev` on `Pages` work similar to the methods with the same names on `.Page`, but are more flexible (and slightly slower) as they can be used on any page collection.
+Use any of these methods with page collections in your templates.
-`.Next` points **up** to the next page relative to the page sent in as the argument. Example: `{{ with .Site.RegularPages.Next . }}{{ .RelPermalink }}{{ end }}`. Calling `.Next` with the first page in the collection returns `nil`.
-`.Prev` points **down** to the previous page relative to the page sent in as the argument. Example: `{{ with .Site.RegularPages.Prev . }}{{ .RelPermalink }}{{ end }}`. Calling `.Prev` with the last page in the collection returns `nil`.
-description: Shortcodes can access page variables and also have their own specific built-in variables.
-categories: [variables and parameters]
-keywords: [shortcodes]
-menu:
- docs:
- parent: variables
- weight: 20
-weight: 20
----
-
-[Shortcodes][shortcodes] have access to parameters delimited in the shortcode declaration via [`.Get`][getfunction], page- and site-level variables, and also the following shortcode-specific fields:
-
-.Name
-: Shortcode name.
-
-.Ordinal
-: Zero-based ordinal in relation to its parent. If the parent is the page itself, this ordinal will represent the position of this shortcode in the page content.
-
-.Page
-: The owning ´Page`.
-
-.Parent
-: provides access to the parent shortcode context in nested shortcodes. This can be very useful for inheritance of common shortcode parameters from the root.
-
-.Position
-: Contains [file name and position](https://godoc.org/github.com/gohugoio/hugo/common/text#Position) for the shortcode in a page. Note that this can be relatively expensive to calculate, and is meant for error reporting. See [Error Handling in Shortcodes](/templates/shortcode-templates/#error-handling-in-shortcodes).
-
-.IsNamedParams
-: boolean that returns `true` when the shortcode in question uses [named rather than positional parameters][shortcodes]
-
-.Inner
-: represents the content between the opening and closing shortcode tags when a [closing shortcode][markdownshortcode] is used
-
-.Scratch
-: returns a writable [`Scratch`][scratch] to store and manipulate data which will be attached to the shortcode context. This scratch is reset on server rebuilds.
-
-.InnerDeindent {{< new-in "0.100.0" >}}
-: Gets the `.Inner` with any indentation removed. This is what's used in the built-in `{{</* highlight */>}}` shortcode.
-description: Many, but not all, site-wide variables are defined in your site's configuration. However, Hugo provides a number of built-in variables for convenient access to global values in your templates.
-categories: [variables and parameters]
-keywords: [global,site]
+description: Use these methods with Site objects. A multilingual project will have two or more sites, one for each language.
+categories: [variables]
+keywords: []
menu:
docs:
parent: variables
- weight: 10
-weight: 10
-aliases: [/variables/site-variables/]
+ weight: 80
+weight: 80
toc: true
+aliases: [/variables/site-variables/]
---
-The following is a list of site-level (aka "global") variables. Many of these variables are defined in your site's [configuration file][config], whereas others are built into Hugo's core for convenient usage in your templates.
-
-## Get the site object from a partial
-
-All the methods below, e.g. `.Site.RegularPages` can also be reached via the global [`site`](/functions/site/) function, e.g. `site.RegularPages`, which can be handy in partials where the `Page` object isn't easily available.
-
-## Site variables
-
-.Site.AllPages
-: array of all pages, regardless of their translation.
-
-.Site.BaseURL
-: the base URL for the site as defined in the site configuration.
-
-.Site.BuildDrafts
-: a boolean (default: `false`) to indicate whether to build drafts as defined in the site configuration.
-
-.Site.Copyright
-: a string representing the copyright of your website as defined in the site configuration.
-
-.Site.Data
-: custom data, see [Data Templates](/templates/data-templates/).
-
-.Site.DisqusShortname
-: a string representing the shortname of the Disqus shortcode as defined in the site configuration.
-
-.Site.GoogleAnalytics
-: a string representing your tracking code for Google Analytics as defined in the site configuration.
-
-.Site.Home
-: reference to the homepage's [page object](/variables/page/)
-
-.Site.IsMultiLingual
-: whether there are more than one language in this site. See [Multilingual](/content-management/multilingual/) for more information.
-
-.Site.IsServer
-: a boolean to indicate if the site is being served with Hugo's built-in server. See [`hugo server`](/commands/hugo_server/) for more information.
-
-.Site.Language.Lang
-: the language code of the current locale (e.g., `en`).
-
-.Site.Language.LanguageName
-: the full language name (e.g. `English`).
-
-.Site.Language.Weight
-: the weight that defines the order in the `.Site.Languages` list.
-
-.Site.Language
-: indicates the language currently being used to render the website. This object's attributes are set in site configurations' language definition.
-
-.Site.LanguageCode
-: a string representing the language tag as defined in the site configuration.
-
-.Site.LanguagePrefix
-: this can be used to prefix URLs to point to the correct language. It will even work when there is only one defined language. See also the functions [absLangURL](/functions/urls/abslangurl) and [relLangURL](/functions/urls/rellangurl).
-
-.Site.Languages
-: an ordered list (ordered by defined weight) of languages.
+{{% include "variables/_common/consistent-terminology.md" %}}
-.Site.LastChange
-: a [time.Time](https://godoc.org/time#Time) value representing the date/time of the most recent change to your site.
+## All methods
-.Site.Menus
-: all the menus in the site.
+Use any of these methods in your templates.
-.Site.Pages
-: array of all content ordered by Date with the newest first. This array contains only the pages in the current language.
-: a shortcut to the *regular* page collection. `.Site.RegularPages` is equivalent to `where .Site.Pages "Kind" "page"`.
+## Multilingual
-.Site.Sections
-: top-level directories of the site.
+Use these methods with your multilingual projects.
-.Site.Taxonomies
-: the [taxonomies](/content-management/taxonomies/) for the entire site. Also see section [Access taxonomy data from any template](/variables/taxonomy/#access-taxonomy-data-from-any-template).
-A sitemap is a `Page` and therefore has all the [page variables][pagevars] available to use sitemap templates. They also have the following sitemap-specific variables available to them:
-In taxonomy templates you may access `.Site`, `.Page`. `.Section`, and `.File` variables, as well as the following _taxonomy_ variables:
+{{% note %}}
+Within a taxonomy or term template use the [`Data`] method to retrieve information specific to the taxonomy or term.
-.Data.Singular
-: The singular name of the taxonomy (e.g., `tags => tag`).
-
-.Data.Plural
-: The plural name of the taxonomy (e.g., `tags => tags`).
-
-.Data.Pages
-: The collection of term pages related to this taxonomy. Aliased by `.Pages`.
-
-.Data.Terms
-: A map of terms and weighted pages related to this taxonomy.
-
-.Data.Terms.Alphabetical
-: A map of terms and weighted pages related to this taxonomy, sorted alphabetically in ascending order. Reverse the sort order with`.Data.Terms.Alphabetical.Reverse`.
-
-.Data.Terms.ByCount
-: A map of terms and weighted pages related to this taxonomy, sorted by count in ascending order. Reverse the sort order with`.Data.Terms.ByCount.Reverse`.
-
-## Term templates
-
-Pages rendered by term templates have `.Kind` set to `term` and `.Type` set to the taxonomy name.
-
-In term templates you may access `.Site`, `.Page`. `.Section`, and `.File` variables, as well as the following _term_ variables:
-
-.Data.Singular
-: The singular name of the taxonomy (e.g., `tags => tag`).
-
-.Data.Plural
-: The plural name of the taxonomy (e.g., `tags => tags`).
-
-.Data.Pages
-: The collection of content pages related to this taxonomy. Aliased by `.Pages`.
-
-.Data.Term
-: The term itself (e.g., `tag-one`).
-
-## Access taxonomy data from any template
-
-Access the entire taxonomy data structure from any template with `site.Taxonomies`. This returns a map of taxonomies, terms, and a collection of weighted content pages related to each term. For example:
-
-```json
-{
- "categories": {
- "news": [
- {
- "Weight": 0,
- "Page": {
- "Title": "Post 1",
- "Date": "2022-12-18T15:13:35-08:00"
- ...
- }
- },
- {
- "Weight": 0,
- "Page": {
- "Title": "Post 2",
- "Date": "2022-12-18T15:13:46-08:00",
- ...
- }
- }
- ]
- },
- "tags": {
- "international": [
- {
- "Weight": 0,
- "Page": {
- "Title": "Post 1",
- "Date": "2021-01-01T00:00:00Z"
- ...
- }
- }
- ]
- }
-}
-```
-
-Access a subset of the taxonomy data structure by chaining one or more identifiers, or by using the [`index`] function with one or more keys. For example, to access the collection of weighted content pages related to the news category, use either of the following:
-
-[`index`]: /functions/collections/indexfunction/
-
-```go-html-template
-{{ $pages := site.Taxonomies.categories.news }}
-{{ $pages := index site.Taxonomies "categories" "news" }}
-```
-
-For example, to render the entire taxonomy data structure as a nested unordered list:
-
-```go-html-template
-<ul>
- {{ range $taxonomy, $terms := site.Taxonomies }}
-Most of the commands for **Hugo Modules** require a newer version of Go installed (see https://golang.org/dl/) and the relevant VCS client (e.g. Git, see https://git-scm.com/downloads/ ). If you have an "older" site running on Netlify, you may have to set GO_VERSION to 1.12 in your Environment settings.
-Also see [Module Mounts Config](/hugo-modules/configuration/#module-configuration-mounts) for an alternative way to configure this directory (from Hugo 0.56).
+ {{- if or (gt $majorVersionDiff $majorVersionDiffThreshold) (gt $minorVersionDiff $minorVersionDiffThreshold) }}
+ {{- if $displayExpirationWarning }}
+ {{- warnf "This call to the %q shortcode should be removed: %s. The button is now hidden because the specified version (%s) is older than the display threshold." $.Name $.Position $version }}