Namespace functions and methods

This commit is contained in:
Joe Mooring
2023-11-04 21:01:42 -07:00
committed by GitHub
parent 40212779ae
commit 723a827fdc
687 changed files with 20449 additions and 5821 deletions
+3 -2
View File
@@ -335,7 +335,7 @@
"مدونتي" "مدونتي"
], ],
"language": "en,en-US,de,fr", "language": "en,en-US,de,fr",
"allowCompoundWords": true, "allowCompoundWords": false,
"files": [ "files": [
"**/*.md" "**/*.md"
], ],
@@ -354,7 +354,8 @@
"**/node_modules/**", "**/node_modules/**",
"*.min.*", "*.min.*",
"**/news/*", "**/news/*",
"**/showcase/*" "**/showcase/*",
"**/content-management/emoji-shortcodes.md"
], ],
"useGitignore": true, "useGitignore": true,
"enabled": true "enabled": true
+168 -161
View File
@@ -1,194 +1,201 @@
Apache License Apache License
============== Version 2.0, January 2004
http://www.apache.org/licenses/
_Version 2.0, January 2004_ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution 1. Definitions.
#### 1. Definitions "License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
License” shall mean the terms and conditions for use, reproduction, and "Licensor" shall mean the copyright owner or entity authorized by
distribution as defined by Sections 1 through 9 of this document. the copyright owner that is granting the License.
“Licensor” shall mean the copyright owner or entity authorized by the copyright "Legal Entity" shall mean the union of the acting entity and all
owner that is granting the License. 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.
“Legal Entity” shall mean the union of the acting entity and all other entities "You" (or "Your") shall mean an individual or Legal Entity
that control, are controlled by, or are under common control with that entity. exercising permissions granted by this License.
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 "Source" form shall mean the preferred form for making modifications,
permissions granted by this License. including but not limited to software source code, documentation
source, and configuration files.
“Source” form shall mean the preferred form for making modifications, including "Object" form shall mean any form resulting from mechanical
but not limited to software source code, documentation source, and configuration transformation or translation of a Source form, including but
files. not limited to compiled object code, generated documentation,
and conversions to other media types.
“Object” form shall mean any form resulting from mechanical transformation or "Work" shall mean the work of authorship, whether in Source or
translation of a Source form, including but not limited to compiled object code, Object form, made available under the License, as indicated by a
generated documentation, and conversions to other media types. copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
Work shall mean the work of authorship, whether in Source or Object form, made "Derivative Works" shall mean any work, whether in Source or Object
available under the License, as indicated by a copyright notice that is included form, that is based on (or derived from) the Work and for which the
in or attached to the work (an example is provided in the Appendix below). 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.
“Derivative Works” shall mean any work, whether in Source or Object form, that "Contribution" shall mean any work of authorship, including
is based on (or derived from) the Work and for which the editorial revisions, the original version of the Work and any modifications or additions
annotations, elaborations, or other modifications represent, as a whole, an to that Work or Derivative Works thereof, that is intentionally
original work of authorship. For the purposes of this License, Derivative Works submitted to Licensor for inclusion in the Work by the copyright owner
shall not include works that remain separable from, or merely link (or bind by or by an individual or Legal Entity authorized to submit on behalf of
name) to the interfaces of, the Work and Derivative Works thereof. 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."
Contribution” shall mean any work of authorship, including the original version "Contributor" shall mean Licensor and any individual or Legal Entity
of the Work and any modifications or additions to that Work or Derivative Works on behalf of whom a Contribution has been received by Licensor and
thereof, that is intentionally submitted to Licensor for inclusion in the Work subsequently incorporated within 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 2. Grant of Copyright License. Subject to the terms and conditions of
of whom a Contribution has been received by Licensor and subsequently this License, each Contributor hereby grants to You a perpetual,
incorporated within the Work. 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.
#### 2. Grant of Copyright License 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.
Subject to the terms and conditions of this License, each Contributor hereby 4. Redistribution. You may reproduce and distribute copies of the
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, Work or Derivative Works thereof in any medium, with or without
irrevocable copyright license to reproduce, prepare Derivative Works of, modifications, and in Source or Object form, provided that You
publicly display, publicly perform, sublicense, and distribute the Work and such meet the following conditions:
Derivative Works in Source or Object form.
#### 3. Grant of Patent License (a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
Subject to the terms and conditions of this License, each Contributor hereby (b) You must cause any modified files to carry prominent notices
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, stating that You changed the files; and
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 (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
You may reproduce and distribute copies of the Work or Derivative Works thereof (d) If the Work includes a "NOTICE" text file as part of its
in any medium, with or without modifications, and in Source or Object form, distribution, then any Derivative Works that You distribute must
provided that You meet the following conditions: 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.
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of You may add Your own copyright statement to Your modifications and
this License; and may provide additional or different license terms and conditions
* **(b)** You must cause any modified files to carry prominent notices stating that You for use, reproduction, or distribution of Your modifications, or
changed the files; and for any such Derivative Works as a whole, provided Your use,
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, reproduction, and distribution of the Work otherwise complies with
all copyright, patent, trademark, and attribution notices from the Source form the conditions stated in this License.
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 5. Submission of Contributions. Unless You explicitly state otherwise,
additional or different license terms and conditions for use, reproduction, or any Contribution intentionally submitted for inclusion in the Work
distribution of Your modifications, or for any such Derivative Works as a whole, by You to the Licensor shall be under the terms and conditions of
provided Your use, reproduction, and distribution of the Work otherwise complies this License, without any additional terms or conditions.
with the conditions stated in this License. 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.
#### 5. Submission of Contributions 6. Trademarks. 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.
Unless You explicitly state otherwise, any Contribution intentionally submitted 7. Disclaimer of Warranty. Unless required by applicable law or
for inclusion in the Work by You to the Licensor shall be under the terms and agreed to in writing, Licensor provides the Work (and each
conditions of this License, without any additional terms or conditions. Contributor provides its Contributions) on an "AS IS" BASIS,
Notwithstanding the above, nothing herein shall supersede or modify the terms of WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
any separate license agreement you may have executed with Licensor regarding implied, including, without limitation, any warranties or conditions
such Contributions. 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.
#### 6. Trademarks 8. Limitation of Liability. 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.
This License does not grant permission to use the trade names, trademarks, 9. Accepting Warranty or Additional Liability. While redistributing
service marks, or product names of the Licensor, except as required for the Work or Derivative Works thereof, You may choose to offer,
reasonable and customary use in describing the origin of the Work and and charge a fee for, acceptance of support, warranty, indemnity,
reproducing the content of the NOTICE file. 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.
#### 7. Disclaimer of Warranty END OF TERMS AND CONDITIONS
Unless required by applicable law or agreed to in writing, Licensor provides the APPENDIX: How to apply the Apache License to your work.
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.
#### 8. Limitation of Liability 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.
In no event and under no legal theory, whether in tort (including negligence), Copyright [yyyy] [name of copyright owner]
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 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
While redistributing the Work or Derivative Works thereof, You may choose to http://www.apache.org/licenses/LICENSE-2.0
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.
_END OF TERMS AND CONDITIONS_ Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
### APPENDIX: How to apply the Apache License to your work WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
To apply the Apache License to your work, attach the following boilerplate limitations under the License.
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.
Copyright [yyyy] [name of copyright owner]
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
http://www.apache.org/licenses/LICENSE-2.0
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.
+3 -4
View File
@@ -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. * 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. * 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 ## 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: 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 "**" 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: To view the documentation site locally, you need to clone this repository:
```bash ```sh
git clone https://github.com/gohugoio/hugoDocs.git git clone https://github.com/gohugoio/hugoDocs.git
``` ```
@@ -45,7 +44,7 @@ Also note that the documentation version for a given version of Hugo can also be
Then to view the docs in your browser, run Hugo and open up the link: Then to view the docs in your browser, run Hugo and open up the link:
```bash ```sh
▶ hugo server ▶ hugo server
Started building sites ... Started building sites ...
+3 -6
View File
@@ -1,14 +1,11 @@
--- ---
title: {{ replace .File.ContentBaseName "-" " " | title }} title: {{ replace .File.ContentBaseName "-" " " | title }}
description: description:
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [] aliases: []
related: []
returnType: returnType:
signatures: [] signatures: []
relatedFunctions: []
--- ---
+10
View File
@@ -0,0 +1,10 @@
---
title: {{ replace .File.ContentBaseName "-" " " | title }}
description:
categories: []
keywords: []
action:
related: []
returnType:
signatures: []
---
+2 -3
View File
@@ -3,6 +3,5 @@ Add some **general info** about {{ replace .Name "-" " " | title }} here.
The site is built by: The site is built by:
* [Person 1](https://example.com) * [Person 1](https://example.org)
* [Person 1](https://example.com) * [Person 1](https://example.org)
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

+103 -93
View File
@@ -1,142 +1,152 @@
[[docs]] [[docs]]
name = "About Hugo" identifier = 'about'
weight = 10 name = 'About Hugo'
identifier = "about" pageRef = '/about/'
url = "/about/" weight = 10
[[docs]] [[docs]]
name = "Installation" name = 'Installation'
weight = 20 weight = 20
identifier = "installation" identifier = 'installation'
url = "/installation/" pageRef = '/installation/'
[[docs]] [[docs]]
name = "Getting started" name = 'Getting started'
weight = 30 weight = 30
identifier = "getting-started" identifier = 'getting-started'
url = "/getting-started/" pageRef = '/getting-started/'
[[docs]] [[docs]]
name = "Hugo Modules" name = 'Hugo Modules'
weight = 40 weight = 40
identifier = "modules" identifier = 'modules'
post = "break" post = 'break'
url = "/hugo-modules/" pageRef = '/hugo-modules/'
# Core menus
[[docs]] [[docs]]
name = "Content management" name = 'Content management'
weight = 50 weight = 50
identifier = "content-management" identifier = 'content-management'
post = "expanded" post = 'expanded'
url = "/content-management/" pageRef = '/content-management/'
[[docs]] [[docs]]
name = "Templates" name = 'Templates'
weight = 60 weight = 60
identifier = "templates" identifier = 'templates'
url = "/templates/" pageRef = '/templates/'
[[docs]] [[docs]]
name = "Functions" name = 'Functions'
weight = 70 weight = 70
identifier = "functions" identifier = 'functions'
url = "/functions/" pageRef = '/functions/'
[[docs]] [[docs]]
name = "Variables" name = 'Methods'
weight = 80 weight = 80
identifier = "variables" identifier = 'methods'
url = "/variables/" pageRef = '/methods/'
[[docs]] [[docs]]
name = "Hugo Pipes" name = 'Quick reference'
weight = 90 weight = 90
identifier = "hugo-pipes" identifier = 'quick-reference'
url = "/hugo-pipes/" pageRef = '/quick-reference/'
[[docs]] [[docs]]
name = "CLI" name = 'Variables'
weight = 100 weight = 95
post = "break" identifier = 'variables'
identifier = "commands" pageRef = '/variables/'
url = "/commands/"
[[docs]]
name = 'Hugo Pipes'
weight = 100
identifier = 'hugo-pipes'
pageRef = '/hugo-pipes/'
[[docs]]
name = 'CLI'
weight = 110
post = 'break'
identifier = 'commands'
pageRef = '/commands/'
# Low level items # Low level items
[[docs]] [[docs]]
name = "Troubleshooting" name = 'Troubleshooting'
weight = 110 weight = 120
identifier = "troubleshooting" identifier = 'troubleshooting'
url = "/troubleshooting/" pageRef = '/troubleshooting/'
[[docs]] [[docs]]
name = "Developer tools" name = 'Developer tools'
weight = 120 weight = 130
identifier = "developer-tools" identifier = 'developer-tools'
url = "/tools/" pageRef = '/tools/'
[[docs]] [[docs]]
name = "Hosting and deployment" name = 'Hosting and deployment'
weight = 130 weight = 140
identifier = "hosting-and-deployment" identifier = 'hosting-and-deployment'
url = "/hosting-and-deployment/" pageRef = '/hosting-and-deployment/'
[[docs]] [[docs]]
name = "Contribute" name = 'Contribute'
weight = 140 weight = 150
post = "break" post = 'break'
identifier = "contribute" identifier = 'contribute'
url = "/contribute/" pageRef = '/contribute/'
######## QUICKLINKS ######## QUICKLINKS
[[quicklinks]] [[quicklinks]]
name = "Fundamentals" identifier = 'fundamentals'
weight = 1 name = 'Fundamentals'
identifier = "fundamentals" pageRef = '/tags/fundamentals/'
url = "/tags/fundamentals/" weight = 1
######## GLOBAL ITEMS TO BE SHARED WITH THE HUGO SITES ######## GLOBAL ITEMS TO BE SHARED WITH THE HUGO SITES
[[global]] [[global]]
name = "News" name = 'News'
weight = 1 weight = 1
identifier = "news" identifier = 'news'
url = "/news/" pageRef = '/news/'
[[global]] [[global]]
name = "Docs" name = 'Docs'
weight = 5 weight = 5
identifier = "docs" identifier = 'docs'
url = "/documentation/" url = '/documentation/'
[[global]] [[global]]
name = "Themes" name = 'Themes'
weight = 10 weight = 10
identifier = "themes" identifier = 'themes'
url = "https://themes.gohugo.io/" url = 'https://themes.gohugo.io/'
[[global]] [[global]]
name = "Showcase" name = 'Showcase'
weight = 20 weight = 20
identifier = "showcase" identifier = 'showcase'
url = "/showcase/" pageRef = '/showcase/'
# Anything with a weight > 100 gets an external icon # Anything with a weight > 100 gets an external icon
[[global]] [[global]]
name = "Community" name = 'Community'
weight = 150 weight = 150
icon = true icon = true
identifier = "community" identifier = 'community'
post = "external" post = 'external'
url = "https://discourse.gohugo.io/" url = 'https://discourse.gohugo.io/'
[[global]] [[global]]
name = "GitHub" name = 'GitHub'
weight = 200 weight = 200
identifier = "github" identifier = 'github'
post = "external" post = 'external'
url = "https://github.com/gohugoio/hugo" url = 'https://github.com/gohugoio/hugo'
+3
View File
@@ -22,3 +22,6 @@ flex_box_interior_classes = "flex-auto w-100 w-40-l mr3 mb3 bg-white ba b--moon-
[social] [social]
twitter = "GoHugoIO" twitter = "GoHugoIO"
[render_hooks.link]
errorLevel = 'warning' # ignore (default), warning, or error (fails the build)
+4 -4
View File
@@ -29,7 +29,7 @@ toc: true
Below are all privacy settings and their default value. These settings need to be put in your site configuration (e.g. `hugo.toml`). Below are all privacy settings and their default value. These settings need to be put in your site configuration (e.g. `hugo.toml`).
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[privacy] [privacy]
[privacy.disqus] [privacy.disqus]
disable = false disable = false
@@ -58,7 +58,7 @@ privacyEnhanced = false
An example privacy configuration that disables all the relevant services in Hugo. With this configuration, the other settings will not matter. An example privacy configuration that disables all the relevant services in Hugo. With this configuration, the other settings will not matter.
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[privacy] [privacy]
[privacy.disqus] [privacy.disqus]
disable = true disable = true
@@ -98,7 +98,7 @@ simple
**Note:** If you use the _simple mode_ for Instagram and a site styled with Bootstrap 4, you may want to disable the inline styles provided by Hugo: **Note:** If you use the _simple mode_ for Instagram and a site styled with Bootstrap 4, you may want to disable the inline styles provided by Hugo:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[services] [services]
[services.instagram] [services.instagram]
disableInlineCSS = true disableInlineCSS = true
@@ -114,7 +114,7 @@ simple
**Note:** If you use the _simple mode_ for Twitter, you may want to disable the inline styles provided by Hugo: **Note:** If you use the _simple mode_ for Twitter, you may want to disable the inline styles provided by Hugo:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[services] [services]
[services.twitter] [services.twitter]
disableInlineCSS = true disableInlineCSS = true
+32 -112
View File
@@ -1,160 +1,80 @@
--- ---
title: License title: License
description: Hugo v0.15 and later are released under the Apache 2.0 license. description: Hugo is released under the Apache 2.0 license.
categories: ["about hugo"] categories: ["about hugo"]
keywords: ["License","apache"] keywords: ["license","apache"]
menu: menu:
docs: docs:
parent: about parent: about
weight: 70 weight: 70
weight: 70 weight: 70
aliases: [/meta/license]
toc: true
--- ---
{{% note %}} ## Apache License
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* _Version 2.0, January 2004_
_<http://www.apache.org/licenses/>_
## 1. Definitions ### Terms and Conditions for use, reproduction, and distribution
“License” shall mean the terms and conditions for use, reproduction, and #### 1. Definitions
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright “License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities “Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
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 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.
permissions granted by this License.
Sourceform shall mean the preferred form for making modifications, including You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
but not limited to software source code, documentation source, and configuration
files.
Object” form shall mean any form resulting from mechanical transformation or Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
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 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.
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 “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).
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 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.
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 “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.”
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
## 2. Grant of Copyright License “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.
Subject to the terms and conditions of this License, each Contributor hereby #### 2. Grant of Copyright License
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 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.
Subject to the terms and conditions of this License, each Contributor hereby #### 3. Grant of Patent License
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 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.
You may reproduce and distribute copies of the Work or Derivative Works thereof #### 4. Redistribution
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 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:
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You * **(a)** You must give any other recipients of the Work or Derivative Works a copy of this License; and
changed the files; 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, * **(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
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. * **(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. 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 #### 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. 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 #### 6. Trademarks
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. 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 #### 7. Disclaimer of Warranty
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. 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.
## 8. Limitation of Liability #### 8. Limitation of Liability
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. 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 #### 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. 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.
_END OF TERMS AND CONDITIONS_
## APPENDIX: How to apply the Apache License to your work
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.
{{< code file="apache-notice.txt" >}}
Copyright [yyyy] [name of copyright owner]
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
https://www.apache.org/licenses/LICENSE-2.0
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 >}}
@@ -0,0 +1,13 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->
@@ -1,3 +1,7 @@
---
# Do not remove front matter.
---
| Kind | Description | Example | | Kind | Description | Example |
|----------------|--------------------------------------------------------------------|-------------------------------------------------------------------------------| |----------------|--------------------------------------------------------------------|-------------------------------------------------------------------------------|
| `home` | The landing page for the home page | `/index.html` | | `home` | The landing page for the home page | `/index.html` |
@@ -5,3 +9,9 @@
| `section` | The landing page of a given section | `posts` section (`/posts/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`) | | `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`) | | `term` | The landing page for one taxonomy's term | term `awesome` in `tags` taxonomy (`/tags/awesome/index.html`) |
Four other page kinds unrelated to content are `robotsTXT`, `RSS`, `sitemap`, and `404`. Although primarily for internal use, you can specify the name when disabling one or more page kinds on your site. For example:
{{< code-toggle file=hugo >}}
disableKinds = ['robotsTXT','404']
{{< /code-toggle >}}
+13 -14
View File
@@ -19,7 +19,7 @@ A content file consists of [front matter] and markup. The markup is typically ma
The `hugo new content` command creates a new file in the `content` directory, using an archetype as a template. This is the default archetype: The `hugo new content` command creates a new file in the `content` directory, using an archetype as a template. This is the default archetype:
{{< code-toggle file="archetypes/default.md" copy=false fm=true >}} {{< code-toggle file="archetypes/default.md" fm=true >}}
title = '{{ replace .File.ContentBaseName `-` ` ` | title }}' title = '{{ replace .File.ContentBaseName `-` ` ` | title }}'
date = '{{ .Date }}' date = '{{ .Date }}'
draft = true draft = true
@@ -27,13 +27,13 @@ draft = true
When you create new content, Hugo evaluates the [template actions] within the archetype. For example: When you create new content, Hugo evaluates the [template actions] within the archetype. For example:
```text ```sh
hugo new content posts/my-first-post.md hugo new content posts/my-first-post.md
``` ```
With the default archetype shown above, Hugo creates this content file: With the default archetype shown above, Hugo creates this content file:
{{< code-toggle file="content/posts/my-first-post.md" copy=false fm=true >}} {{< code-toggle file="content/posts/my-first-post.md" fm=true >}}
title = 'My First Post' title = 'My First Post'
date = '2023-08-24T11:49:46-07:00' date = '2023-08-24T11:49:46-07:00'
draft = true draft = true
@@ -53,7 +53,7 @@ Hugo looks for archetypes in the `archetypes` directory in the root of your proj
For example, with this command: For example, with this command:
```text ```sh
hugo new content posts/my-first-post.md hugo new content posts/my-first-post.md
``` ```
@@ -75,7 +75,7 @@ Archetypes receive the following objects and values in [context]:
- `.Date` - `.Date`
- `.Type` - `.Type`
- `.Site` (see [details](/variables/site/)) - `.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. 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. For example, in a documentation site you might have a section (content type) for functions. Every page within this section should follow the same format: a brief description, the function signature, examples, and notes. We can pre-populate the page to remind content authors of the standard format.
{{< code file="archetypes/functions.md" >}}
{{< code file="archetypes/functions.md" copy=false >}}
--- ---
date: '{{ .Date }}' date: '{{ .Date }}'
draft: true draft: true
@@ -125,17 +124,17 @@ Create an archetype for galleries:
```text ```text
archetypes/ archetypes/
├── galleries/ ├── galleries/
   ├── images/ ├── images/
   │   └── .gitkeep └── .gitkeep
   └── index.md <-- same format as default.md └── index.md <-- same format as default.md
└── default.md └── default.md
``` ```
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&nbsp;`.gitkeep` file, an empty file commonly used to preserve otherwise empty directories in a Git repository. 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&nbsp;`.gitkeep` file, an empty file commonly used to preserve otherwise empty directories in a Git repository.
To create a new gallery: To create a new gallery:
```text
```sh
hugo new galleries/bryce-canyon hugo new galleries/bryce-canyon
``` ```
@@ -166,13 +165,13 @@ archetypes/
To create an article using the articles archetype: To create an article using the articles archetype:
```text ```sh
hugo new content articles/something.md hugo new content articles/something.md
``` ```
To create an article using the tutorials archetype: To create an article using the tutorials archetype:
```text ```sh
hugo new content --kind tutorials articles/something.md hugo new content --kind tutorials articles/something.md
``` ```
@@ -51,7 +51,7 @@ If set to `true` (default) the [Bundle's Resources](/content-management/page-bun
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. 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.
{{% note %}} {{% note %}}
Any page, regardless of their build options, will always be available using the [`.GetPage`](/functions/getpage) methods. Any page, regardless of their build options, will always be available using the [`.GetPage`](/methods/page/getpage) methods.
{{% /note %}} {{% /note %}}
### Illustrative use cases ### Illustrative use cases
@@ -60,14 +60,14 @@ Any page, regardless of their build options, will always be available using the
Project needs a "Who We Are" content file for front matter and body to be used by the homepage but nowhere else. Project needs a "Who We Are" content file for front matter and body to be used by the homepage but nowhere else.
{{< code-toggle file="content/who-we-are.md" fm=true copy=false >}} {{< code-toggle file="content/who-we-are.md" fm=true >}}
title: Who we are title: Who we are
_build: _build:
list: false list: false
render: false render: false
{{< /code-toggle >}} {{< /code-toggle >}}
{{< code file="layouts/index.html" copy=false >}} {{< code file="layouts/index.html" >}}
<section id="who-we-are"> <section id="who-we-are">
{{ with site.GetPage "who-we-are" }} {{ with site.GetPage "who-we-are" }}
{{ .Content }} {{ .Content }}
@@ -91,7 +91,7 @@ cascade:
list: true # default list: true # default
{{< /code-toggle >}} {{< /code-toggle >}}
{{< code file="layouts/_defaults/testimonials.html" copy=false >}} {{< code file="layouts/_defaults/testimonials.html" >}}
<section id="testimonials"> <section id="testimonials">
{{ range first 5 .Pages }} {{ range first 5 .Pages }}
<blockquote cite="{{ .Params.cite }}"> <blockquote cite="{{ .Params.cite }}">
+2 -3
View File
@@ -24,9 +24,8 @@ Hugo comes with all the code you need to load Disqus into your templates. Before
Disqus comments require you set a single value in your [site's configuration file][configuration] like so: Disqus comments require you set a single value in your [site's configuration file][configuration] like so:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[services.disqus] disqusShortname = "yourDisqusShortname"
shortname = 'your-disqus-shortname'
{{</ code-toggle >}} {{</ code-toggle >}}
For many websites, this is enough configuration. However, you also have the option to set the following in the [front matter] of a single content file: For many websites, this is enough configuration. However, you also have the option to set the following in the [front matter] of a single content file:
@@ -35,7 +35,6 @@ The `ref` and `relref` shortcodes require a single parameter: the path to a cont
The pages can be referenced as follows: The pages can be referenced as follows:
```text ```text
{{</* ref "document2" */>}} // <- From pages/document1.md, relative path {{</* ref "document2" */>}} // <- From pages/document1.md, relative path
{{</* ref "document2#anchor" */>}} {{</* ref "document2#anchor" */>}}
@@ -138,7 +137,7 @@ produces this HTML:
## Ref and RelRef Configuration ## Ref and RelRef Configuration
The behavior can, since Hugo 0.45, be configured in `hugo.toml`: The behavior can be configured in `hugo.toml`:
refLinksErrorLevel ("ERROR") 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`). : 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`).
@@ -146,7 +145,6 @@ refLinksErrorLevel ("ERROR")
refLinksNotFoundURL refLinksNotFoundURL
: URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is. : URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is.
[lists]: /templates/lists/ [lists]: /templates/lists/
[output formats]: /templates/output-formats/ [output formats]: /templates/output-formats/
[shortcode]: /content-management/shortcodes/ [shortcode]: /content-management/shortcodes/
@@ -165,7 +165,6 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
└─Fedora └─Fedora
``` ```
### Sequence diagram ### Sequence diagram
<https://arthursonzogni.com/Diagon/#Sequence> <https://arthursonzogni.com/Diagon/#Sequence>
@@ -186,7 +185,6 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
``` ```
### Flowchart ### Flowchart
<https://arthursonzogni.com/Diagon/#Flowchart> <https://arthursonzogni.com/Diagon/#Flowchart>
@@ -232,7 +230,6 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
``` ```
### Table ### Table
<https://arthursonzogni.com/Diagon/#Table> <https://arthursonzogni.com/Diagon/#Table>
+2 -3
View File
@@ -24,7 +24,7 @@ The current list of content formats in Hugo:
| Name | Markup identifiers | Comment | | 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/).| | 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/).|
|Emacs Org-Mode|org|See [go-org](https://github.com/niklasfasching/go-org).| |Emacs Org-Mode|org|See [go-org](https://github.com/niklasfasching/go-org).|
|AsciiDoc|asciidocext, adoc, ad|Needs [Asciidoctor][ascii] installed.| |AsciiDoc|asciidocext, adoc, ad|Needs [Asciidoctor][ascii] installed.|
|RST|rst|Needs [RST](https://docutils.sourceforge.io/rst.html) installed.| |RST|rst|Needs [RST](https://docutils.sourceforge.io/rst.html) installed.|
@@ -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`. 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 %}} {{% /note %}}
Some Asciidoctor parameters can be customized in Hugo. See [details]. Some Asciidoctor parameters can be customized in Hugo. See&nbsp;[details].
[details]: /getting-started/configuration-markup/#asciidoc [details]: /getting-started/configuration-markup/#asciidoc
@@ -75,7 +75,6 @@ Markdown syntax is simple enough to learn in a single sitting. The following are
[ascii]: https://asciidoctor.org/ [ascii]: https://asciidoctor.org/
[config]: /getting-started/configuration/ [config]: /getting-started/configuration/
[developer tools]: /tools/ [developer tools]: /tools/
[emojis]: https://www.webpagefx.com/tools/emoji-cheat-sheet/
[fireball]: https://daringfireball.net/projects/markdown/ [fireball]: https://daringfireball.net/projects/markdown/
[gfmtasks]: https://guides.github.com/features/mastering-markdown/#syntax [gfmtasks]: https://guides.github.com/features/mastering-markdown/#syntax
[helperssource]: https://github.com/gohugoio/hugo/blob/77c60a3440806067109347d04eb5368b65ea0fe8/helpers/general.go#L65 [helperssource]: https://github.com/gohugoio/hugo/blob/77c60a3440806067109347d04eb5368b65ea0fe8/helpers/general.go#L65
@@ -93,7 +93,7 @@ lastmod
: The datetime at which the content was last modified. : The datetime at which the content was last modified.
linkTitle 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 markup
: **experimental**; specify `"rst"` for reStructuredText (requires`rst2html`) or `"md"` (default) for Markdown. : **experimental**; specify `"rst"` for reStructuredText (requires`rst2html`) or `"md"` (default) for Markdown.
@@ -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. 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 include_toc: true
show_comments: false show_comments: false
{{</ code-toggle >}} {{</ 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. The `cascade` block can be a slice with a optional `_target` keyword, allowing for multiple `cascade` values targeting different page sets.
{{< code-toggle copy=false >}} {{< code-toggle >}}
title ="Blog" title ="Blog"
[[cascade]] [[cascade]]
background = "yosemite.jpg" background = "yosemite.jpg"
@@ -191,7 +191,7 @@ Any of the above can be omitted.
In `content/blog/_index.md` In `content/blog/_index.md`
{{< code-toggle copy=false >}} {{< code-toggle >}}
title: Blog title: Blog
cascade: cascade:
banner: images/typewriter.jpg banner: images/typewriter.jpg
@@ -219,13 +219,12 @@ It's possible to set some options for Markdown rendering in a content's front ma
[variables]: /variables/ [variables]: /variables/
[aliases]: /content-management/urls/#aliases [aliases]: /content-management/urls/#aliases
[archetype]: /content-management/archetypes/ [archetype]: /content-management/archetypes/
[bylinktitle]: /templates/lists/#by-link-title
[config]: /getting-started/configuration/ [config]: /getting-started/configuration/
[content type]: /content-management/types/ [content type]: /content-management/types/
[contentorg]: /content-management/organization/ [contentorg]: /content-management/organization/
[headless-bundle]: /content-management/page-bundles/#headless-bundle [headless-bundle]: /content-management/page-bundles/#headless-bundle
[json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf [json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
[lists]: /templates/lists/#order-content [lists]: /templates/lists/#sort-content
[lookup]: /templates/lookup-order/ [lookup]: /templates/lookup-order/
[ordering]: /templates/lists/ [ordering]: /templates/lists/
[outputs]: /templates/output-formats/ [outputs]: /templates/output-formats/
@@ -10,6 +10,7 @@ menu:
toc: true toc: true
weight: 90 weight: 90
--- ---
## Image resources ## Image resources
To process an image you must access the file as a page resource, global resource, or remote resource. To process an image you must access the file as a page resource, global resource, or remote resource.
@@ -50,7 +51,7 @@ To access an image as a global resource:
### Remote resource ### Remote resource
A remote resource is a file on a remote server, accessible via http or https. To access an image as a remote resource: A remote resource is a file on a remote server, accessible via HTTP or HTTPS. To access an image as a remote resource:
```go-html-template ```go-html-template
{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }} {{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}
@@ -112,7 +113,7 @@ Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. U
{{< new-in "0.119.0" >}} {{< new-in "0.119.0" >}}
{{% note %}} {{% 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 %}} {{% /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`]. 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`].
@@ -139,10 +140,9 @@ Some more examples:
{{ $image := $image.Process "fill 600x400" }} {{ $image := $image.Process "fill 600x400" }}
``` ```
### Resize ### Resize
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. If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio.
@@ -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. 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 ### EXIF
Provides an [EXIF] object containing image metadata. 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 ## 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 ### Dimensions
@@ -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. 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]. 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)_ _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)_
{{< imgproc sunset Resize "300x" />}} {{< imgproc "sunset.jpg" "resize 300x" />}}
{{< imgproc sunset Fill "90x120 left" />}} {{< imgproc "sunset.jpg" "fill 90x120 left" />}}
{{< imgproc sunset Fill "90x120 right" />}} {{< imgproc "sunset.jpg" "fill 90x120 right" />}}
{{< imgproc sunset Fit "90x90" />}} {{< imgproc "sunset.jpg" "fit 90x90" />}}
{{< imgproc sunset Crop "250x250 center" />}} {{< imgproc "sunset.jpg" "crop 250x250 center" />}}
{{< imgproc sunset Resize "300x q10" />}} {{< imgproc "sunset.jpg" "resize 300x q10" />}}
This is the shortcode used to generate the examples above: This is the shortcode used to generate the examples above:
{{< code file="layouts/shortcodes/imgproc.html" >}} {{< readfile file="layouts/shortcodes/imgproc.html" highlight="go-html-template" >}}
{{< readfile file="layouts/shortcodes/imgproc.html" >}}
{{< /code >}}
Call the shortcode from your Markdown like this: Call the shortcode from your Markdown like this:
```go-html-template ```go-html-template
{{</* imgproc sunset Resize "300x" /*/>}} {{</* imgproc "sunset.jpg" "resize 300x" /*/>}}
``` ```
{{% note %}} {{% note %}}
@@ -457,7 +454,7 @@ resampleFilter
Define an `imaging.exif` section in your site configuration to control the availability of EXIF data. Define an `imaging.exif` section in your site configuration to control the availability of EXIF data.
{{< code-toggle file="hugo" copy=true >}} {{< code-toggle file=hugo >}}
[imaging.exif] [imaging.exif]
includeFields = "" includeFields = ""
excludeFields = "" excludeFields = ""
@@ -487,9 +484,9 @@ By default, Hugo uses the [Smartcrop] library when cropping images with the `Cro
Examples using the sunset image from above: Examples using the sunset image from above:
{{< imgproc sunset Fill "200x200 smart" />}} {{< imgproc "sunset.jpg" "fill 200x200 smart" />}}
{{< imgproc sunset Crop "200x200 smart" />}} {{< imgproc "sunset.jpg" "crop 200x200 smart" />}}
## Image processing performance consideration ## Image processing performance consideration
@@ -497,7 +494,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: 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:
```bash ```sh
hugo --gc hugo --gc
``` ```
+7 -8
View File
@@ -36,7 +36,7 @@ Although you can use these methods in combination when defining a menu, the menu
To automatically define menu entries for each top-level section of your site, enable the section pages menu in your site configuration. To automatically define menu entries for each top-level section of your site, enable the section pages menu in your site configuration.
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
sectionPagesMenu = "main" sectionPagesMenu = "main"
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -46,7 +46,7 @@ This creates a menu structure that you can access with `site.Menus.main` in your
To add a page to the "main" menu: To add a page to the "main" menu:
{{< code-toggle file="content/about.md" copy=false fm=true >}} {{< code-toggle file="content/about.md" fm=true >}}
title = 'About' title = 'About'
menu = 'main' menu = 'main'
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -55,7 +55,7 @@ Access the entry with `site.Menus.main` in your templates. See [menu templates]
To add a page to the "main" and "footer" menus: To add a page to the "main" and "footer" menus:
{{< code-toggle file="content/contact.md" copy=false fm=true >}} {{< code-toggle file="content/contact.md" fm=true >}}
title = 'Contact' title = 'Contact'
menu = ['main','footer'] menu = ['main','footer']
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -94,7 +94,7 @@ weight
This front matter menu entry demonstrates some of the available properties: This front matter menu entry demonstrates some of the available properties:
{{< code-toggle file="content/products/software.md" copy=false fm=true >}} {{< code-toggle file="content/products/software.md" fm=true >}}
title = 'Software' title = 'Software'
[menu.main] [menu.main]
parent = 'Products' parent = 'Products'
@@ -106,12 +106,11 @@ class = 'center'
Access the entry with `site.Menus.main` in your templates. See [menu templates] for details. Access the entry with `site.Menus.main` in your templates. See [menu templates] for details.
## Define in site configuration ## Define in site configuration
To define entries for the "main" menu: To define entries for the "main" menu:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[[menu.main]] [[menu.main]]
name = 'Home' name = 'Home'
pageRef = '/' pageRef = '/'
@@ -132,7 +131,7 @@ This creates a menu structure that you can access with `site.Menus.main` in your
To define entries for the "footer" menu: To define entries for the "footer" menu:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[[menu.footer]] [[menu.footer]]
name = 'Terms' name = 'Terms'
pageRef = '/terms' pageRef = '/terms'
@@ -177,7 +176,7 @@ url
This nested menu demonstrates some of the available properties: This nested menu demonstrates some of the available properties:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[[menu.main]] [[menu.main]]
name = 'Products' name = 'Products'
pageRef = '/products' pageRef = '/products'
+20 -21
View File
@@ -25,7 +25,7 @@ This is the default language configuration:
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. This is an example of a site configuration for a multilingual project. Any key not defined in a `languages` object will fall back to the global value in the root of your site configuration.
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
defaultContentLanguage = 'de' defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true defaultContentLanguageInSubdir = true
@@ -104,7 +104,7 @@ In Hugo `v0.112.0` we consolidated all configuration options, and improved how t
1. `site.Language.Params` is deprecated. Use `site.Params` directly. 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. 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" title = "My blog"
languageCode = "en-us" 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: To disable a language within a `languages` object in your site configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[languages.es] [languages.es]
disabled = true disabled = true
{{< /code-toggle >}} {{< /code-toggle >}}
To disable one or more languages in the root of your site configuration: 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"] disableLanguages = ["es", "fr"]
{{< /code-toggle >}} {{< /code-toggle >}}
To disable one or more languages using an environment variable: To disable one or more languages using an environment variable:
```bash ```sh
HUGO_DISABLELANGUAGES="es fr" hugo HUGO_DISABLELANGUAGES="es fr" hugo
``` ```
@@ -160,7 +160,7 @@ If a `baseURL` is set on the `language` level, then all languages must have one
Example: Example:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[languages] [languages]
[languages.fr] [languages.fr]
baseURL = "https://example.fr" baseURL = "https://example.fr"
@@ -169,7 +169,7 @@ weight = 1
title = "En Français" title = "En Français"
[languages.en] [languages.en]
baseURL = "https://example.com" baseURL = "https://example.org/"
languageName = "English" languageName = "English"
weight = 2 weight = 2
title = "In English" title = "In English"
@@ -183,7 +183,7 @@ public
└── fr └── fr
``` ```
**All URLs (i.e `.Permalink` etc.) will be generated from that root. So the English home page above will have its `.Permalink` set to `https://example.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: When you run `hugo server` we will start multiple HTTP servers. You will typically see something like this in the console:
@@ -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. This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` parameter.
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
languages: languages:
en: en:
weight: 10 weight: 10
@@ -277,7 +277,7 @@ To localize URLs:
For example, a French translation can have its own localized slug. For example, a French translation can have its own localized slug.
{{< code-toggle file="content/about.fr.md" fm=true copy=false >}} {{< code-toggle file="content/about.fr.md" fm=true >}}
title: A Propos title: A Propos
slug: "a-propos" slug: "a-propos"
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -427,7 +427,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. 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' defaultContentLanguage = 'en'
[languages] [languages]
@@ -530,7 +530,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 [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 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 ### Create language-specific menu entries
@@ -538,7 +538,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: For a simple menu with a small number of entries, use a single configuration file. For example:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[languages.de] [languages.de]
languageCode = 'de-DE' languageCode = 'de-DE'
languageName = 'Deutsch' languageName = 'Deutsch'
@@ -583,7 +583,7 @@ config/
└── hugo.toml └── hugo.toml
``` ```
{{< code-toggle file="config/_default/menus/menu.de" copy=false >}} {{< code-toggle file="config/_default/menus/menu.de" >}}
[[main]] [[main]]
name = 'Produkte' name = 'Produkte'
pageRef = '/products' pageRef = '/products'
@@ -594,7 +594,7 @@ pageRef = '/services'
weight = 20 weight = 20
{{< /code-toggle >}} {{< /code-toggle >}}
{{< code-toggle file="config/_default/menus/menu.en" copy=false >}} {{< code-toggle file="config/_default/menus/menu.en" >}}
[[main]] [[main]]
name = 'Products' name = 'Products'
pageRef = '/products' pageRef = '/products'
@@ -624,7 +624,7 @@ The `identifier` depends on how you define menu entries:
For example, if you define menu entries in site configuration: For example, if you define menu entries in site configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[[menu.main]] [[menu.main]]
identifier = 'products' identifier = 'products'
name = 'Products' name = 'Products'
@@ -639,7 +639,7 @@ For example, if you define menu entries in site configuration:
Create corresponding entries in the translation tables: Create corresponding entries in the translation tables:
{{< code-toggle file="i18n/de" copy=false >}} {{< code-toggle file="i18n/de" >}}
products = 'Produkte' products = 'Produkte'
services = 'Leistungen' services = 'Leistungen'
{{< / code-toggle >}} {{< / code-toggle >}}
@@ -663,7 +663,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: To track down missing translation strings, run Hugo with the `--printI18nWarnings` flag:
```bash ```sh
hugo --printI18nWarnings | grep i18n hugo --printI18nWarnings | grep i18n
i18n|MISSING_TRANSLATION|en|wordCount i18n|MISSING_TRANSLATION|en|wordCount
``` ```
@@ -677,19 +677,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). 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` ## Generate multilingual content with `hugo new content`
If you organize content with translations in the same directory: If you organize content with translations in the same directory:
```text ```sh
hugo new content post/test.en.md hugo new content post/test.en.md
hugo new content post/test.de.md hugo new content post/test.de.md
``` ```
If you organize content with translations in different directories: If you organize content with translations in different directories:
```text ```sh
hugo new content content/en/post/test.md hugo new content content/en/post/test.md
hugo new content content/de/post/test.md hugo new content content/de/post/test.md
``` ```
@@ -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. 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.
{{< imgproc 1-featured Resize "300x" >}} {{< imgproc "1-featured-content-bundles.png" "resize 300x" >}}
The illustration shows three bundles. Note that the home page bundle cannot contain other content pages, although other files (images etc.) are allowed. The illustration shows three bundles. Note that the home page bundle cannot contain other content pages, although other files (images etc.) are allowed.
{{< /imgproc >}} {{< /imgproc >}}
{{% note %}} {{% note %}}
The bundle documentation is a **work in progress**. We will publish more comprehensive docs about this soon. The bundle documentation is a **work in progress**. We will publish more comprehensive docs about this soon.
{{% /note %}} {{% /note %}}
## Organization of content source ## Organization of content source
In Hugo, your content should be organized in a manner that reflects the rendered website. 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:
. .
└── content └── content
└── about └── about
| └── index.md // <- https://example.com/about/ | └── index.md // <- https://example.org/about/
├── posts ├── posts
| ├── firstpost.md // <- https://example.com/posts/firstpost/ | ├── firstpost.md // <- https://example.org/posts/firstpost/
| ├── happy | ├── happy
| | └── ness.md // <- https://example.com/posts/happy/ness/ | | └── ness.md // <- https://example.org/posts/happy/ness/
| └── secondpost.md // <- https://example.com/posts/secondpost/ | └── secondpost.md // <- https://example.org/posts/secondpost/
└── quote └── quote
├── first.md // <- https://example.com/quote/first/ ├── first.md // <- https://example.org/quote/first/
└── second.md // <- https://example.com/quote/second/ └── second.md // <- https://example.org/quote/second/
``` ```
## Path breakdown in Hugo ## Path breakdown in Hugo
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].
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].
### Index pages: `_index.md` ### 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]. `_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 %}} {{% 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 %}} {{% /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: 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 ```txt
. url . url
. ⊢--^-⊣ . ⊢--^-⊣
@@ -88,17 +84,15 @@ At build, this will output to the following destination with the associated valu
⊢--------^---------⊣⊢-^-⊣ ⊢--------^---------⊣⊢-^-⊣
permalink 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`). 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 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`: 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 ```txt
path ("posts/my-first-hugo-post.md") 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
⊢--------^--------⊣⊢-^--⊣⊢-------^---------⊣ ⊢--------^--------⊣⊢-^--⊣⊢-------^---------⊣
permalink permalink
⊢--------------------^---------------------⊣ ⊢--------------------^---------------------⊣
https://example.com/posts/my-first-hugo-post/index.html https://example.org/posts/my-first-hugo-post/index.html
``` ```
## Paths explained ## Paths explained
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. 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
[config]: /getting-started/configuration/ [config]: /getting-started/configuration/
[formats]: /content-management/formats/ [formats]: /content-management/formats/
[front matter]: /content-management/front-matter/ [front matter]: /content-management/front-matter/
[getpage]: /functions/getpage/ [getpage]: /methods/page/getpage
[homepage template]: /templates/homepage/ [homepage template]: /templates/homepage/
[homepage]: /templates/homepage/ [homepage]: /templates/homepage/
[lists]: /templates/lists/ [lists]: /templates/lists/
+10 -12
View File
@@ -48,14 +48,14 @@ content/
│ │ ├── image2.png │ │ ├── image2.png
│ │ └── index.md │ │ └── index.md
│ └── my-other-post │ └── my-other-post
   └── index.md └── index.md
└── another-section └── another-section
├── .. ├── ..
   └── not-a-leaf-bundle └── not-a-leaf-bundle
├── .. ├── ..
   └── another-leaf-bundle └── another-leaf-bundle
   └── index.md └── index.md
``` ```
In the above example `content/` directory, there are four leaf In the above example `content/` directory, there are four leaf
@@ -90,7 +90,6 @@ The hierarchy depth at which a leaf bundle is created does not matter,
as long as it is not inside another **leaf** bundle. as long as it is not inside another **leaf** bundle.
{{% /note %}} {{% /note %}}
### Headless bundle ### Headless bundle
A headless bundle is a bundle that is configured to not get published A headless bundle is a bundle that is configured to not get published
@@ -128,7 +127,7 @@ Explanation of the above example:
A leaf bundle can be made headless by adding below in the front matter A leaf bundle can be made headless by adding below in the front matter
(in the `index.md`): (in the `index.md`):
{{< code-toggle file="content/headless/index.md" fm=true copy=false >}} {{< code-toggle file="content/headless/index.md" fm=true >}}
headless = true headless = true
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -149,17 +148,16 @@ Here `md` (markdown) is used just as an example. You can use any file
type as a content resource as long as it is a content type recognized by Hugo. type as a content resource as long as it is a content type recognized by Hugo.
{{% /note %}} {{% /note %}}
### Examples of branch bundle organization ### Examples of branch bundle organization
```text ```text
content/ content/
├── branch-bundle-1 ├── branch-bundle-1
   ├── branch-content1.md ├── branch-content1.md
   ├── branch-content2.md ├── branch-content2.md
   ├── image1.jpg ├── image1.jpg
   ├── image2.png ├── image2.png
   └── _index.md └── _index.md
└── branch-bundle-2 └── branch-bundle-2
├── _index.md ├── _index.md
└── a-leaf-bundle └── a-leaf-bundle
@@ -112,7 +112,6 @@ GetMatch
.Resources.Match "*" 🚫 .Resources.Match "*" 🚫
.Resources.Match "sunset.jpg" 🚫 .Resources.Match "sunset.jpg" 🚫
.Resources.Match "*sunset.jpg" 🚫 .Resources.Match "*sunset.jpg" 🚫
``` ```
## Page resources metadata ## Page resources metadata
@@ -138,7 +137,7 @@ params
### Resources metadata example ### Resources metadata example
{{< code-toggle copy=false >}} {{< code-toggle >}}
title: Application title: Application
date : 2018-01-25 date : 2018-01-25
resources : resources :
@@ -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: 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:
{{< code-toggle copy=false >}} {{< code-toggle file="content/inspections/engine/index.md" fm=true >}}
title = 'Engine inspections'
[[resources]] [[resources]]
src = "*specs.pdf" src = "*specs.pdf"
title = "Specification #:counter" title = "Specification #:counter"
+10 -8
View File
@@ -33,16 +33,19 @@ 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: The `Related` method takes one argument which may be a `Page` or a options map. The options map have these options:
indices indices
: The indices to search in. : (`slice`) The indices to search within.
document 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 namedSlices
: The keywords to search for. : (`slice`) The keywords to search for, expressed as a slice of `KeyValues` using the [`keyVals`] function.
fragments 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: A fictional example using all of the above options:
@@ -57,7 +60,7 @@ A fictional example using all of the above options:
``` ```
{{% note %}} {{% 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 %}} {{% /note %}}
## Index content headings in related content ## Index content headings in related content
@@ -66,7 +69,7 @@ We improved and simplified this feature in Hugo 0.111.0. Before this we had 3 di
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: Hugo can index the headings in your content and use this to find related content. You can enable this by adding a index of type `fragments` to your `related` configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[related] [related]
threshold = 20 threshold = 20
includeNewer = true includeNewer = true
@@ -74,7 +77,7 @@ toLower = false
[[related.indices]] [[related.indices]]
name = "fragmentrefs" name = "fragmentrefs"
type = "fragments" type = "fragments"
applyFilter = false applyFilter = true
weight = 80 weight = 80
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -146,7 +149,6 @@ applyFilter
weight 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. : 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) 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. : {{< 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.
+31 -33
View File
@@ -26,35 +26,35 @@ A typical site consists of one or more sections. For example:
```text ```text
content/ content/
├── articles/ <-- section (top-level directory) ├── articles/ <-- section (top-level directory)
   ├── 2022/ ├── 2022/
   │   ├── article-1/ ├── article-1/
   │   │   ├── cover.jpg │ │ ├── cover.jpg
   │   │   └── index.md │ │ └── index.md
   │   └── article-2.md └── article-2.md
   └── 2023/ └── 2023/
   ├── article-3.md ├── article-3.md
   └── article-4.md └── article-4.md
├── products/ <-- section (top-level directory) ├── products/ <-- section (top-level directory)
   ├── product-1/ <-- section (has _index.md file) ├── product-1/ <-- section (has _index.md file)
   │   ├── benefits/ <-- section (has _index.md file) ├── benefits/ <-- section (has _index.md file)
   │   │   ├── _index.md │ │ ├── _index.md
   │   │   ├── benefit-1.md │ │ ├── benefit-1.md
   │   │   └── benefit-2.md │ │ └── benefit-2.md
   │   ├── features/ <-- section (has _index.md file) ├── features/ <-- section (has _index.md file)
   │   │   ├── _index.md │ │ ├── _index.md
   │   │   ├── feature-1.md │ │ ├── feature-1.md
   │   │   └── feature-2.md │ │ └── feature-2.md
   │   └── _index.md └── _index.md
   └── product-2/ <-- section (has _index.md file) └── product-2/ <-- section (has _index.md file)
   ├── benefits/ <-- section (has _index.md file) ├── benefits/ <-- section (has _index.md file)
     ├── _index.md ├── _index.md
     ├── benefit-1.md ├── benefit-1.md
     └── benefit-2.md └── benefit-2.md
   ├── features/ <-- section (has _index.md file) ├── features/ <-- section (has _index.md file)
     ├── _index.md ├── _index.md
     ├── feature-1.md ├── feature-1.md
     └── feature-2.md └── feature-2.md
   └── _index.md └── _index.md
├── _index.md ├── _index.md
└── about.md └── about.md
``` ```
@@ -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 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&nbsp;[details](/variables/page/#page-collections).
1. All directories in the products section have list pages; each directory is a section. 1. All directories in the products section have list pages; each directory is a section.
@@ -108,7 +108,6 @@ If you need to use a different template for a subsection, specify `type` and/or
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 ```text
content/products/product-1/benefits/benefit-1.md content/products/product-1/benefits/benefit-1.md
``` ```
@@ -122,11 +121,11 @@ For example, use the `.Ancestors` method to render breadcrumb navigation.
<ol> <ol>
{{ range .Ancestors.Reverse }} {{ range .Ancestors.Reverse }}
<li> <li>
<a href="{{ .Permalink }}">{{ .LinkTitle }}</a> <a href="{{ .Permalink }}">{{ .Title }}</a>
</li> </li>
{{ end }} {{ end }}
<li class="active"> <li class="active">
<a aria-current="page" href="{{ .Permalink }}">{{ .LinkTitle }}</a> <a aria-current="page" href="{{ .Permalink }}">{{ .Title }}</a>
</li> </li>
</ol> </ol>
</nav> </nav>
@@ -154,7 +153,6 @@ Hugo renders this, where each breadcrumb is a link to the corresponding page:
Home » Products » Product 1 » Benefits » Benefit 1 Home » Products » Product 1 » Benefits » Benefit 1
``` ```
[archetype]: /content-management/archetypes/ [archetype]: /content-management/archetypes/
[content type]: /content-management/types/ [content type]: /content-management/types/
[directory structure]: /getting-started/directory-structure/ [directory structure]: /getting-started/directory-structure/
+10 -12
View File
@@ -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 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 ### Shortcodes without markdown
The `<` character indicates that the shortcode's inner content does *not* need further rendering. Often shortcodes without Markdown include internal HTML: The `<` character indicates that the shortcode's inner content does *not* need further rendering. Often shortcodes without Markdown include internal HTML:
@@ -172,7 +171,7 @@ To display a highlighted code sample:
```text ```text
{{</* highlight go-html-template */>}} {{</* highlight go-html-template */>}}
{{ range .Pages }} {{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
{{</* /highlight */>}} {{</* /highlight */>}}
``` ```
@@ -181,7 +180,7 @@ Rendered:
{{< highlight go-html-template >}} {{< highlight go-html-template >}}
{{ range .Pages }} {{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
{{< /highlight >}} {{< /highlight >}}
@@ -192,7 +191,7 @@ To specify one or more [highlighting options], include a quotation-encapsulated,
```text ```text
{{</* highlight go-html-template "lineNos=inline, lineNoStart=42" */>}} {{</* highlight go-html-template "lineNos=inline, lineNoStart=42" */>}}
{{ range .Pages }} {{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
{{</* /highlight */>}} {{</* /highlight */>}}
``` ```
@@ -201,7 +200,7 @@ Rendered:
{{< highlight go-html-template "lineNos=inline, lineNoStart=42" >}} {{< highlight go-html-template "lineNos=inline, lineNoStart=42" >}}
{{ range .Pages }} {{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
{{< /highlight >}} {{< /highlight >}}
@@ -220,14 +219,14 @@ You must obtain an Access Token to use the `instagram` shortcode.
If your site configuration is private: If your site configuration is private:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[services.instagram] [services.instagram]
accessToken = 'xxx' accessToken = 'xxx'
{{< /code-toggle >}} {{< /code-toggle >}}
If your site configuration is _not_ private, set the Access Token with an environment variable: If your site configuration is _not_ private, set the Access Token with an environment variable:
```text ```sh
HUGO_SERVICES_INSTAGRAM_ACCESSTOKEN=xxx hugo --gc --minify HUGO_SERVICES_INSTAGRAM_ACCESSTOKEN=xxx hugo --gc --minify
``` ```
@@ -251,7 +250,7 @@ Include this in your markdown:
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. 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 */>}} {{</* 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: To access deeply nested parameters, use "dot syntax", e.g:
```bash ```sh
{{</* param "my.nested.param" */>}} {{</* 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. Assuming that standard Hugo pretty URLs are turned on.
```html ```html
<a href="https://example.com/blog/neat">Neat</a> <a href="https://example.org/blog/neat">Neat</a>
<a href="/about/#who">Who</a> <a href="/about/#who">Who</a>
``` ```
@@ -355,7 +354,6 @@ Copy the YouTube video ID that follows `v=` in the video's URL and pass it to th
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`: 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`:
{{< code file="example-youtube-input-with-autoplay.md" >}} {{< code file="example-youtube-input-with-autoplay.md" >}}
{{</* youtube id="w7Ft2ymGmfc" autoplay="true" */>}} {{</* youtube id="w7Ft2ymGmfc" autoplay="true" */>}}
{{< /code >}} {{< /code >}}
@@ -398,7 +396,7 @@ To learn more about creating custom shortcodes, see the [shortcode template docu
[partials]: /templates/partials/ [partials]: /templates/partials/
[quickstart]: /getting-started/quick-start/ [quickstart]: /getting-started/quick-start/
[sctemps]: /templates/shortcode-templates/ [sctemps]: /templates/shortcode-templates/
[scvars]: /variables/shortcodes/ [scvars]: /variables/shortcode/
[shortcode template documentation]: /templates/shortcode-templates/ [shortcode template documentation]: /templates/shortcode-templates/
[templatessection]: /templates/ [templatessection]: /templates/
[Vimeo]: https://vimeo.com/ [Vimeo]: https://vimeo.com/
@@ -27,13 +27,13 @@ This union filesystem will be served from your site root. So a file
Here's an example of setting `staticDir` and `staticDir2` for a Here's an example of setting `staticDir` and `staticDir2` for a
multi-language site: multi-language site:
{{< code-toggle copy=false file="hugo" >}} {{< code-toggle file=hugo >}}
staticDir = ["static1", "static2"] staticDir = ["static1", "static2"]
[languages] [languages]
[languages.en] [languages.en]
staticDir2 = "static_en" staticDir2 = "static_en"
baseURL = "https://example.com" baseURL = "https://example.org/"
languageName = "English" languageName = "English"
weight = 2 weight = 2
title = "In English" title = "In English"
+2 -2
View File
@@ -53,7 +53,7 @@ Pros
Cons Cons
: Extra work for content authors, since they need to remember to type <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</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 <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</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/).
{{% warning "Be Precise with the Summary Divider" %}} {{% note %}}
Be careful to enter <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> exactly; i.e., all lowercase and with no whitespace. Be careful to enter <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> exactly; i.e., all lowercase and with no whitespace.
{{% /note %}} {{% /note %}}
@@ -75,7 +75,7 @@ Because there are multiple ways in which a summary can be specified it is useful
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 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 3. The text at the start of the article will be provided as per the automatic summary split method
{{% warning "Competing selections" %}} {{% 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 <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider Hugo will use the manual summary split method. 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>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider Hugo will use the manual summary split method.
{{% /note %}} {{% /note %}}
@@ -24,7 +24,7 @@ If you run with `markup.highlight.noClasses=false` in your site configuration, y
You can generate one with Hugo: You can generate one with Hugo:
```bash ```sh
hugo gen chromastyles --style=monokai > syntax.css hugo gen chromastyles --style=monokai > syntax.css
``` ```
@@ -104,7 +104,6 @@ Highlighting in code fences is enabled by default.
``` ```
```` ````
Gives this: Gives this:
```go {linenos=table,hl_lines=[8,"15-17"],linenostart=199} ```go {linenos=table,hl_lines=[8,"15-17"],linenostart=199}
+7 -20
View File
@@ -27,7 +27,6 @@ Term
Value Value
: a piece of content assigned to a term : a piece of content assigned to a term
## Example taxonomy: movie website ## Example taxonomy: movie website
Let's assume you are making a website about movies. You may want to include the following taxonomies: Let's assume you are making a website about movies. You may want to include the following taxonomies:
@@ -86,11 +85,11 @@ Without adding a single line to your [site configuration] file, Hugo will automa
If you do not want Hugo to create any taxonomies, set `disableKinds` in your [site configuration] to the following: 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"] disableKinds = ["taxonomy","term"]
{{</ code-toggle >}} {{</ code-toggle >}}
{{% page-kinds %}} {{% include "content-management/_common/page-kinds.md" %}}
### Default destinations ### 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_. While adding custom taxonomies, you need to put in the default taxonomies too, _if you want to keep them_.
{{% /note %}} {{% /note %}}
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[taxonomies] [taxonomies]
tag = "tags" tag = "tags"
category = "categories" 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]. 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] [taxonomies]
tag = "tags" tag = "tags"
{{</ code-toggle >}} {{</ code-toggle >}}
@@ -129,14 +128,6 @@ If you want to disable all taxonomies altogether, see the use of `disableKinds`
{{% note %}} {{% 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. 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 %}} {{% /note %}}
## Add taxonomies to content ## Add taxonomies to content
@@ -151,7 +142,7 @@ If you would like the ability to quickly generate content files with preconfigur
### Example: front matter with taxonomies ### Example: front matter with taxonomies
{{< code-toggle file="content/example.md" fm=true copy=false >}} {{< code-toggle file="content/example.md" fm=true >}}
title = "Hugo: A fast and flexible static site generator" title = "Hugo: A fast and flexible static site generator"
tags = [ "Development", "Go", "fast", "Blogging" ] tags = [ "Development", "Go", "fast", "Blogging" ]
categories = [ "Development" ] categories = [ "Development" ]
@@ -168,7 +159,7 @@ The following show a piece of content that has a weight of 22, which can be used
### Example: taxonomic `weight` ### Example: taxonomic `weight`
{{< code-toggle copy=false >}} {{< code-toggle >}}
title = "foo" title = "foo"
tags = [ "a", "b", "c" ] tags = [ "a", "b", "c" ]
tags_weight = 22 tags_weight = 22
@@ -178,15 +169,11 @@ categories_weight = 44
By using taxonomic weight, the same piece of content can appear in different positions in different taxonomies. 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 ## 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: 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:
{{< code-toggle file="content/actors/bruce-willis/_index.md" fm=true copy=false >}} {{< code-toggle file="content/actors/bruce-willis/_index.md" fm=true >}}
title: "Bruce Willis" title: "Bruce Willis"
wikipedia: "https://en.wikipedia.org/wiki/Bruce_Willis" wikipedia: "https://en.wikipedia.org/wiki/Bruce_Willis"
{{< /code-toggle >}} {{< /code-toggle >}}
+3 -2
View File
@@ -37,7 +37,7 @@ He lay on his armour-like back, and if he lifted his head a little he could see
### My Subheading ### 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`. 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`.
@@ -105,8 +105,9 @@ He lay on his armour-like back, and if he lifted his head a little he could see
=== My Subheading === 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. 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.
[conditionals]: /templates/introduction/#conditionals [conditionals]: /templates/introduction/#conditionals
+17 -17
View File
@@ -28,7 +28,7 @@ You can change the structure and appearance of URLs with front matter values and
Set the `slug` in front matter to override the last segment of the path. The `slug` value does not affect section pages. Set the `slug` in front matter to override the last segment of the path. The `slug` value does not affect section pages.
{{< code-toggle file="content/posts/post-1.md" copy=false fm=true >}} {{< code-toggle file="content/posts/post-1.md" fm=true >}}
title = 'My First Post' title = 'My First Post'
slug = 'my-first-post' slug = 'my-first-post'
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -45,7 +45,7 @@ Set the `url` in front matter to override the entire path. Use this with either
With this front matter: With this front matter:
{{< code-toggle file="content/posts/post-1.md" copy=false fm=true >}} {{< code-toggle file="content/posts/post-1.md" fm=true >}}
title = 'My First Article' title = 'My First Article'
url = '/articles/my-first-article' url = '/articles/my-first-article'
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -58,7 +58,7 @@ https://example.org/articles/my-first-article/
If you include a file extension: If you include a file extension:
{{< code-toggle file="content/posts/post-1.md" copy=false fm=true >}} {{< code-toggle file="content/posts/post-1.md" fm=true >}}
title = 'My First Article' title = 'My First Article'
url = '/articles/my-first-article.html' url = '/articles/my-first-article.html'
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -112,7 +112,7 @@ content/
Render tutorials under "training", and render the posts under "articles" with a date-base hierarchy: Render tutorials under "training", and render the posts under "articles" with a date-base hierarchy:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[permalinks.page] [permalinks.page]
posts = '/articles/:year/:month/:slug/' posts = '/articles/:year/:month/:slug/'
tutorials = '/training/:slug/' tutorials = '/training/:slug/'
@@ -145,14 +145,14 @@ public/
To create a date-based hierarchy for regular pages in the content root: To create a date-based hierarchy for regular pages in the content root:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[permalinks.page] [permalinks.page]
"/" = "/:year/:month/:slug/" "/" = "/:year/:month/:slug/"
{{< /code-toggle >}} {{< /code-toggle >}}
Use the same approach with taxonomy terms. For example, to omit the taxonomy segment of the URL: Use the same approach with taxonomy terms. For example, to omit the taxonomy segment of the URL:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[permalinks.term] [permalinks.term]
'tags' = '/:slug/' 'tags' = '/:slug/'
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -179,7 +179,7 @@ content/
And this site configuration: And this site configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
defaultContentLanguage = 'en' defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = true defaultContentLanguageInSubdir = true
@@ -280,7 +280,7 @@ For time-related values, you can also use the layout string components defined i
[time package]: https://pkg.go.dev/time#pkg-constants [time package]: https://pkg.go.dev/time#pkg-constants
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
permalinks: permalinks:
posts: /:06/:1/:2/:title/ posts: /:06/:1/:2/:title/
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -296,7 +296,7 @@ pretty|content/about.md|`https://example.org/about/`
By default, Hugo produces pretty URLs. To generate ugly URLs, change your site configuration: 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 uglyURLs = true
{{< /code-toggle >}} {{< /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. 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.
```text ```html
<a href="/about"> → <a href="https://example.org/about/"> <a href="/about"> → <a href="https://example.org/about/">
<img src="/a.gif"> → <img src="https://example.org/a.gif"> <img src="/a.gif"> → <img src="https://example.org/a.gif">
``` ```
@@ -323,7 +323,7 @@ This is an imperfect, brute force approach that can affect content as well as HT
To enable: To enable:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
canonifyURLs = true canonifyURLs = true
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -337,7 +337,7 @@ If enabled, Hugo performs a search and replace _after_ it renders the page. It s
For example, when rendering `content/posts/post-1`: For example, when rendering `content/posts/post-1`:
```text ```html
<a href="/about"><a href="../../about"> <a href="/about"><a href="../../about">
<img src="/a.gif"><img src="../../a.gif"> <img src="/a.gif"><img src="../../a.gif">
``` ```
@@ -346,7 +346,7 @@ This is an imperfect, brute force approach that can affect content as well as HT
To enable: To enable:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
relativeURLs = true relativeURLs = true
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -361,7 +361,7 @@ Create redirects from old URLs to new URLs with aliases:
Change the file name of an existing page, and create an alias from the previous URL to the new URL: Change the file name of an existing page, and create an alias from the previous URL to the new URL:
{{< code-toggle file="content/posts/new-file-name.md" copy=false >}} {{< code-toggle file="content/posts/new-file-name.md" >}}
aliases = ['/posts/previous-file-name'] aliases = ['/posts/previous-file-name']
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -373,13 +373,13 @@ Each of these directory-relative aliases is equivalent to the site-relative alia
You can create more than one alias to the current page: You can create more than one alias to the current page:
{{< code-toggle file="content/posts/new-file-name.md" copy=false >}} {{< code-toggle file="content/posts/new-file-name.md" >}}
aliases = ['previous-file-name','original-file-name'] aliases = ['previous-file-name','original-file-name']
{{< /code-toggle >}} {{< /code-toggle >}}
In a multilingual site, use a directory-relative alias, or include the language prefix with a site-relative alias: In a multilingual site, use a directory-relative alias, or include the language prefix with a site-relative alias:
{{< code-toggle file="content/posts/new-file-name.de.md" copy=false >}} {{< code-toggle file="content/posts/new-file-name.de.md" >}}
aliases = ['/de/posts/previous-file-name'] aliases = ['/de/posts/previous-file-name']
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -400,7 +400,7 @@ public/
The alias from the previous URL to the new URL is a client-side redirect: The alias from the previous URL to the new URL is a client-side redirect:
{{< code file="posts/previous-file-name/index.html" copy=false >}} {{< code file="posts/previous-file-name/index.html" >}}
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en-us"> <html lang="en-us">
<head> <head>
+1 -1
View File
@@ -313,7 +313,7 @@ git commit --amend
#### Modify multiple commits #### Modify multiple commits
{{% warning "Be Careful Modifying Multiple Commits"%}} {{% note %}}
Modifications such as those described in this section can have serious unintended consequences. Skip this section if you're not sure! Modifications such as those described in this section can have serious unintended consequences. Skip this section if you're not sure!
{{% /note %}} {{% /note %}}
+4 -4
View File
@@ -24,7 +24,7 @@ Step 2
Step 3 Step 3
: Create a new branch with a descriptive name. : Create a new branch with a descriptive name.
```bash ```sh
git checkout -b fix/typos-site-variables git checkout -b fix/typos-site-variables
``` ```
@@ -34,7 +34,7 @@ Step 4
Step 5 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]. : 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].
```bash ```sh
git commit -m "Fix typos on site variables page git commit -m "Fix typos on site variables page
Closes #1234 Closes #1234
@@ -128,7 +128,7 @@ fm
#### Site configuration example #### Site configuration example
```text ```text
{{</* code-toggle file="hugo" */>}} {{</* code-toggle file=hugo */>}}
baseURL = 'https://example.org' baseURL = 'https://example.org'
languageCode = 'en-US' languageCode = 'en-US'
title = "Example Site" title = "Example Site"
@@ -137,7 +137,7 @@ title = "Example Site"
Rendered: Rendered:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
baseURL = 'https://example.org' baseURL = 'https://example.org'
languageCode = 'en-US' languageCode = 'en-US'
title = "Example Site" title = "Example Site"
+9 -1
View File
@@ -9,6 +9,14 @@ weight: 1
layout: documentation-home layout: documentation-home
--- ---
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.
[bep]: https://github.com/bep
[spf13]: https://github.com/spf13
[friends]: https://github.com/gohugoio/hugo/graphs/contributors
[go]: https://go.dev/
[static site generator]: https://en.wikipedia.org/wiki/Static_site_generator
Below you will find some of the most common and helpful pages from our documentation. Below you will find some of the most common and helpful pages from our documentation.
-26
View File
@@ -1,26 +0,0 @@
---
title: .Get
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:
```go-html-template
{{ $quality := default "100" (.Get 1) }}
```
[sc]: /templates/shortcode-templates/
-84
View File
@@ -1,84 +0,0 @@
---
title: .GetPage
description: Gets a `Page` of a given `path`.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType:
signatures: [.GetPage PATH]
relatedFunctions: []
---
`.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.
[partials]: /templates/partials/
[taxonomy]: /content-management/taxonomies/
[page_kinds]: /templates/section-templates/#page-kinds
[leaf_bundle]: /content-management/page-bundles/#leaf-bundles
[headless_bundle]: /content-management/page-bundles/#headless-bundle
[page_resources]: /content-management/page-resources/
-50
View File
@@ -1,50 +0,0 @@
---
title: .Param
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:
**Configuration**
{{< code-toggle file="hugo" copy=false >}}
[params]
display_toc = true
{{< /code-toggle >}}
**Content**
{{< code-toggle file="content/example.md" fm=true copy=false >}}
title = 'Example'
date = 2023-01-01
draft = false
display_toc = false
{{< /code-toggle >}}
**Template**
{{< code file="layouts/_default/single.html" copy=false >}}
{{ if .Param "display_toc" }}
{{ .TableOfContents }}
{{ end }}
{{< /code >}}
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:
{{< code file="layouts/_default/single.html" copy=false >}}
{{ or .Params.foo site.Params.foo }}
{{< /code >}}
-28
View File
@@ -1,28 +0,0 @@
---
title: .Render
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`:
```go-html-template
{{ range .Pages }}
{{ .Render "summary" }}
{{ end }}
```
[list context]: /templates/lists/
-35
View File
@@ -1,35 +0,0 @@
---
title: .RenderString
description: Renders markup to HTML.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: template.HTML
signatures: ['.RenderString MARKUP [OPTIONS]']
---
`.RenderString` is a method on `Page` that renders some markup to HTML using the content renderer defined for that page (if not set in the options).
The method takes an optional map argument with these options:
display ("inline")
: `inline` or `block`. If `inline` (default), surrounding `<p></p>` on short snippets will be trimmed.
markup (defaults to the Page's markup)
: See identifiers in [List of content formats](/content-management/formats/#list-of-content-formats).
Some examples:
```go-html-template
{{ $optBlock := dict "display" "block" }}
{{ $optOrg := dict "markup" "org" }}
{{ "**Bold Markdown**" | $p.RenderString }}
{{ "**Bold Block Markdown**" | $p.RenderString $optBlock }}
{{ "/italic org mode/" | $p.RenderString $optOrg }}
```
{{< 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).
-151
View File
@@ -1,151 +0,0 @@
---
title: .Scratch
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`.
```go-html-template
{{ .Scratch.Set "greeting" "bonjour" }}
{{ range .Pages }}
{{ .Scratch.Set "greeting" (print "bonjour" .Title) }}
{{ end }}
```
#### The local `newScratch`
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.
```go-html-template
{{ $scratch.Add "greetings" "Hello" }}
{{ $scratch.Add "greetings" "Welcome" }}
----
{{ $scratch.Get "greetings" }} > HelloWelcome
```
```go-html-template
{{ $scratch.Add "total" 3 }}
{{ $scratch.Add "total" 7 }}
----
{{ $scratch.Get "total" }} > 10
```
```go-html-template
{{ $scratch.Add "greetings" (slice "Hello") }}
{{ $scratch.Add "greetings" (slice "Welcome" "Cheers") }}
----
{{ $scratch.Get "greetings" }} > []interface {}{"Hello", "Welcome", "Cheers"}
```
#### .SetInMap
Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`.
```go-html-template
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.Get "greetings" }} > map[french:Bonjour english:Hello]
```
#### .DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ .Scratch.SetInMap "greetings" "english" "Hello" }}
{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ .Scratch.DeleteInMap "greetings" "english" }}
----
{{ .Scratch.Get "greetings" }} > map[french:Bonjour]
```
#### .GetSortedMapValues
Return an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.GetSortedMapValues "greetings" }} > [Hello Bonjour]
```
#### .Delete
Remove the given key.
```go-html-template
{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Delete "greeting" }}
```
#### .Values
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.
[pagevars]: /variables/page/
-111
View File
@@ -1,111 +0,0 @@
---
title: .Store
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.
```go-html-template
{{ .Store.Add "greetings" "Hello" }}
{{ .Store.Add "greetings" "Welcome" }}
{{ .Store.Get "greetings" }} → HelloWelcome
```
```go-html-template
{{ .Store.Add "total" 3 }}
{{ .Store.Add "total" 7 }}
{{ .Store.Get "total" }} → 10
```
```go-html-template
{{ .Store.Add "greetings" (slice "Hello") }}
{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }}
{{ .Store.Get "greetings" }} → []interface {}{"Hello", "Welcome", "Cheers"}
```
#### .SetInMap
Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`.
```go-html-template
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.Get "greetings" }} → map[french:Bonjour english:Hello]
```
#### .DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.DeleteInMap "greetings" "english" }}
{{ .Store.Get "greetings" }} → map[french:Bonjour]
```
#### .GetSortedMapValues
Returns an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour]
```
#### .Delete
Removes the given key.
```go-html-template
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.Delete "greeting" }}
```
-36
View File
@@ -1,36 +0,0 @@
---
title: .Unix
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&nbsp;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.
```go-html-template
.Date.Unix → 1637259694
.ExpiryDate.Unix → 1672559999
.Lastmod.Unix → 1637361786
.PublishDate.Unix → 1637421261
("1970-01-01T00:00:00-00:00" | time.AsTime).Unix → 0
("1970-01-01T00:00:42-00:00" | time.AsTime).Unix → 42
("1970-04-11T01:48:29-08:00" | time.AsTime).Unix → 8675309
("2026-05-02T20:09:31-07:00" | time.AsTime).Unix → 1777777771
now.Unix → 1637447841
now.UnixMilli → 1637447841347
now.UnixMicro → 1637447841347378
now.UnixNano → 1637447841347378799
```
+13
View File
@@ -0,0 +1,13 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->
@@ -0,0 +1,23 @@
---
# Do not remove front matter.
---
Path|Pattern|Match
:--|:--|:--
`images/foo/a.jpg`|`images/foo/*.jpg`|`true`
`images/foo/a.jpg`|`images/foo/*.*`|`true`
`images/foo/a.jpg`|`images/foo/*`|`true`
`images/foo/a.jpg`|`images/*/*.jpg`|`true`
`images/foo/a.jpg`|`images/*/*.*`|`true`
`images/foo/a.jpg`|`images/*/*`|`true`
`images/foo/a.jpg`|`*/*/*.jpg`|`true`
`images/foo/a.jpg`|`*/*/*.*`|`true`
`images/foo/a.jpg`|`*/*/*`|`true`
`images/foo/a.jpg`|`**/*.jpg`|`true`
`images/foo/a.jpg`|`**/*.*`|`true`
`images/foo/a.jpg`|`**/*`|`true`
`images/foo/a.jpg`|`**`|`true`
`images/foo/a.jpg`|`*/*.jpg`|`false`
`images/foo/a.jpg`|`*.jpg`|`false`
`images/foo/a.jpg`|`*.*`|`false`
`images/foo/a.jpg`|`*`|`false`
@@ -1,3 +0,0 @@
See Go's [text/template] documentation for more details.
[text/template]: https://pkg.go.dev/text/template
-3
View File
@@ -1,3 +0,0 @@
+++
headless = true
+++
+7
View File
@@ -1,3 +1,10 @@
---
# Do not remove front matter.
---
{{% note %}}
Localization of dates, currencies, numbers, and percentages is performed by the [gohugoio/locales] package. The language tag of the current site must match one of the listed locales. Localization of dates, currencies, numbers, and percentages is performed by the [gohugoio/locales] package. The language tag of the current site must match one of the listed locales.
[gohugoio/locales]: https://github.com/gohugoio/locales [gohugoio/locales]: https://github.com/gohugoio/locales
{{% /note %}}
@@ -1,3 +1,7 @@
---
# Do not remove front matter.
---
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. 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'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.
@@ -1,12 +1,16 @@
---
# Do not remove front matter.
---
Format a `time.Time` value based on [Go's reference time]: Format a `time.Time` value based on [Go's reference time]:
[Go's reference time]: https://pkg.go.dev/time#pkg-constants [Go's reference time]: https://pkg.go.dev/time#pkg-constants
```text {copy=false} ```text
Mon Jan 2 15:04:05 MST 2006 Mon Jan 2 15:04:05 MST 2006
``` ```
Create a format string using these components: Create a layout string using these components:
Description|Valid components Description|Valid components
:--|:-- :--|:--
@@ -21,7 +25,7 @@ Second|`"5" "05"`
AM/PM mark|`"PM"` AM/PM mark|`"PM"`
Time zone offsets|`"-0700" "-07:00" "-07" "-070000" "-07:00:00"` Time zone offsets|`"-0700" "-07:00" "-07" "-070000" "-07:00:00"`
Replace the sign in the format string with a Z to print Z instead of an offset for the UTC zone. Replace the sign in the layout string with a Z to print Z instead of an offset for the UTC zone.
Description|Valid components Description|Valid components
:--|:-- :--|:--
+4 -4
View File
@@ -1,7 +1,8 @@
--- ---
title: Functions title: Functions
linkTitle: Overview linkTitle: Overview
description: Comprehensive list of Hugo templating functions, including basic and advanced usage examples. description: A list of Hugo template functions including examples.
categories: []
keywords: [] keywords: []
menu: menu:
docs: docs:
@@ -9,9 +10,8 @@ menu:
parent: functions parent: functions
weight: 10 weight: 10
weight: 10 weight: 10
showSectionMenu: true
aliases: [/layout/functions/,/templates/functions] aliases: [/layout/functions/,/templates/functions]
--- ---
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. Use these functions within your templates and archetypes.
[gofuncs]: https://golang.org/pkg/text/template/#hdr-Functions
+6 -11
View File
@@ -1,20 +1,15 @@
--- ---
title: cast.ToFloat title: cast.ToFloat
linkTitle: float description: Converts a value to a decimal floating-point number (base 10).
description: Casts a value to a decimal (base 10) floating point value. categories: []
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [float] aliases: [float]
related:
- functions/cast/ToInt
- functions/cast/ToString
returnType: float64 returnType: float64
signatures: [cast.ToFloat INPUT] signatures: [cast.ToFloat INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
aliases: [/functions/float] aliases: [/functions/float]
--- ---
+9 -15
View File
@@ -1,20 +1,14 @@
--- ---
title: cast.ToInt title: cast.ToInt
linkTitle: int description: Converts a value to a decimal integer (base 10).
description: Casts a value to a decimal (base 10) integer.
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [int] aliases: [int]
related:
- functions/cast/ToFloat
- functions/cast/ToString
returnType: int returnType: int
signatures: [cast.ToInt INPUT] signatures: [cast/ToInt INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
aliases: [/functions/int] aliases: [/functions/int]
--- ---
@@ -24,8 +18,8 @@ With a decimal (base 10) input:
{{ int 11 }} → 11 (int) {{ int 11 }} → 11 (int)
{{ int "11" }} → 11 (int) {{ int "11" }} → 11 (int)
{{ int 11.1 }} → 11 (int) {{ int 11/1 }} → 11 (int)
{{ int 11.9 }} → 11 (int) {{ int 11/9 }} → 11 (int)
``` ```
With a binary (base 2) input: With a binary (base 2) input:
@@ -55,5 +49,5 @@ With a hexadecimal (base 16) input:
{{% note %}} {{% note %}}
Values with a leading zero are octal (base 8). When casting a string representation of a decimal (base 10) number, remove leading zeros: Values with a leading zero are octal (base 8). When casting a string representation of a decimal (base 10) number, remove leading zeros:
`{{ strings.TrimLeft "0" "0011" | int }} → 11` `{{ strings/TrimLeft "0" "0011" | int }} → 11`
{{% /note %}} {{% /note %}}
+6 -11
View File
@@ -1,20 +1,15 @@
--- ---
title: cast.ToString title: cast.ToString
linkTitle: string description: Converts a value to a string.
description: Cast a value to a string. categories: []
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [string] aliases: [string]
related:
- functions/cast/ToFloat
- functions/cast/ToInt
returnType: string returnType: string
signatures: [cast.ToString INPUT] signatures: [cast.ToString INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
aliases: [/functions/string] aliases: [/functions/string]
--- ---
+12
View File
@@ -0,0 +1,12 @@
---
title: Cast functions
linkTitle: cast
description: Template functions to cast a value from one data type to another.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to cast a value from one data type to another.
+24 -29
View File
@@ -1,20 +1,15 @@
--- ---
title: collections.After title: collections.After
linkTitle: after
description: Slices an array to the items after the Nth item. description: Slices an array to the items after the Nth item.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [after] aliases: [after]
related:
- functions/collections/First
- functions/collections/Last
returnType: any returnType: any
signatures: [collections.After INDEX COLLECTION] signatures: [collections.After INDEX COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
aliases: [/functions/after] aliases: [/functions/after]
--- ---
@@ -37,30 +32,30 @@ You can use `after` in combination with the [`first`] function and Hugo's [power
{{< code file="layouts/section/articles.html" >}} {{< code file="layouts/section/articles.html" >}}
{{ define "main" }} {{ define "main" }}
<section class="row featured-article"> <section class="row featured-article">
<h2>Featured Article</h2> <h2>Featured Article</h2>
{{ range first 1 .Pages.ByPublishDate.Reverse }} {{ range first 1 .Pages.ByPublishDate.Reverse }}
<header> <header>
<h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3> <h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3>
</header> </header>
<p>{{ .Description }}</p> <p>{{ .Description }}</p>
{{ end }}
</section>
<div class="row recent-articles">
<h2>Recent Articles</h2>
{{ range first 3 (after 1 .Pages.ByPublishDate.Reverse) }}
<section class="recent-article">
<header>
<h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3>
</header>
<p>{{ .Description }}</p>
</section>
{{ end }} {{ end }}
</div> </section>
<div class="row recent-articles">
<h2>Recent Articles</h2>
{{ range first 3 (after 1 .Pages.ByPublishDate.Reverse) }}
<section class="recent-article">
<header>
<h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3>
</header>
<p>{{ .Description }}</p>
</section>
{{ end }}
</div>
{{ end }} {{ end }}
{{< /code >}} {{< /code >}}
[`first`]: /functions/collections/first [`first`]: /functions/collections/first
[list/section page]: /templates/section-templates [list/section page]: /templates/section-templates
[lists]: /templates/lists/#order-content [lists]: /templates/lists/#sort-content
[`slice`]: /functions/collections/slice/ [`slice`]: /functions/collections/slice/
+7 -12
View File
@@ -1,22 +1,17 @@
--- ---
title: collections.Append title: collections.Append
linkTitle: append
description: Appends one or more elements to a slice and returns the resulting slice. description: Appends one or more elements to a slice and returns the resulting slice.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [append] aliases: [append]
related:
- functions/collections/Merge
- functions/collections/Slice
returnType: any returnType: any
signatures: signatures:
- COLLECTION | collections.Append ELEMENT [ELEMENT]... - COLLECTION | collections.Append ELEMENT [ELEMENT...]
- COLLECTION | collections.Append COLLECTION - COLLECTION | collections.Append COLLECTION
relatedFunctions:
- collections.Append
- collections.Merge
- collections.Slice
aliases: [/functions/append] aliases: [/functions/append]
--- ---
@@ -100,7 +95,7 @@ Although the elements in the examples above are strings, you can use the `append
{{ with $p }} {{ with $p }}
<ul> <ul>
{{ range . }} {{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
{{ end }} {{ end }}
</ul> </ul>
{{ end }} {{ end }}
+2 -8
View File
@@ -1,18 +1,13 @@
--- ---
title: collections.Apply title: collections.Apply
linkTitle: apply
description: Returns a new collection with each element transformed by the given function. description: Returns a new collection with each element transformed by the given function.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [apply] aliases: [apply]
returnType: '[]any' returnType: '[]any'
signatures: [collections.Apply COLLECTION FUNCTION PARAM...] signatures: [collections.Apply COLLECTION FUNCTION PARAM...]
relatedFunctions: relatedFunctions:
- collections.Apply
- collections.Delimit - collections.Delimit
- collections.In - collections.In
- collections.Reverse - 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. 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.
```go-html-template ```go-html-template
{{ $s := slice "hello" "world" }} {{ $s := slice "hello" "world" }}
+10 -16
View File
@@ -1,21 +1,16 @@
--- ---
title: collections.Complement title: collections.Complement
linkTitle: complement
description: Returns the elements of the last collection that are not in any of the others. description: Returns the elements of the last collection that are not in any of the others.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [complement] aliases: [complement]
related:
- functions/collections/Intersect
- functions/collections/SymDiff
- functions/collections/Union
returnType: any returnType: any
signatures: ['collections.Complement COLLECTION [COLLECTION]...'] signatures: ['collections.Complement COLLECTION [COLLECTION...]']
relatedFunctions:
- collections.Complement
- collections.Intersect
- collections.SymDiff
- collections.Union
aliases: [/functions/complement] aliases: [/functions/complement]
--- ---
@@ -35,7 +30,6 @@ Make your code simpler to understand by using a [chained pipeline]:
[chained pipeline]: https://pkg.go.dev/text/template#hdr-Pipelines [chained pipeline]: https://pkg.go.dev/text/template#hdr-Pipelines
{{% /note %}} {{% /note %}}
```go-html-template ```go-html-template
{{ $c3 | complement $c1 $c2 }} → [1 2] {{ $c3 | complement $c1 $c2 }} → [1 2]
``` ```
@@ -57,7 +51,7 @@ To list everything except blog articles (`blog`) and frequently asked questions
{{ $blog := where site.RegularPages "Type" "blog" }} {{ $blog := where site.RegularPages "Type" "blog" }}
{{ $faqs := where site.RegularPages "Type" "faqs" }} {{ $faqs := where site.RegularPages "Type" "faqs" }}
{{ range site.RegularPages | complement $blog $faqs }} {{ range site.RegularPages | complement $blog $faqs }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> <a href="{{ .RelPermalink }}">{{ .Title }}</a>
{{ end }} {{ end }}
``` ```
@@ -65,11 +59,11 @@ To list everything except blog articles (`blog`) and frequently asked questions
Although the example above demonstrates the `complement` function, you could use the [`where`] function as well: Although the example above demonstrates the `complement` function, you could use the [`where`] function as well:
[`where`]: /functions/collections/where [`where`]: /functions/collections/where
{{% /note %}} {{% /note %}}
```go-html-template ```go-html-template
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }} {{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> <a href="{{ .RelPermalink }}">{{ .Title }}</a>
{{ end }} {{ end }}
``` ```
+14 -19
View File
@@ -1,24 +1,19 @@
--- ---
title: collections.Delimit title: collections.Delimit
linkTitle: delimit
description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter. description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [delimit] aliases: [delimit]
returnType: template.HTML related:
- functions/collections/Apply
- functions/collections/In
- functions/collections/Reverse
- functions/collections/Seq
- functions/collections/Slice
- functions/strings/Split
returnType: string
signatures: ['collections.Delimit COLLECTION DELIMITER [LAST]'] signatures: ['collections.Delimit COLLECTION DELIMITER [LAST]']
relatedFunctions:
- collections.Apply
- collections.Delimit
- collections.In
- collections.Reverse
- collections.Seq
- collections.Slice
- strings.Split
aliases: [/functions/delimit] aliases: [/functions/delimit]
--- ---
@@ -26,8 +21,8 @@ Delimit a slice:
```go-html-template ```go-html-template
{{ $s := slice "b" "a" "c" }} {{ $s := slice "b" "a" "c" }}
{{ delimit $s ", " }} → "b, a, c" {{ delimit $s ", " }} → b, a, c
{{ delimit $s ", " " and "}} → "b, a and c" {{ delimit $s ", " " and "}} → b, a and c
``` ```
Delimit a map: Delimit a map:
@@ -38,6 +33,6 @@ The `delimit` function sorts maps by key, returning the values.
```go-html-template ```go-html-template
{{ $m := dict "b" 2 "a" 1 "c" 3 }} {{ $m := dict "b" 2 "a" 1 "c" 3 }}
{{ delimit $m ", " }} → "1, 2, 3" {{ delimit $m ", " }} → 1, 2, 3
{{ delimit $m ", " " and "}} → "1, 2 and 3" {{ delimit $m ", " " and "}} → 1, 2 and 3
``` ```
+22 -14
View File
@@ -1,22 +1,17 @@
--- ---
title: collections.Dictionary title: collections.Dictionary
linkTitle: dict
description: Creates a map from a list of key and value pairs. description: Creates a map from a list of key and value pairs.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [dict] aliases: [dict]
related:
- functions/collections/Group
- functions/collections/IndexFunction
- functions/collections/IsSet
- functions/collections/Where
returnType: mapany returnType: mapany
signatures: ['collections.Dictionary KEY VALUE [KEY VALUE]...'] signatures: ['collections.Dictionary KEY VALUE [VALUE...]']
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
aliases: [/functions/dict] aliases: [/functions/dict]
--- ---
@@ -24,10 +19,23 @@ aliases: [/functions/dict]
Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deeply nested structure, e.g.: Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deeply nested structure, e.g.:
```go-text-template ```go-html-template
{{ $m := dict (slice "a" "b" "c") "value" }} {{ $m := dict (slice "a" "b" "c") "value" }}
``` ```
The above produces this data structure:
```json
{
"a": {
"b": {
"c": "value"
}
}
}
```
## Example: using `dict` to pass multiple values to a `partial` ## Example: using `dict` to pass multiple values to a `partial`
The partial below creates an SVG and expects `fill`, `height` and `width` from the caller: The partial below creates an SVG and expects `fill`, `height` and `width` from the caller:
@@ -1,40 +0,0 @@
---
title: collections.EchoParam
linkTitle: echoParam
description: Prints a parameter if it is set.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: [echoParam]
returnType: any
signatures: [collections.EchoParam COLLECTION KEY]
relatedFunctions: []
aliases: [/functions/echoparam]
---
For example, consider this site configuration:
{{< code-toggle file=hugo copy=false >}}
[params.footer]
poweredBy = 'Hugo'
{{< /code-toggle >}}
To print the value of `poweredBy`:
```go-html-template
{{ echoParam site.Params.footer "poweredby" }} → Hugo
```
{{% note %}}
When using the `echoParam` function you must reference the key using lower case. See the previous example.
The `echoParam` function will be deprecated in a future release. Instead, use either of the constructs below.
{{% /note %}}
```go-html-template
{{ site.Params.footer.poweredBy }} → Hugo
{{ index site.Params.footer "poweredBy" }} → Hugo
```
+9 -16
View File
@@ -1,34 +1,28 @@
--- ---
title: collections.First title: collections.First
linkTitle: first
description: Slices an array to the first N elements. description: Slices an array to the first N elements.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [first] aliases: [first]
related:
- functions/collections/After
- functions/collections/Last
returnType: any returnType: any
signatures: [collections.First LIMIT COLLECTION] signatures: [collections.First LIMIT COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
aliases: [/functions/first] aliases: [/functions/first]
--- ---
`first` works in a similar manner to the [`limit` keyword in `first` works in a similar manner to the [`limit` keyword in SQL][limitkeyword]. It reduces the array to only the `first N` elements. It takes the array and number of elements as input.
SQL][limitkeyword]. It reduces the array to only the `first N`
elements. It takes the array and number of elements as input.
`first` takes two arguments: `first` takes two arguments:
1. `number of elements` 1. `number of elements`
2. `array` *or* `slice of maps or structs` 2. `array` *or* `slice of maps or structs`
{{< code file="layout/_default/section.html" >}} {{< code file="layout/_default/section.html" >}}
{{ range first 10 .Pages }} {{ range first 10 .Pages }}
{{ .Render "summary" }} {{ .Render "summary" }}
{{ end }} {{ end }}
{{< /code >}} {{< /code >}}
@@ -43,11 +37,10 @@ ranges through only the first 5 posts in that list:
{{< code file="first-and-where-together.html" >}} {{< code file="first-and-where-together.html" >}}
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }} {{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }}
{{ .Content }} {{ .Content }}
{{ end }} {{ end }}
{{< /code >}} {{< /code >}}
[limitkeyword]: https://www.techonthenet.com/sql/select_limit.php [limitkeyword]: https://www.techonthenet.com/sql/select_limit.php
[`where`]: /functions/collections/where [`where`]: /functions/collections/where
[main sections]: /functions/collections/where#mainsections [main sections]: /functions/collections/where#mainsections
+9 -14
View File
@@ -1,26 +1,21 @@
--- ---
title: collections.Group title: collections.Group
linkTitle: group
description: Groups a list of pages. description: Groups a list of pages.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [group] aliases: [group]
related:
- functions/collections/Dictionary
- functions/collections/IndexFunction
- functions/collections/IsSet
- functions/collections/Where
returnType: any returnType: any
signatures: [PAGES | collections.Group KEY] signatures: [PAGES | collections.Group KEY]
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
aliases: [/functions/group] aliases: [/functions/group]
--- ---
{{< code file="layouts/partials/groups.html" >}} ```go-html-template
{{ $new := .Site.RegularPages | first 10 | group "New" }} {{ $new := .Site.RegularPages | first 10 | group "New" }}
{{ $old := .Site.RegularPages | last 10 | group "Old" }} {{ $old := .Site.RegularPages | last 10 | group "Old" }}
{{ $groups := slice $new $old }} {{ $groups := slice $new $old }}
@@ -35,6 +30,6 @@ aliases: [/functions/group]
{{ end }} {{ end }}
</ul> </ul>
{{ end }} {{ 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). 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).
+9 -9
View File
@@ -1,22 +1,22 @@
--- ---
title: collections.In title: collections.In
linkTitle: in
description: Reports whether an element is in an array or slice, or if a substring is in a string. description: Reports whether an element is in an array or slice, or if a substring is in a string.
categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [in] aliases: [in]
related:
- functions/collections/Slice
- functions/strings/Contains
- functions/strings/ContainsAny
- functions/strings/ContainsNonSpace
- functions/strings/HasPrefix
- functions/strings/HasSuffix
returnType: bool returnType: bool
signatures: [collections.In SET ITEM] signatures: [collections.In SET ITEM]
relatedFunctions:
- collections.Slice
aliases: [/functions/in] aliases: [/functions/in]
--- ---
```go-html-template ```go-html-template
{{ $s := slice "a" "b" "c" }} {{ $s := slice "a" "b" "c" }}
{{ in $s "b" }} → true {{ in $s "b" }} → true
@@ -1,71 +1,66 @@
--- ---
title: collections.Index title: collections.Index
linkTitle: index
description: Looks up the index(es) or key(s) of the data structure passed into it. description: Looks up the index(es) or key(s) of the data structure passed into it.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [index] aliases: [index]
related:
- functions/collections/Dictionary
- functions/collections/Group
- functions/collections/IsSet
- functions/collections/Where
returnType: any returnType: any
signatures: signatures:
- collections.Index COLLECTION INDEXES - collections.Index COLLECTION INDEXES
- collections.Index COLLECTION KEYS - collections.Index COLLECTION KEYS
relatedFunctions:
- collections.Dictionary
- collections.EchoParam
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
aliases: [/functions/index,/functions/index-function] aliases: [/functions/index,/functions/index-function]
--- ---
The `index` functions returns the result of indexing its first argument by the following arguments. Each indexed item must be a map or a slice, e.g.: The `index` functions returns the result of indexing its first argument by the following arguments. Each indexed item must be a map or a slice, e.g.:
```go-text-template ```go-html-template
{{ $slice := slice "a" "b" "c" }} {{ $slice := slice "a" "b" "c" }}
{{ index $slice 1 }} => b {{ index $slice 0 }} → a
{{ index $slice 1 }} → b
{{ $map := dict "a" 100 "b" 200 }} {{ $map := dict "a" 100 "b" 200 }}
{{ index $map "b" }} => 200 {{ index $map "b" }} 200
``` ```
The function takes multiple indices as arguments, and this can be used to get nested values, e.g.: The function takes multiple indices as arguments, and this can be used to get nested values, e.g.:
```go-text-template ```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }} {{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $map "c" 1 }} => 20 {{ index $map "c" 1 }} 20
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }} {{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $map "c" "e" }} => 20 {{ index $map "c" "e" }} 20
``` ```
You may write multiple indices as a slice: You may write multiple indices as a slice:
```go-text-template ```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }} {{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $slice := slice "c" "e" }} {{ $slice := slice "c" "e" }}
{{ index $map $slice }} => 20 {{ index $map $slice }} 20
``` ```
## Example: load data from a path based on front matter parameters ## 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: 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:
``` ```text
. data/
└── data └── locations/
└── locations ├── abilene.toml
├── abilene.toml ├── chicago.toml
├── chicago.toml ├── oslo.toml
├── oslo.toml └── provo.toml
└── provo.toml
``` ```
Here is an example: Here is an example:
{{< code-toggle file="data/locations/oslo" copy=false >}} {{< code-toggle file="data/locations/oslo" >}}
website = "https://www.oslo.kommune.no" website = "https://www.oslo.kommune.no"
pop_city = 658390 pop_city = 658390
pop_metro = 1717900 pop_metro = 1717900
@@ -73,7 +68,7 @@ pop_metro = 1717900
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 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/`:
{{< code-toggle file="content/articles/oslo.md" fm=true copy=false >}} {{< code-toggle file="content/articles/oslo.md" fm=true >}}
title = "My Norwegian Vacation" title = "My Norwegian Vacation"
location = "oslo" location = "oslo"
{{< /code-toggle >}} {{< /code-toggle >}}
+6 -12
View File
@@ -1,21 +1,16 @@
--- ---
title: collections.Intersect title: collections.Intersect
linkTitle: intersect
description: Returns the common elements of two arrays or slices, in the same order as the first array. description: Returns the common elements of two arrays or slices, in the same order as the first array.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [intersect] aliases: [intersect]
related:
- functions/collections/Complement
- functions/collections/SymDiff
- functions/collections/Union
returnType: any returnType: any
signatures: [collections.Intersect SET1 SET2] signatures: [collections.Intersect SET1 SET2]
relatedFunctions:
- collections.Complement
- collections.Intersect
- collections.SymDiff
- collections.Union
aliases: [/functions/intersect] aliases: [/functions/intersect]
--- ---
A useful example is to use it as `AND` filters when combined with where: A useful example is to use it as `AND` filters when combined with where:
@@ -32,6 +27,5 @@ The above fetches regular pages not of `page` or `about` type unless they are pi
See [union](/functions/collections/union) for `OR`. See [union](/functions/collections/union) for `OR`.
[partials]: /templates/partials/ [partials]: /templates/partials/
[single]: /templates/single-page-templates/ [single]: /templates/single-page-templates/
+10 -13
View File
@@ -1,28 +1,25 @@
--- ---
title: collections.IsSet title: collections.IsSet
linkTitle: isset
description: Reports whether the key exists within the collection. description: Reports whether the key exists within the collection.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [isset] aliases: [isset]
related:
- functions/collections/Dictionary
- functions/collections/Group
- functions/collections/IndexFunction
- functions/collections/Where
- functions/go-template/if
- functions/go-template/with
returnType: bool returnType: bool
signatures: [collections.IsSet COLLECTION KEY] signatures: [collections.IsSet COLLECTION KEY]
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
aliases: [/functions/isset] aliases: [/functions/isset]
--- ---
For example, consider this site configuration: For example, consider this site configuration:
{{< code-toggle file=hugo copy=false >}} {{< code-toggle file=hugo >}}
[params] [params]
showHeroImage = false showHeroImage = false
{{< /code-toggle >}} {{< /code-toggle >}}
+8 -9
View File
@@ -1,21 +1,20 @@
--- ---
title: collections.KeyVals title: collections.KeyVals
linkTitle: keyVals
description: Returns a KeyVals struct. description: Returns a KeyVals struct.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [keyVals] aliases: [keyVals]
returnType: KeyValues related:
- methods/pages/Related
returnType: types.KeyValues
signatures: [collections.KeyVals KEY VALUES...] signatures: [collections.KeyVals KEY VALUES...]
relatedFunctions: []
aliases: [/functions/keyvals] aliases: [/functions/keyvals]
--- ---
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). See [related content](/content-management/related).
+5 -10
View File
@@ -1,20 +1,15 @@
--- ---
title: collections.Last title: collections.Last
linkTitle: last
description: Slices an array to the last N elements. description: Slices an array to the last N elements.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [last] aliases: [last]
related:
- functions/collections/After
- functions/collections/First
returnType: any returnType: any
signatures: [collections.Last INDEX COLLECTION] signatures: [collections.Last INDEX COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
aliases: [/functions/last] aliases: [/functions/last]
--- ---
+4 -9
View File
@@ -1,19 +1,14 @@
--- ---
title: collections.Merge title: collections.Merge
linkTitle: merge
description: Returns the result of merging two or more maps. description: Returns the result of merging two or more maps.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [merge] aliases: [merge]
related:
- functions/collections/Append
returnType: any returnType: any
signatures: [collections.Merge MAP MAP...] signatures: [collections.Merge MAP MAP...]
relatedFunctions:
- collections.Append
- collections.Merge
aliases: [/functions/merge] aliases: [/functions/merge]
--- ---
+98 -13
View File
@@ -1,22 +1,107 @@
--- ---
title: collections.NewScratch title: collections.NewScratch
linkTitle: newScratch description: Returns a locally scoped "scratch pad" to store and manipulate data.
description: Creates a new Scratch which can be used to store values in a thread safe way. categories: []
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [newScratch] aliases: [newScratch]
returnType: Scratch related:
- methods/page/scratch
- methods/page/store
returnType: maps.Scratch
signatures: [collections.NewScratch ] 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.
[`Scratch`]: /methods/page/scratch
[`Store`]: /methods/page/store
[scratch pad]: /getting-started/glossary/#scratch-pad
## Methods
Set
: Sets the value of a given key.
```go-html-template ```go-html-template
{{ $scratch := newScratch }} {{ $s := newScratch }}
{{ $scratch.Add "b" 2 }} {{ $s.Set "greeting" "Hello" }}
{{ $scratch.Add "b" 2 }}
{{ $scratch.Get "b" }} → 4
``` ```
Get
: Gets the value of a given key.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.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.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.Add "greeting" "Welcome" }}
{{ $s.Get "greeting" }} → HelloWelcome
```
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "total" 3 }}
{{ $s.Add "total" 7 }}
{{ $s.Get "total" }} → 10
```
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greetings" (slice "Hello") }}
{{ $s.Add "greetings" (slice "Welcome" "Cheers") }}
{{ $s.Get "greetings" }} → [Hello Welcome Cheers]
```
SetInMap
: Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.Get "greetings" }} → map[english:Hello french:Bonjour]
```
DeleteInMap
: Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.DeleteInMap "greetings" "english" }}
{{ $s.Get "greetings" }} → map[french:Bonjour]
```
GetSortedMapValues
: Returns an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.GetSortedMapValues "greetings" }} → [Hello Bonjour]
```
Delete
: Removes the given key.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.Delete "greeting" }}
```
Values
: Returns the raw backing map. Do not use with `Scratch` or `Store` methods on a `Page` object due to concurrency issues.
+4 -8
View File
@@ -1,19 +1,15 @@
--- ---
title: collections.Querify title: collections.Querify
linkTitle: querify
description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs. description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [querify] aliases: [querify]
returnType: string returnType: string
signatures: signatures:
- collections.Querify KEY VALUE [KEY VALUE]... - collections.Querify VALUE [VALUE...]
- collections.Querify COLLECTION - collections.Querify COLLECTION
relatedFunctions: related:
- collections.Querify - collections.Querify
- urlquery - urlquery
aliases: [/functions/querify] aliases: [/functions/querify]
+3 -7
View File
@@ -1,16 +1,13 @@
--- ---
title: collections.Reverse title: collections.Reverse
description: Reverses the order of a collection. description: Reverses the order of a collection.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [] aliases: []
returnType: any returnType: any
signatures: [collections.Reverse COLLECTION] signatures: [collections.Reverse COLLECTION]
relatedFunctions: related:
- collections.Apply - collections.Apply
- collections.Delimit - collections.Delimit
- collections.In - collections.In
@@ -20,7 +17,6 @@ relatedFunctions:
aliases: [/functions/collections.reverse] aliases: [/functions/collections.reverse]
--- ---
```go-html-template ```go-html-template
{{ slice 2 1 3 | collections.Reverse }} → [3 1 2] {{ slice 2 1 3 | collections.Reverse }} → [3 1 2]
``` ```
+3 -7
View File
@@ -1,20 +1,16 @@
--- ---
title: collections.Seq title: collections.Seq
linkTitle: seq
description: Returns a slice of integers. description: Returns a slice of integers.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [seq] aliases: [seq]
returnType: '[]int' returnType: '[]int'
signatures: signatures:
- collections.Seq LAST - collections.Seq LAST
- collections.Seq FIRST LAST - collections.Seq FIRST LAST
- collections.Seq FIRST INCREMENT LAST - collections.Seq FIRST INCREMENT LAST
relatedFunctions: related:
- collections.Apply - collections.Apply
- collections.Delimit - collections.Delimit
- collections.In - collections.In
+3 -8
View File
@@ -1,18 +1,13 @@
--- ---
title: collections.Shuffle title: collections.Shuffle
linkTitle: shuffle
description: Returns a random permutation of a given array or slice. description: Returns a random permutation of a given array or slice.
keywords: [ordering] categories: []
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [shuffle] aliases: [shuffle]
returnType: any returnType: any
signatures: [collections.Shuffle COLLECTION] signatures: [collections.Shuffle COLLECTION]
relatedFunctions: related:
- collections.Reverse - collections.Reverse
- collections.Shuffle - collections.Shuffle
- collections.Sort - collections.Sort
+3 -9
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.Slice title: collections.Slice
linkTitle: slice
description: Creates a slice (array) of all passed arguments. description: Creates a slice (array) of all passed arguments.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [slice] aliases: [slice]
returnType: any returnType: any
signatures: [collections.Slice ITEM...] signatures: [collections.Slice ITEM...]
relatedFunctions: related:
- collections.Append - collections.Append
- collections.Apply - collections.Apply
- collections.Delimit - collections.Delimit
@@ -22,8 +18,6 @@ relatedFunctions:
aliases: [/functions/slice] aliases: [/functions/slice]
--- ---
One use case is the concatenation of elements in combination with the [`delimit` function]:
```go-html-template ```go-html-template
{{ $s := slice "a" "b" "c" }} {{ $s := slice "a" "b" "c" }}
{{ $s }} → [a b c] {{ $s }} → [a b c]
+16 -21
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.Sort title: collections.Sort
linkTitle: sort
description: Sorts slices, maps, and page collections. description: Sorts slices, maps, and page collections.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [sort] aliases: [sort]
returnType: any returnType: any
signatures: ['collections.Sort COLLECTION [KEY] [ORDER]'] signatures: ['collections.Sort COLLECTION [KEY] [ORDER]']
relatedFunctions: related:
- collections.Reverse - collections.Reverse
- collections.Shuffle - collections.Shuffle
- collections.Sort - collections.Sort
@@ -27,7 +23,7 @@ The `ORDER` may be either `asc` (ascending) or `desc` (descending). The default
The examples below assume this site configuration: The examples below assume this site configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[params] [params]
grades = ['b','a','c'] grades = ['b','a','c']
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -36,10 +32,10 @@ grades = ['b','a','c']
Sort slice elements in ascending order using either of these constructs: Sort slice elements in ascending order using either of these constructs:
{{< code file="layouts/_default/single.html" copy=false >}} ```go-html-template
{{ sort site.Params.grades }} → [a b c] {{ sort site.Params.grades }} → [a b c]
{{ sort site.Params.grades "value" "asc" }} → [a b c] {{ sort site.Params.grades "value" "asc" }} → [a b c]
{{< /code >}} ```
In the examples above, `value` is the `KEY` representing the value of the slice element. In the examples above, `value` is the `KEY` representing the value of the slice element.
@@ -47,9 +43,9 @@ In the examples above, `value` is the `KEY` representing the value of the slice
Sort slice elements in descending order: Sort slice elements in descending order:
{{< code file="layouts/_default/single.html" copy=false >}} ```go-html-template
{{ sort site.Params.grades "value" "desc" }} → [c b a] {{ sort site.Params.grades "value" "desc" }} → [c b a]
{{< /code >}} ```
In the example above, `value` is the `KEY` representing the value of the slice element. In the example above, `value` is the `KEY` representing the value of the slice element.
@@ -57,7 +53,7 @@ In the example above, `value` is the `KEY` representing the value of the slice e
The examples below assume this site configuration: The examples below assume this site configuration:
{{< code-toggle file="hugo" copy=false >}} {{< code-toggle file=hugo >}}
[params.authors.a] [params.authors.a]
firstName = "Marius" firstName = "Marius"
lastName = "Pontmercy" lastName = "Pontmercy"
@@ -77,7 +73,7 @@ When sorting maps, the `KEY` argument must be lowercase.
Sort map objects in ascending order using either of these constructs: Sort map objects in ascending order using either of these constructs:
{{< code file="layouts/_default/single.html" copy=false >}} ```go-html-template
{{ range sort site.Params.authors "firstname" }} {{ range sort site.Params.authors "firstname" }}
{{ .firstName }} {{ .firstName }}
{{ end }} {{ end }}
@@ -85,7 +81,7 @@ Sort map objects in ascending order using either of these constructs:
{{ range sort site.Params.authors "firstname" "asc" }} {{ range sort site.Params.authors "firstname" "asc" }}
{{ .firstName }} {{ .firstName }}
{{ end }} {{ end }}
{{< /code >}} ```
These produce: These produce:
@@ -97,11 +93,11 @@ Jean Marius Victor
Sort map objects in descending order: Sort map objects in descending order:
{{< code file="layouts/_default/single.html" copy=false >}} ```go-html-template
{{ range sort site.Params.authors "firstname" "desc" }} {{ range sort site.Params.authors "firstname" "desc" }}
{{ .firstName }} {{ .firstName }}
{{ end }} {{ end }}
{{< /code >}} ```
This produces: This produces:
@@ -125,11 +121,10 @@ Although you can use the `sort` function to sort a page collection, Hugo provide
In this contrived example, sort the site's regular pages by `.Type` in descending order: In this contrived example, sort the site's regular pages by `.Type` in descending order:
{{< code file="layouts/_default/home.html" copy=false >}} ```go-html-template
{{ range sort site.RegularPages "Type" "desc" }} {{ range sort site.RegularPages "Type" "desc" }}
<h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
{{< /code >}} ```
[built-in methods for sorting page collections]: /templates/lists/#sort-content
[built-in methods for sorting page collections]: /templates/lists/#order-content
+4 -8
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.SymDiff title: collections.SymDiff
linkTitle: symdiff
description: Returns the symmetric difference of two collections. description: Returns the symmetric difference of two collections.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [symdiff] aliases: [symdiff]
returnType: any returnType: any
signatures: [COLLECTION | collections.SymDiff COLLECTION] signatures: [COLLECTION | collections.SymDiff COLLECTION]
relatedFunctions: related:
- collections.Complement - collections.Complement
- collections.Intersect - collections.Intersect
- collections.SymDiff - collections.SymDiff
@@ -25,4 +21,4 @@ Example:
{{ slice 1 2 3 | symdiff (slice 3 4) }} → [1 2 4] {{ slice 1 2 3 | symdiff (slice 3 4) }} → [1 2 4]
``` ```
Also see https://en.wikipedia.org/wiki/Symmetric_difference Also see <https://en.wikipedia.org/wiki/Symmetric_difference>.
+3 -7
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.Union title: collections.Union
linkTitle: union
description: Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices. description: Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [union] aliases: [union]
returnType: any returnType: any
signatures: [collections.Union SET1 SET2] signatures: [collections.Union SET1 SET2]
relatedFunctions: related:
- collections.Complement - collections.Complement
- collections.Intersect - collections.Intersect
- collections.SymDiff - collections.SymDiff
+3 -8
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.Uniq title: collections.Uniq
linkTitle: uniq
description: Takes in a slice or array and returns a slice with duplicate elements removed. description: Takes in a slice or array and returns a slice with duplicate elements removed.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [uniq] aliases: [uniq]
returnType: any returnType: any
signatures: [collections.Uniq COLLECTION] signatures: [collections.Uniq COLLECTION]
relatedFunctions: related:
- collections.Reverse - collections.Reverse
- collections.Shuffle - collections.Shuffle
- collections.Sort - collections.Sort
@@ -19,7 +15,6 @@ relatedFunctions:
aliases: [/functions/uniq] aliases: [/functions/uniq]
--- ---
```go-html-template ```go-html-template
{{ slice 1 3 2 1 | uniq }} → [1 3 2] {{ slice 1 3 2 1 | uniq }} → [1 3 2]
``` ```
+11 -15
View File
@@ -1,17 +1,13 @@
--- ---
title: collections.Where title: collections.Where
linkTitle: where
description: Filters an array to only the elements containing a matching value for a given field. description: Filters an array to only the elements containing a matching value for a given field.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [where] aliases: [where]
returnType: any returnType: any
signatures: ['collections.Where COLLECTION KEY [OPERATOR] MATCH'] signatures: ['collections.Where COLLECTION KEY [OPERATOR] MATCH']
relatedFunctions: related:
- collections.Dictionary - collections.Dictionary
- collections.Group - collections.Group
- collections.Index - collections.Index
@@ -35,7 +31,7 @@ SQL][wherekeyword].
It can be used by dot-chaining the second argument to refer to a nested element of a value. It can be used by dot-chaining the second argument to refer to a nested element of a value.
{{< code-toggle file="content/example.md" fm=true copy=false >}} {{< code-toggle file="content/example.md" fm=true >}}
title: Example title: Example
series: golang series: golang
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -106,13 +102,13 @@ When using booleans you should not put quotation marks.
You can also put the returned value of the `where` clauses into a variable: You can also put the returned value of the `where` clauses into a variable:
{{< code file="where-intersect-variables.html" >}} ```go-html-template
{{ $v1 := where .Site.Pages "Params.a" "v1" }} {{ $v1 := where .Site.Pages "Params.a" "v1" }}
{{ $v2 := where .Site.Pages "Params.b" "v2" }} {{ $v2 := where .Site.Pages "Params.b" "v2" }}
{{ $filtered := $v1 | intersect $v2 }} {{ $filtered := $v1 | intersect $v2 }}
{{ range $filtered }} {{ range $filtered }}
{{ end }} {{ end }}
{{< /code >}} ```
## Use `where` with `like` ## Use `where` with `like`
@@ -120,11 +116,11 @@ This example matches pages where the "foo" parameter begins with "ab":
```go-html-template ```go-html-template
{{ range where site.RegularPages "Params.foo" "like" `^ab` }} {{ range where site.RegularPages "Params.foo" "like" `^ab` }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }} {{ end }}
``` ```
{{% readfile file="/functions/_common/regular-expressions.md" %}} {{% include "functions/_common/regular-expressions.md" %}}
## Use `where` with `first` ## Use `where` with `first`
@@ -134,11 +130,11 @@ sections**](#mainsections), sorts it using the [default
ordering](/templates/lists/) for lists (i.e., `weight => date`), and ordering](/templates/lists/) for lists (i.e., `weight => date`), and
then ranges through only the first 5 posts in that list: then ranges through only the first 5 posts in that list:
{{< code file="first-and-where-together.html" >}} ```go-html-template
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections) }} {{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections) }}
{{ .Content }} {{ .Content }}
{{ end }} {{ end }}
{{< /code >}} ```
## Nest `where` clauses ## Nest `where` clauses
@@ -181,7 +177,7 @@ If the user has not set this configuration parameter in their site configuration
The user can override the default: The user can override the default:
{{< code-toggle file="hugo" >}} {{< code-toggle file=hugo >}}
[params] [params]
mainSections = ["blog", "docs"] mainSections = ["blog", "docs"]
{{< /code-toggle >}} {{< /code-toggle >}}
@@ -0,0 +1,12 @@
---
title: Collections functions
linkTitle: collections
description: Template functions to work with arrays, slices, maps, and page collections.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to work with arrays, slices, maps, and page collections.
@@ -1,19 +1,14 @@
--- ---
title: compare.Conditional title: compare.Conditional
linkTitle: cond
description: Returns one of two arguments depending on the value of the control argument. description: Returns one of two arguments depending on the value of the control argument.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [cond] aliases: [cond]
related:
- functions/compare/Default
returnType: any returnType: any
signatures: [compare.Conditional CONTROL ARG1 ARG2] signatures: [compare.Conditional CONTROL ARG1 ARG2]
relatedFunctions:
- compare.Conditional
- compare.Default
aliases: [/functions/cond] aliases: [/functions/cond]
--- ---
@@ -21,14 +16,14 @@ The CONTROL argument is a boolean value that indicates whether the function shou
```go-html-template ```go-html-template
{{ $qty := 42 }} {{ $qty := 42 }}
{{ cond (le $qty 3) "few" "many" }} → "many" {{ 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. The CONTROL argument must be either `true` or `false`. To cast a non-boolean value to boolean, pass it through the `not` operator twice.
```go-html-template ```go-html-template
{{ cond (42 | not | not) "truthy" "falsy" }} → "truthy" {{ cond (42 | not | not) "truthy" "falsy" }} → truthy
{{ cond ("" | not | not) "truthy" "falsy" }} → "falsy" {{ cond ("" | not | not) "truthy" "falsy" }} → falsy
``` ```
{{% note %}} {{% note %}}
@@ -38,7 +33,6 @@ Unlike [ternary operators] in other languages, the `cond` function does not perf
[ternary operators]: https://en.wikipedia.org/wiki/Ternary_conditional_operator [ternary operators]: https://en.wikipedia.org/wiki/Ternary_conditional_operator
{{% /note %}} {{% /note %}}
Due to the absence of short-circuit evaluation, these examples throw an error: Due to the absence of short-circuit evaluation, these examples throw an error:
```go-html-template ```go-html-template
+28 -68
View File
@@ -1,88 +1,48 @@
--- ---
title: compare.Default title: compare.Default
linkTitle: default description: Returns the second argument if set, else the first argument.
description: Allows setting a default value that can be returned if a first value is not set.
categories: [functions]
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [default] aliases: [default]
related:
- functions/compare/Conditional
- functions/go-template/Or
returnType: any returnType: any
signatures: [compare.Default DEFAULT INPUT] signatures: [compare.Default DEFAULT INPUT]
relatedFunctions:
- compare.Conditional
- compare.Default
aliases: [/functions/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 {{% note %}}
* non-zero length for strings, arrays, slices, and maps When the second argument is the boolean `false` value, the `default` function returns `false`. All _other_ falsy values are considered unset.
* any boolean or struct value
* non-nil for any other types
`default` function examples reference the following content page: {{% include "functions/go-template/_common/truthy-falsy.md" %}}
{{< code file="content/posts/default-function-example.md" >}} To set a default value based on truthiness, use the [`or`] operator instead.
---
title: Sane Defaults
seo_title:
date: 2017-02-18
font:
oldparam: The default function helps make your templating DRYer.
newparam:
---
{{< /code >}}
`default` can be written in more than one way: [`or`]: /functions/go-template/or
{{% /note %}}
The `default` function returns the second argument if set:
```go-html-template ```go-html-template
{{ .Params.font | default "Roboto" }} {{ default 42 1 }} → 1
{{ default "Roboto" .Params.font }} {{ default 42 "foo" }} → foo
{{ default 42 (dict "k" "v") }} → map[k:v]
{{ default 42 (slice "a" "b") }} → [a b]
{{ default 42 true }} → true
<!-- As noted above, the boolean "false" is considered set -->
{{ default 42 false }} → false
``` ```
Both of the above `default` function calls return `Roboto`. The `default` function returns the first argument if the second argument is not set:
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 ```go-html-template
{{ $old := .Params.oldparam }} {{ default 42 0 }} → 42
<p>{{ .Params.newparam | default $old }}</p> {{ default 42 "" }} → 42
``` {{ default 42 dict }} → 42
{{ default 42 slice }} → 42
Which would return: {{ default 42 <nil> }} → 42
```html
<p>The default function helps make your templating DRYer.</p>
```
And then using dot notation
```go-html-template
<title>{{ .Params.seo_title | default .Title }}</title>
```
Which would return
```html
<title>Sane Defaults</title>
```
The following have equivalent return values but are far less terse. This demonstrates the utility of `default`:
Using `if`:
```go-html-template
<title>{{ if .Params.seo_title }}{{ .Params.seo_title }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults
```
Using `with`:
```go-html-template
<title>{{ with .Params.seo_title }}{{ . }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults
``` ```
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Eq title: compare.Eq
linkTitle: eq
description: Returns the boolean truth of arg1 == arg2 || arg1 == arg3. description: Returns the boolean truth of arg1 == arg2 || arg1 == arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [eq] aliases: [eq]
related:
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool returnType: bool
signatures: ['compare.Eq ARG1 ARG2 [ARG...]'] signatures: ['compare.Eq ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/eq] aliases: [/functions/eq]
--- ---
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Ge title: compare.Ge
linkTitle: ge
description: Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3. description: Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [ge] aliases: [ge]
related:
- functions/compare/Eq
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool returnType: bool
signatures: ['compare.Ge ARG1 ARG2 [ARG...]'] signatures: ['compare.Ge ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/ge] aliases: [/functions/ge]
--- ---
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Gt title: compare.Gt
linkTitle: gt
description: Returns the boolean truth of arg1 > arg2 && arg1 > arg3. description: Returns the boolean truth of arg1 > arg2 && arg1 > arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [gt] aliases: [gt]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool returnType: bool
signatures: ['compare.Gt ARG1 ARG2 [ARG...]'] signatures: ['compare.Gt ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/gt] aliases: [/functions/gt]
--- ---
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Le title: compare.Le
linkTitle: le
description: Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3. description: Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [le] aliases: [le]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Lt
- functions/compare/Ne
returnType: bool returnType: bool
signatures: ['compare.Le ARG1 ARG2 [ARG...]'] signatures: ['compare.Le ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/le] aliases: [/functions/le]
--- ---
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Lt title: compare.Lt
linkTitle: lt
description: Returns the boolean truth of arg1 < arg2 && arg1 < arg3. description: Returns the boolean truth of arg1 < arg2 && arg1 < arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [lt] aliases: [lt]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Ne
returnType: bool returnType: bool
signatures: ['compare.Lt ARG1 ARG2 [ARG...]'] signatures: ['compare.Lt ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/lt] aliases: [/functions/lt]
--- ---
+8 -13
View File
@@ -1,23 +1,18 @@
--- ---
title: compare.Ne title: compare.Ne
linkTitle: ne
description: Returns the boolean truth of arg1 != arg2 && arg1 != arg3. description: Returns the boolean truth of arg1 != arg2 && arg1 != arg3.
categories: [functions] categories: []
keywords: [] keywords: []
menu: action:
docs:
parent: functions
function:
aliases: [ne] aliases: [ne]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
returnType: bool returnType: bool
signatures: ['compare.Ne ARG1 ARG2 [ARG...]'] signatures: ['compare.Ne ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/ne] aliases: [/functions/ne]
--- ---

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