diff options
Diffstat (limited to 'content/en/methods/page')
90 files changed, 4602 insertions, 0 deletions
diff --git a/content/en/methods/page/Aliases.md b/content/en/methods/page/Aliases.md new file mode 100644 index 000000000..15e73384b --- /dev/null +++ b/content/en/methods/page/Aliases.md @@ -0,0 +1,29 @@ +--- +title: Aliases +description: Returns the URL aliases as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: '[]string' + signatures: [PAGE.Aliases] +--- + +The `Aliases` method on a `Page` object returns the URL [aliases] as defined in front matter. + +For example: + +{{< code-toggle file=content/about.md fm=true >}} +title = 'About' +aliases = ['/old-url','/really-old-url'] +{{< /code-toggle >}} + +To list the aliases: + +```go-html-template +{{ range .Aliases }} + {{ . }} +{{ end }} +``` + +[aliases]: /content-management/urls/#aliases diff --git a/content/en/methods/page/AllTranslations.md b/content/en/methods/page/AllTranslations.md new file mode 100644 index 000000000..b9c156127 --- /dev/null +++ b/content/en/methods/page/AllTranslations.md @@ -0,0 +1,90 @@ +--- +title: AllTranslations +description: Returns all translation of the given page, including the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Translations + - methods/page/IsTranslated + - methods/page/TranslationKey + returnType: page.Pages + signatures: [PAGE.AllTranslations] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 + +[languages.fr] +contentDir = 'content/fr' +languageCode = 'fr-FR' +languageName = 'Français' +weight = 3 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── fr/ +│ ├── books/ +│ │ └── book-1.md +│ └── _index.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ with .AllTranslations }} + <ul> + {{ range . }} + {{ $lang := .Language.LanguageName}} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }} ({{ $lang }})</a></li> + {{ end }} + </ul> +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of each site: + +```html +<ul> + <li><a href="/books/book-1/">Book 1 (English)</a></li> + <li><a href="/de/books/book-1/">Book 1 (Deutsch)</a></li> + <li><a href="/fr/books/book-1/">Book 1 (Français)</a></li> +</ul> +``` + +On the "Book 2" page of the English and German sites, Hugo will render this: + +```html +<ul> + <li><a href="/books/book-1/">Book 1 (English)</a></li> + <li><a href="/de/books/book-1/">Book 1 (Deutsch)</a></li> +</ul> +``` diff --git a/content/en/methods/page/AlternativeOutputFormats.md b/content/en/methods/page/AlternativeOutputFormats.md new file mode 100644 index 000000000..b48d1adf4 --- /dev/null +++ b/content/en/methods/page/AlternativeOutputFormats.md @@ -0,0 +1,43 @@ +--- +title: AlternativeOutputFormats +description: Returns a slice of OutputFormat objects, excluding the current output format, each representing one of the output formats enabled for the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/OutputFormats + returnType: page.OutputFormats + signatures: [PAGE.AlternativeOutputFormats] +--- + +{{% include "methods/page/_common/output-format-definition.md" %}} + +The `AlternativeOutputFormats` method on a `Page` object returns a slice of `OutputFormat` objects, excluding the current output format, each representing one of the output formats enabled for the given page.. See [details](/templates/output-formats/). + +## Methods + +{{% include "methods/page/_common/output-format-methods.md" %}} + +## Example + +Generate a `link` element in the `<head>` of each page for each of the alternative output formats: + +```go-html-template +<head> + ... + {{ $title := printf "%s | %s" .Title site.Title }} + {{ if .IsHome }} + {{ $title = site.Title }} + {{ end }} + {{ range .AlternativeOutputFormats -}} + {{ printf `<link rel=%q type=%q href=%q title=%q>` .Rel .MediaType.Type .Permalink $title | safeHTML }} + {{ end }} + ... +</head> +``` + +On the site's home page, Hugo renders this to: + +```html +<link rel="alternate" type="application/rss+xml" href="https://example.org/index.xml" title="ABC Widgets, Inc."> +``` diff --git a/content/en/methods/page/Ancestors.md b/content/en/methods/page/Ancestors.md new file mode 100644 index 000000000..3bf36d9aa --- /dev/null +++ b/content/en/methods/page/Ancestors.md @@ -0,0 +1,87 @@ +--- +title: Ancestors +description: Returns a collection of Page objects, one for each ancestor section of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections + returnType: page.Pages + signatures: [PAGE.Ancestors] +--- + +{{< new-in 0.109.0 >}} + +{{% include "methods/page/_common/definition-of-section.md" %}} + +With this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- front matter: weight = 202311 +│ │ ├── auction-1.md +│ │ └── auction-2.md +│ ├── 2023-12/ +│ │ ├── _index.md <-- front matter: weight = 202312 +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- front matter: weight = 30 +│ ├── bidding.md +│ └── payment.md +├── books/ +│ ├── _index.md <-- front matter: weight = 10 +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── _index.md <-- front matter: weight = 20 +│ ├── film-1.md +│ └── film-2.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ range .Ancestors }} + <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> +{{ end }} +``` + +On the November 2023 auctions page, Hugo renders: + +```html +<a href="/auctions/2023-11/">Auctions in November 2023</a> +<a href="/auctions/">Auctions</a> +<a href="/">Home</a> +``` + +In the example above, notice that Hugo orders the ancestors from closest to furthest. This makes breadcrumb navigation simple: + +```go-html-template +<nav aria-label="breadcrumb" class="breadcrumb"> + <ol> + {{ range .Ancestors.Reverse }} + <li> + <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> + </li> + {{ end }} + <li class="active"> + <a aria-current="page" href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> + </li> + </ol> +</nav> +``` + +With some CSS, the code above renders something like this, where each breadcrumb links to its page: + +```text +Home > Auctions > Auctions in November 2023 > Auction 1 +``` diff --git a/content/en/methods/page/BundleType.md b/content/en/methods/page/BundleType.md new file mode 100644 index 000000000..77d1d72eb --- /dev/null +++ b/content/en/methods/page/BundleType.md @@ -0,0 +1,37 @@ +--- +title: BundleType +description: Returns the bundle type of the given page, or an empty string if the page is not a page bundle. +categories: [] +keywords: [] +action: + related: [] + returnType: files.ContentClass + signatures: [PAGE.BundleType] +--- + +A page bundle is a directory that encapsulates both content and associated [resources]. There are two types of page bundles: [leaf bundles] and [branch bundles]. See [details](/content-management/page-bundles/). + +The `BundleType` method on a `Page` object returns `branch` for branch bundles, `leaf` for leaf bundles, and an empty string if the page is not a page bundle. + +```text +content/ +├── films/ +│ ├── film-1/ +│ │ ├── a.jpg +│ │ └── index.md <-- leaf bundle +│ ├── _index.md <-- branch bundle +│ ├── b.jpg +│ ├── film-2.md +│ └── film-3.md +└── _index.md <-- branch bundle +``` + +To get the value within a template: + +```go-html-template +{{ .BundleType }} +``` + +[resources]: /getting-started/glossary/#resource +[leaf bundles]: /getting-started/glossary/#leaf-bundle +[branch bundles]: /getting-started/glossary/#branch-bundle diff --git a/content/en/methods/page/CodeOwners.md b/content/en/methods/page/CodeOwners.md new file mode 100644 index 000000000..ec7e5c8bf --- /dev/null +++ b/content/en/methods/page/CodeOwners.md @@ -0,0 +1,66 @@ +--- +title: CodeOwners +description: Returns of slice of code owners for the given page, derived from the CODEOWNERS file in the root of the project directory. +categories: [] +keywords: [] +action: + related: + - methods/page/GitInfo + returnType: '[]string' + signatures: [PAGE.CodeOwners] +--- + +GitHub and GitLab support CODEOWNERS files. This file specifies the users responsible for developing and maintaining software and documentation. This definition can apply to the entire repository, specific directories, or to individual files. To learn more: + +- [GitHub CODEOWNERS documentation] +- [GitLab CODEOWNERS documentation] + +Use the `CodeOwners` method on a `Page` object to determine the code owners for the given page. + +[GitHub CODEOWNERS documentation]: https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners +[GitLab CODEOWNERS documentation]: https://docs.gitlab.com/ee/user/project/code_owners.html + +To use the `CodeOwners` method you must enable access to your local Git repository: + +{{< code-toggle file=hugo >}} +enableGitInfo = true +{{< /code-toggle >}} + +Consider this project structure: + +```text +hugo-testing/ +├── content/ +│ ├── books/ +│ │ └── les-miserables.md +│ └── films/ +│ └── the-hunchback-of-notre-dame.md +└── CODEOWNERS +``` + +And this CODEOWNERS file: + +```text +* @jdoe +/content/books/ @tjones +/content/films/ @mrichards @rsmith +``` + +The table below shows the slice of code owners returned for each file: + +Path|Code owners +:--|:-- +`books/les-miserables.md`|`[@tjones]` +`films/the-hunchback-of-notre-dame.md`|`[@mrichards @rsmith]` + +Render the code owners for each content page: + +```go-html-template +{{ range .CodeOwners }} + {{ . }} +{{ end }} +``` + +Combine this method with [`resources.GetRemote`] to retrieve names and avatars from your Git provider by querying their API. + +[`resources.GetRemote`]: functions/resources/getremote diff --git a/content/en/methods/page/Content.md b/content/en/methods/page/Content.md new file mode 100644 index 000000000..40a057f02 --- /dev/null +++ b/content/en/methods/page/Content.md @@ -0,0 +1,22 @@ +--- +title: Content +description: Returns the rendered content of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/RawContent + - methods/page/Plain + - methods/page/PlainWords + - methods/page/RenderShortcodes + returnType: template.HTML + signatures: [PAGE.Content] +--- + +The `Content` method on a `Page` object renders markdown and shortcodes to HTML. The content does not include front matter. + +[shortcodes]: /getting-started/glossary/#shortcode + +```go-html-template +{{ .Content }} +``` diff --git a/content/en/methods/page/CurrentSection.md b/content/en/methods/page/CurrentSection.md new file mode 100644 index 000000000..03cb9eb3d --- /dev/null +++ b/content/en/methods/page/CurrentSection.md @@ -0,0 +1,60 @@ +--- +title: CurrentSection +description: Returns the Page object of the section in which the given page resides. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections + returnType: hugolib.pageState + signatures: [PAGE.CurrentSection] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +The current section of a [section] page, [taxonomy] page, [term] page, or the home page, is itself. + +[section]: /getting-started/glossary/#section +[taxonomy]: /getting-started/glossary/#taxonomy +[term]: /getting-started/glossary/#term +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- current section: 2023-11 +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- current section: 2023-11 +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- current section: auctions +│ ├── bidding.md +│ └── payment.md <-- current section: auctions +├── books/ +│ ├── _index.md <-- current section: books +│ ├── book-1.md +│ └── book-2.md <-- current section: books +├── films/ +│ ├── _index.md <-- current section: films +│ ├── film-1.md +│ └── film-2.md <-- current section: films +└── _index.md <-- current section: home +``` + +To create a link to the current section page: + +```go-html-template +<a href="{{ .CurrentSection.RelPermalink }}">{{ .CurrentSection.LinkTitle }}</a> +``` diff --git a/content/en/methods/page/Data.md b/content/en/methods/page/Data.md new file mode 100644 index 000000000..4eccde6ff --- /dev/null +++ b/content/en/methods/page/Data.md @@ -0,0 +1,111 @@ +--- +title: Data +description: Returns a unique data object for each page kind. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Data + signatures: [PAGE.Data] +toc: true +--- + +The `Data` method on a `Page` object returns a unique data object for each [page kind]. + +[page kind]: /getting-started/glossary/#page-kind + +{{% note %}} +The `Data` method is only useful within [taxonomy] and [term] templates. + +Themes that are not actively maintained may still use `.Data.Pages` in list templates. Although that syntax remains functional, use one of these methods instead: [`Pages`], [`RegularPages`], or [`RegularPagesRecursive`] + +[`Pages`]: /methods/page/pages/ +[`RegularPages`]: /methods/page/regularpages/ +[`RegularPagesRecursive`]: /methods/page/regularpagesrecursive/ +[term]: /getting-started/glossary/#term +[taxonomy]: /getting-started/glossary/#taxonomy +{{% /note %}} + +The examples that follow are based on this site configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +genre = 'genres' +author = 'authors' +{{< /code-toggle >}} + +And this content structure: + +```text +content/ +├── books/ +│ ├── and-then-there-were-none.md --> genres: suspense +│ ├── death-on-the-nile.md --> genres: suspense +│ └── jamaica-inn.md --> genres: suspense, romance +│ └── pride-and-prejudice.md --> genres: romance +└── _index.md +``` + +## In a taxonomy template + +Use these methods on the `Data` object within a taxonomy template. + +Singular +: (`string`) Returns the singular name of the taxonomy. + +```go-html-template +{{ .Data.Singular }} → genre +``` + +Plural +: (`string`) Returns the plural name of the taxonomy. + +```go-html-template +{{ .Data.Plural }} → genres +``` + +Terms +: (`page.Taxonomy`) Returns the taxonomy object, consisting of a map of terms and the [weighted pages] associated with each term. + +```go-html-template +{{ $taxonomyObject := .Data.Terms }} +``` + +{{% note %}} +Once you have captured the taxonomy object, use any of the [taxonomy methods] to sort, count, or capture a subset of its weighted pages. + +[taxonomy methods]: /methods/taxonomy +{{% /note %}} + +Learn more about [taxonomy templates]. + +## In a term template + +Use these methods on the `Data` object within a term template. + +Singular +: (`string`) Returns the singular name of the taxonomy. + +```go-html-template +{{ .Data.Singular }} → genre +``` + +Plural +: (`string`) Returns the plural name of the taxonomy. + +```go-html-template +{{ .Data.Plural }} → genres +``` + +Term +: (`string`) Returns the name of the term. + +```go-html-template +{{ .Data.Term }} → suspense +``` + +Learn more about [term templates]. + +[taxonomy templates]: /templates/taxonomy-templates/ +[term templates]: /templates/taxonomy-templates/ +[weighted pages]: /getting-started/glossary/#weighted-page diff --git a/content/en/methods/page/Date.md b/content/en/methods/page/Date.md new file mode 100644 index 000000000..83192f94c --- /dev/null +++ b/content/en/methods/page/Date.md @@ -0,0 +1,39 @@ +--- +title: Date +description: Returns the date of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/ExpiryDate + - methods/page/LastMod + - methods/page/PublishDate + returnType: time.Time + signatures: [PAGE.Date] +--- + +Set the date in front matter: + +{{< code-toggle file=content/news/article-1.md fm=true >}} +title = 'Article 1' +date = 2023-10-19T00:40:04-07:00 +{{< /code-toggle >}} + +{{% note %}} +The date field in front matter is often considered to be the creation date, You can change its meaning, and its effect on your site, in the site configuration. See [details]. + +[details]: /getting-started/configuration/#configure-dates +{{% /note %}} + +The date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods]. + +```go-html-template +{{ .Date | time.Format ":date_medium" }} → Oct 19, 2023 +``` + +In the example above we explicitly set the date in front matter. With Hugo's default configuration, the `Date` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the date is not defined in front matter. See [details]. + +[`time.Format`]: /functions/time/format +[details]: /getting-started/configuration/#configure-dates +[time methods]: /methods/time +[time.Time]: https://pkg.go.dev/time#Time diff --git a/content/en/methods/page/Description.md b/content/en/methods/page/Description.md new file mode 100644 index 000000000..fbb43b8b5 --- /dev/null +++ b/content/en/methods/page/Description.md @@ -0,0 +1,28 @@ +--- +title: Description +description: Returns the description of the given page as defined in front matter. +categories: [] +keywords: [] +action: + related: + - methods/page/Summary + returnType: string + signatures: [PAGE.Description] +--- + +Conceptually different that a [content summary], a page description is typically used in metadata about the page. + +{{< code-toggle file=content/recipes/sushi.md fm=true >}} +title = 'How to make spicy tuna hand rolls' +description = 'Instructions for making spicy tuna hand rolls.' +{{< /code-toggle >}} + +{{< code file=layouts/baseof.html >}} +<head> + ... + <meta name="description" content="{{ .Description }}"> + ... +</head> +{{< /code >}} + +[content summary]: /content-management/summaries diff --git a/content/en/methods/page/Draft.md b/content/en/methods/page/Draft.md new file mode 100644 index 000000000..fd55a9bc9 --- /dev/null +++ b/content/en/methods/page/Draft.md @@ -0,0 +1,21 @@ +--- +title: Draft +description: Reports whether the given page is a draft as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [PAGE.Draft] +--- + +By default, Hugo does not publish draft pages when you build your site. To include draft pages when you build your site, use the `--buildDrafts` command line flag. + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'Post 1' +draft = true +{{< /code-toggle >}} + +```go-html-template +{{ .Draft }} → true +``` diff --git a/content/en/methods/page/Eq.md b/content/en/methods/page/Eq.md new file mode 100644 index 000000000..1be416295 --- /dev/null +++ b/content/en/methods/page/Eq.md @@ -0,0 +1,21 @@ +--- +title: Eq +description: Reports whether two Page objects are equal. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [PAGE1.Eq PAGE2] +--- + +In this contrived example from a single page template, we list all pages in the current section except for the current page. + +```go-html-template +{{ $currentPage := . }} +{{ range .CurrentSection.Pages }} + {{ if not (.Eq $currentPage) }} + <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> + {{ end }} +{{ end }} +``` diff --git a/content/en/methods/page/ExpiryDate.md b/content/en/methods/page/ExpiryDate.md new file mode 100644 index 000000000..353546449 --- /dev/null +++ b/content/en/methods/page/ExpiryDate.md @@ -0,0 +1,35 @@ +--- +title: ExpiryDate +description: Returns the expiry date of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Date + - methods/page/LastMod + - methods/page/PublishDate + returnType: time.Time + signatures: [PAGE.ExpiryDate] +--- + +By default, Hugo excludes expired pages when building your site. To include expired pages, use the `--buildExpired` command line flag. + +Set the expiry date in front matter: + +{{< code-toggle file=content/news/article-1.md fm=true >}} +title = 'Article 1' +expiryDate = 2024-10-19T00:32:13-07:00 +{{< /code-toggle >}} + +The expiry date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods]. + +```go-html-template +{{ .ExpiryDate | time.Format ":date_medium" }} → Oct 19, 2024 +``` + +In the example above we explicitly set the expiry date in front matter. With Hugo's default configuration, the `ExpiryDate` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the expiry date is not defined in front matter. See [details]. + +[`time.Format`]: /functions/time/format +[details]: /getting-started/configuration/#configure-dates +[time methods]: /methods/time +[time.Time]: https://pkg.go.dev/time#Time diff --git a/content/en/methods/page/File.md b/content/en/methods/page/File.md new file mode 100644 index 000000000..c39d1a64d --- /dev/null +++ b/content/en/methods/page/File.md @@ -0,0 +1,180 @@ +--- +title: File +description: For pages backed by a file, returns file information for the given page. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.fileInfo + signatures: [PAGE.File] +toc: true +--- + +By default, not all pages are backed by a file, including top level [section] pages, [taxonomy] pages, and [term] pages. By definition, you cannot retrieve file information when the file does not exist. + +To back one of the pages above with a file, create an _index.md file in the corresponding directory. For example: + +```text +content/ +└── books/ + ├── _index.md <-- the top level section page + ├── book-1.md + └── book-2.md +``` + +Code defensively by verifying file existence as shown in each of the examples below. + +## Methods + +{{% note %}} +The path separators (slash or backslash) in `Path`, `Dir`, and `Filename` depend on the operating system. +{{% /note %}} + +BaseFileName +: (`string`) The file name, excluding the extension. + +```go-html-template +{{ with .File }} + {{ .BaseFileName }} +{{ end }} +``` + +ContentBaseName +: (`string`) If the page is a branch or leaf bundle, the name of the containing directory, else the `TranslationBaseName`. + +```go-html-template +{{ with .File }} + {{ .ContentBaseName }} +{{ end }} +``` + +Dir +: (`string`) The file path, excluding the file name, relative to the `content` directory. + +```go-html-template +{{ with .File }} + {{ .Dir }} +{{ end }} +``` + +Ext +: (`string`) The file extension. + +```go-html-template +{{ with .File }} + {{ .Ext }} +{{ end }} +``` + +Filename +: (`string`) The absolute file path. + +```go-html-template +{{ with .File }} + {{ .Filename }} +{{ end }} +``` + +Lang +: (`string`) The language associated with the given file. + +```go-html-template +{{ with .File }} + {{ .Lang }} +{{ end }} +``` + +LogicalName +: (`string`) The file name. + +```go-html-template +{{ with .File }} + {{ .LogicalName }} +{{ end }} +``` + +Path +: (`string`) The file path, relative to the `content` directory. + +```go-html-template +{{ with .File }} + {{ .Path }} +{{ end }} +``` + +TranslationBaseName +: (`string`) The file name, excluding the extension and language identifier. + +```go-html-template +{{ with .File }} + {{ .TranslationBaseName }} +{{ end }} +``` + +UniqueID +: (`string`) The MD5 hash of `.File.Path`. + +```go-html-template +{{ with .File }} + {{ .UniqueID }} +{{ end }} +``` + +## Examples + +Consider this content structure in a multilingual project: + +```text +content/ +├── news/ +│ ├── b/ +│ │ ├── index.de.md <-- leaf bundle +│ │ └── index.en.md <-- leaf bundle +│ ├── a.de.md <-- regular content +│ ├── a.en.md <-- regular content +│ ├── _index.de.md <-- branch bundle +│ └── _index.en.md <-- branch bundle +├── _index.de.md +└── _index.en.md +``` + +With the English language site: + + |regular content|leaf bundle|branch bundle +:--|:--|:--|:-- +BaseFileName|a.en|index.en|_index.en +ContentBaseName|a|b|news +Dir|news/|news/b/|news/ +Ext|md|md|md +Filename|/home/user/...|/home/user/...|/home/user/... +Lang|en|en|en +LogicalName|a.en.md|index.en.md|_index.en.md +Path|news/a.en.md|news/b/index.en.md|news/_index.en.md +TranslationBaseName|a|index|_index +UniqueID|15be14b...|186868f...|7d9159d... + +## Defensive coding + +Some of the pages on a site may not be backed by a file. For example: + +- Top level section pages +- Taxonomy pages +- Term pages + +Without a backing file, Hugo will throw a warning if you attempt to access a `.File` property. For example: + +```text +WARN .File.ContentBaseName on zero object. Wrap it in if or with... +``` + +To code defensively, first check for file existence: + +```go-html-template +{{ with .File }} + {{ .ContentBaseName }} +{{ end }} +``` + +[section]: /getting-started/glossary/#section +[taxonomy]: /getting-started/glossary/#taxonomy +[term]: /getting-started/glossary/#term diff --git a/content/en/methods/page/FirstSection.md b/content/en/methods/page/FirstSection.md new file mode 100644 index 000000000..f757aa2d2 --- /dev/null +++ b/content/en/methods/page/FirstSection.md @@ -0,0 +1,56 @@ +--- +title: FirstSection +description: Returns the Page object of the top level section of which the given page is a descendant. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections + returnType: hugolib.pageState + signatures: [PAGE.FirstSection] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +When called on the home page, the `FirstSection` method returns the `Page` object of the home page itself. +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- first section: auctions +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- first section: auctions +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- first section: auctions +│ ├── bidding.md +│ └── payment.md <-- first section: auctions +├── books/ +│ ├── _index.md <-- first section: books +│ ├── book-1.md +│ └── book-2.md <-- first section: books +├── films/ +│ ├── _index.md <-- first section: films +│ ├── film-1.md +│ └── film-2.md <-- first section: films +└── _index.md <-- first section: home +``` + +To link to the top level section of which the current page is a descendant: + +```go-html-template +<a href="{{ .FirstSection.RelPermalink }}">{{ .FirstSection.LinkTitle }}</a> +``` diff --git a/content/en/methods/page/Fragments.md b/content/en/methods/page/Fragments.md new file mode 100644 index 000000000..bae1c7d03 --- /dev/null +++ b/content/en/methods/page/Fragments.md @@ -0,0 +1,106 @@ +--- +title: Fragments +description: Returns a data structure of the fragments in the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/TableOfContents + returnType: tableofcontents.Fragments + signatures: [PAGE.Fragments] +toc: true +--- + +{{< new-in 0.111.0 >}} + +In a URL, whether absolute or relative, the [fragment] links to an `id` attribute of an HTML element on the page. + +```text +/articles/article-1#section-2 +------------------- --------- + path fragment +``` + +Hugo assigns an `id` attribute to each markdown [ATX] and [setext] heading within the page content. You can override the `id` with a [markdown attribute] as needed. This creates the relationship between an entry in the [table of contents] (TOC) and a heading on the page. + +Use the `Fragments` method on a `Page` object to create a table of contents with the `Fragments.ToHTML` method, or by [walking] the `Fragments.Map` data structure. + +## Methods + +Headings +: (`map`) A nested map of all headings on the page. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +<pre>{{ .Fragments.Headings | jsonify (dict "indent" " ") }}</pre> +``` + +HeadingsMap +: (`slice`) A slice of maps of all headings on the page, with first-level keys for each heading. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +<pre>{{ .Fragments.HeadingsMap | jsonify (dict "indent" " ") }}</pre> +``` + +Identifiers +: (`slice`) A slice containing the `id` of each heading on the page. To inspect the data structure: + +```go-html-template +<pre>{{ .Fragments.Identifiers | jsonify (dict "indent" " ") }}</pre> +``` + +Identifiers.Contains ID +: (`bool`) Reports whether one or more headings on the page has the given `id` attribute, useful for validating fragments within a link [render hook]. + +```go-html-template +{{ .Fragments.Identifiers.Contains "section-2" }} → true +``` + +Identifiers.Count ID +: (`int`) The number of headings on a page with the given `id` attribute, useful for detecting duplicates. + +```go-html-template +{{ .Fragments.Identifiers.Count "section-2" }} → 1 +``` + +ToHTML +: (`template.HTML`) Returns a TOC as a nested list, either ordered or unordered, identical to the HTML returned by the [`TableOfContents`] method. This method take three arguments: the start level (`int`), the end level (`int`), and a boolean (`true` to return an ordered list, `false` to return an unordered list). + +Use this method when you want to control the start level, end level, or list type independently from the table of contents settings in your site configuration. + +```go-html-template +{{ $startLevel := 2 }} +{{ $endLevel := 3 }} +{{ $ordered := true }} +{{ .Fragments.ToHTML $startLevel $endLevel $ordered }} +``` + +Hugo renders this to: + +```html +<nav id="TableOfContents"> + <ol> + <li><a href="#section-1">Section 1</a> + <ol> + <li><a href="#section-11">Section 1.1</a></li> + <li><a href="#section-12">Section 1.2</a></li> + </ol> + </li> + <li><a href="#section-2">Section 2</a></li> + </ol> +</nav> +``` + +{{% note %}} +It is safe to use the `Fragments` methods within a render hook, even for the current page. + +When using the `Fragments` methods within a shortcode, call the shortcode using the `{{</* */>}}` notation. If you use the `{{%/* */%}}` notation, the rendered shortcode is included in the creation of the fragments map, resulting in a circular loop. +{{% /note %}} + +[atx]: https://spec.commonmark.org/0.30/#atx-headings +[fragment]: /getting-started/glossary/#fragment +[markdown attribute]: /getting-started/glossary/#markdown-attribute +[setext]: https://spec.commonmark.org/0.30/#setext-headings +[table of contents]: /methods/page/tableofcontents +[walking]: /getting-started/glossary/#walk +[`tableofcontents`]: /methods/page/tableofcontents +[render hook]: /getting-started/glossary/#render-hook diff --git a/content/en/methods/page/FuzzyWordCount.md b/content/en/methods/page/FuzzyWordCount.md new file mode 100644 index 000000000..600ad48d5 --- /dev/null +++ b/content/en/methods/page/FuzzyWordCount.md @@ -0,0 +1,20 @@ +--- +title: FuzzyWordCount +description: Returns the number of words in the content of the given page, rounded up to the nearest multiple of 100. +categories: [] +keywords: [] +action: + related: + - methods/page/WordCount + - methods/page/ReadingTime + returnType: int + signatures: [PAGE.FuzzyWordCount] +--- + +```go-html-template +{{ .FuzzyWordCount }} → 200 +``` + +To get the exact word count, use the [`WordCount`] method. + +[`WordCount`]: /methods/page/wordcount diff --git a/content/en/methods/page/GetPage.md b/content/en/methods/page/GetPage.md new file mode 100644 index 000000000..ed072932a --- /dev/null +++ b/content/en/methods/page/GetPage.md @@ -0,0 +1,65 @@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +action: + related: + - methods/site/GetPage + returnType: hugolib.pageState + signatures: [PAGE.GetPage PATH] +aliases: [/functions/getpage] +--- + +The `GetPage` method is also available on a `Site` object. See [details]. + +[details]: /methods/site/getpage + +When using the `GetPage` method on the `Page` object, specify a path relative to the current directory or relative to the content directory. + +If Hugo cannot resolve the path to a page, the method returns nil. If the path is ambiguous, Hugo throws an error and fails the build. + +Consider this content structure: + +```text +content/ +├── works/ +│ ├── paintings/ +│ │ ├── _index.md +│ │ ├── starry-night.md +│ │ └── the-mona-lisa.md +│ ├── sculptures/ +│ │ ├── _index.md +│ │ ├── david.md +│ │ └── the-thinker.md +│ └── _index.md +└── _index.md +``` + +The examples below depict the result of rendering works/paintings/the-mona-list.md with a single page template: + +```go-html-template +{{ with .GetPage "starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "./starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "../paintings/starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "../sculptures/david" }} + {{ .Title }} → David +{{ end }} + +{{ with .GetPage "/works/sculptures/david" }} + {{ .Title }} → David +{{ end }} +``` diff --git a/content/en/methods/page/GetTerms.md b/content/en/methods/page/GetTerms.md new file mode 100644 index 000000000..3020e4c2e --- /dev/null +++ b/content/en/methods/page/GetTerms.md @@ -0,0 +1,41 @@ +--- +title: GetTerms +description: Returns a collection of term pages for terms defined on the given page in the given taxonomy, ordered according to the sequence in which they appear in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGE.GetTerms TAXONOMY] +--- + +Given this front matter: + +{{< code-toggle file=content/books/les-miserables.md fm=true >}} +title = 'Les Misérables' +tags = ['historical','classic','fiction'] +{{< /code-toggle >}} + +This template code: + +```go-html-template +{{ with .GetTerms "tags" }} + <p>Tags</p> + <ul> + {{ range . }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +Is rendered to: + +```html +<p>Tags</p> +<ul> + <li><a href="/tags/historical/">historical</a></li> + <li><a href="/tags/classic/">classic</a></li> + <li><a href="/tags/fiction/">fiction</a></li> +</ul> +``` diff --git a/content/en/methods/page/GitInfo.md b/content/en/methods/page/GitInfo.md new file mode 100644 index 000000000..88137614c --- /dev/null +++ b/content/en/methods/page/GitInfo.md @@ -0,0 +1,130 @@ +--- +title: GitInfo +description: Returns Git information related to the last commit of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/CodeOwners + returnType: source.GitInfo + signatures: [PAGE.GitInfo] +toc: true +--- + +The `GitInfo` method on a `Page` object returns an object with additional methods. + +{{% note %}} +Hugo's Git integration is performant, but may increase build times on large sites. +{{% /note %}} + +## Prerequisites + +Install [Git], create a repository, and commit your project files. + +You must also allow Hugo to access your repository. In your site configuration: + +{{< code-toggle file=hugo >}} +enableGitInfo = true +{{< /code-toggle >}} + +Alternatively, use the command line flag when building your site: + +```sh +hugo --enableGitInfo +``` + +{{% note %}} +When you set `enableGitInto` to `true`, or enable the feature with the command line flag, the last modification date for each content page will be the Author Date of the last commit for that file. + +This is configurable. See [details]. + +[details]: /getting-started/configuration/#configure-dates +{{% /note %}} + +## Methods + +AbbreviatedHash +: (`string`) The abbreviated commit hash. + +```go-html-template +{{ with .GitInfo }} + {{ .AbbreviatedHash }} → aab9ec0b3 +{{ end }} +``` + +AuthorDate +: (`time.Time`) The author date. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorDate.Format "2006-01-02" }} → 2023-10-09 +{{ end }} +``` + +AuthorEmail +: (`string`) The author's email address, respecting [gitmailmap]. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorEmail }} → [email protected] +{{ end }} +``` + +AuthorName +: (`string`) The author's name, respecting [gitmailmap]. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorName }} → John Smith +{{ end }} +``` + +Hash +: (`string`) The commit hash. + +```go-html-template +{{ with .GitInfo }} + {{ .Hash }} → aab9ec0b31ebac916a1468c4c9c305f2bebf78d4 +{{ end }} +``` + +Subject +: (`string`) The commit message subject. + +```go-html-template +{{ with .GitInfo }} + {{ .Subject }} → Add tutorials +{{ end }} +``` + +## Last modified date + +By default, when `enableGitInfo` is `true`, the `Lastmod` method on a `Page` object returns the Git AuthorDate of the last commit that included the file. + +You can change this behavior in your [site configuration]. + +[git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[gitmailmap]: https://git-scm.com/docs/gitmailmap +[site configuration]: /getting-started/configuration/#configure-front-matter + +## Hosting considerations + +When hosting your site in a CI/CD environment, the step that clones your project repository must perform a deep clone. If the clone is shallow, the Git information for a given file may not be accurate---it may reflect the most recent repository commit, not the commit that last modified the file. + +Some providers perform deep clones by default, others allow you to configure the clone depth, and some providers only perform shallow clones. + +Hosting service | Default clone depth | Configurable +:-- | :-- | :-- +Cloudflare Pages | Shallow | Yes [^CFP] +DigitalOcean App Platform | Deep | N/A +GitHub Pages | Shallow | Yes [^GHP] +GitLab Pages | Shallow | Yes [^GLP] +Netlify | Deep | N/A +Render | Shallow | No +Vercel | Shallow | No + +[^CFP]: To configure a Cloudflare Pages site for deep cloning, preface the site's normal Hugo build command with `git fetch --unshallow &&` (*e.g.*, `git fetch --unshallow && hugo`). + +[^GHP]: You can configure the GitHub Action to do a deep clone by specifying `fetch-depth: 0` in the applicable "checkout" step of your workflow file, as shown in the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-github/#procedure). + +[^GLP]: You can configure the GitLab Runner's clone depth [as explained in the GitLab documentation](https://docs.gitlab.com/ee/ci/large_repositories/#shallow-cloning); see also the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-gitlab/#configure-gitlab-cicd). diff --git a/content/en/methods/page/HasMenuCurrent.md b/content/en/methods/page/HasMenuCurrent.md new file mode 100644 index 000000000..68b645905 --- /dev/null +++ b/content/en/methods/page/HasMenuCurrent.md @@ -0,0 +1,31 @@ +--- +title: HasMenuCurrent +description: Reports whether the given page object matches the page object associated with one of the child menu entries under the given menu entry in the given menu. +categories: [] +keywords: [] +action: + related: + - methods/page/IsMenuCurrent + returnType: bool + signatures: [PAGE.HasMenuCurrent MENU MENUENTRY] +aliases: [/functions/hasmenucurrent] +--- + +If the page object associated with the menu entry is a section, this method also returns `true` for any descendant of that section. + +```go-html-template +{{ $currentPage := . }} +{{ range site.Menus.main }} + {{ if $currentPage.IsMenuCurrent .Menu . }} + <a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a> + {{ else if $currentPage.HasMenuCurrent .Menu . }} + <a class="ancestor" aria-current="true" href="{{ .URL }}">{{ .Name }}</a> + {{ else }} + <a href="{{ .URL }}">{{ .Name }}</a> + {{ end }} +{{ end }} +``` + +See [menu templates] for a complete example. + +[menu templates]: /templates/menu-templates/#example diff --git a/content/en/methods/page/HasShortcode.md b/content/en/methods/page/HasShortcode.md new file mode 100644 index 000000000..81268ecba --- /dev/null +++ b/content/en/methods/page/HasShortcode.md @@ -0,0 +1,50 @@ +--- +title: HasShortcode +description: Reports whether the given shortcode is called by the given page. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [PAGE.HasShortcode NAME] +--- + +By example, let's use [MathJax] to render a LaTeX mathematical expression: + +[MathJax]: https://www.mathjax.org/ + +{{< code file=contents/physics/lesson-1.md lang=markdown >}} +Albert Einstein’s theory of special relativity expresses +the fact that mass and energy are the same physical entity +and can be changed into each other. + +{{</* math */>}} +$$ +E=mc^2 +$$ +{{</* /math */>}} + +In the equation, the increased relativistic mass (m) of a +body times the speed of light squared (c2) is equal to +the kinetic energy (E) of that body. +{{< /code >}} + +The shortcode is simple: + +{{< code file=layouts/shortcodes/math.html >}} +{{ trim .Inner "\r\n" }} +{{< /code >}} + +Now we can selectively load the required CSS and JavaScript on pages that call the "math" shortcode: + + +{{< code file=layouts/baseof.html >}} +<head> + ... + {{ if .HasShortcode "math" }} + <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> + <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> + {{ end }} + ... +</head> +{{< /code >}} diff --git a/content/en/methods/page/HeadingsFiltered.md b/content/en/methods/page/HeadingsFiltered.md new file mode 100644 index 000000000..a39c48da1 --- /dev/null +++ b/content/en/methods/page/HeadingsFiltered.md @@ -0,0 +1,18 @@ +--- +title: HeadingsFiltered +description: Returns a slice of headings for each page related to the given page. +categories: [] +keywords: [] +action: + related: + - methods/pages/Related + - methods/page/Fragments + returnType: tableofcontents.Headings + signatures: [PAGE.HeadingsFiltered] +--- + +Use in conjunction with the [`Related`] method on a [`Pages`] object. See [details]. + +[`Pages`]: /methods/pages/ +[`Related`]: /methods/pages/related +[details]: /content-management/related/#index-content-headings-in-related-content diff --git a/content/en/methods/page/InSection.md b/content/en/methods/page/InSection.md new file mode 100644 index 000000000..b98fbc808 --- /dev/null +++ b/content/en/methods/page/InSection.md @@ -0,0 +1,102 @@ +--- +title: InSection +description: Reports whether the given page is in the given section. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections + returnType: bool + signatures: [PAGE.InSection SECTION] +toc: true +--- + +The `InSection` method on a page object reports whether the given page is in the given section. Note that the method returns `true` when comparing a page to a sibling. + +{{% include "methods/page/_common/definition-of-section.md" %}} + +With this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md +│ │ ├── auction-1.md +│ │ └── auction-2.md +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md +│ ├── bidding.md +│ └── payment.md +└── _index.md +``` + +When rendering the "auction-1" page: + +```go-html-template +{{ with .Site.GetPage "/" }} + {{ $.InSection . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions" }} + {{ $.InSection . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11" }} + {{ $.InSection . }} → true +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11/auction-2" }} + {{ $.InSection . }} → true +{{ end }} +``` + +In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting: + +```go-html-template +{{ $path := "/auctions/2023-11" }} +{{ with .Site.GetPage $path }} + {{ $.InSection . }} → true +{{ else }} + {{ errorf "Unable to find the section with path %s" $path }} +{{ end }} + ``` + +## Understanding context + +Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax: + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ .InSection . }} → true +{{ end }} +``` + +The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself. + +{{% note %}} +Use the `$` to get the context passed into the template. +{{% /note %}} + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.InSection . }} → true +{{ end }} +``` + +{{% note %}} +Gaining a thorough understanding of context is critical for anyone writing template code. +{{% /note %}} + +[context]: /getting-started/glossary/#context +[`with`]: /functions/go-template/with +[`else`]: /functions/go-template/else diff --git a/content/en/methods/page/IsAncestor.md b/content/en/methods/page/IsAncestor.md new file mode 100644 index 000000000..ca23c0868 --- /dev/null +++ b/content/en/methods/page/IsAncestor.md @@ -0,0 +1,100 @@ +--- +title: IsAncestor +description: Reports whether PAGE1 in an ancestor of PAGE2. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections + returnType: bool + signatures: [PAGE1.IsAncestor PAGE2] +toc: true +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +With this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md +│ │ ├── auction-1.md +│ │ └── auction-2.md +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md +│ ├── bidding.md +│ └── payment.md +└── _index.md +``` + +When rendering the "auctions" page: + +```go-html-template +{{ with .Site.GetPage "/" }} + {{ $.IsAncestor . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions" }} + {{ $.IsAncestor . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11" }} + {{ $.IsAncestor . }} → true +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11/auction-2" }} + {{ $.IsAncestor . }} → true +{{ end }} +``` + +In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting: + +```go-html-template +{{ $path := "/auctions/2023-11" }} +{{ with .Site.GetPage $path }} + {{ $.IsAncestor . }} → true +{{ else }} + {{ errorf "Unable to find the section with path %s" $path }} +{{ end }} + ``` + +## Understanding context + +Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax: + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ .IsAncestor . }} → true +{{ end }} +``` + +The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself. + +{{% note %}} +Use the `$` to get the context passed into the template. +{{% /note %}} + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.IsAncestor . }} → true +{{ end }} +``` + +{{% note %}} +Gaining a thorough understanding of context is critical for anyone writing template code. +{{% /note %}} + +[context]: /getting-started/glossary/#context +[`with`]: /functions/go-template/with +[`else`]: /functions/go-template/else diff --git a/content/en/methods/page/IsDescendant.md b/content/en/methods/page/IsDescendant.md new file mode 100644 index 000000000..f1042564e --- /dev/null +++ b/content/en/methods/page/IsDescendant.md @@ -0,0 +1,99 @@ +--- +title: IsDescendant +description: Reports whether PAGE1 in a descendant of PAGE2. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/Parent + - methods/page/Sections + returnType: bool + signatures: [PAGE1.IsDescendant PAGE2] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +With this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md +│ │ ├── auction-1.md +│ │ └── auction-2.md +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md +│ ├── bidding.md +│ └── payment.md +└── _index.md +``` + +When rendering the "auctions" page: + +```go-html-template +{{ with .Site.GetPage "/" }} + {{ $.IsDescendant . }} → true +{{ end }} + +{{ with .Site.GetPage "/auctions" }} + {{ $.IsDescendant . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11" }} + {{ $.IsDescendant . }} → false +{{ end }} + +{{ with .Site.GetPage "/auctions/2023-11/auction-2" }} + {{ $.IsDescendant . }} → false +{{ end }} +``` + +In the examples above we are coding defensively using the [`with`] statement, returning nothing if the page does not exist. By adding an [`else`] clause we can do some error reporting: + +```go-html-template +{{ $path := "/auctions/2023-11" }} +{{ with .Site.GetPage $path }} + {{ $.IsDescendant . }} → true +{{ else }} + {{ errorf "Unable to find the section with path %s" $path }} +{{ end }} + ``` + +## Understanding context + +Inside of the `with` block, the [context] (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax: + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ .IsDescendant . }} → true +{{ end }} +``` + +The result would be wrong when rendering the "auction-1" page because we are comparing the section page to itself. + +{{% note %}} +Use the `$` to get the context passed into the template. +{{% /note %}} + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.IsDescendant . }} → true +{{ end }} +``` + +{{% note %}} +Gaining a thorough understanding of context is critical for anyone writing template code. +{{% /note %}} + +[context]: /getting-started/glossary/#context +[`with`]: /functions/go-template/with +[`else`]: /functions/go-template/else diff --git a/content/en/methods/page/IsHome.md b/content/en/methods/page/IsHome.md new file mode 100644 index 000000000..b688f88c0 --- /dev/null +++ b/content/en/methods/page/IsHome.md @@ -0,0 +1,31 @@ +--- +title: IsHome +description: Reports whether the given page is the home page. +categories: [] +keywords: [] +action: + related: + - methods/page/IsNode + - methods/page/IsPage + - methods/page/IsSection + returnType: bool + signatures: [PAGE.IsHome] +--- + +The `IsHome` method on a `Page` object returns `true` if the [page kind] is `home`. + +```text +content/ +├── books/ +│ ├── book-1/ +│ │ └── index.md <-- kind = page +│ ├── book-2.md <-- kind = page +│ └── _index.md <-- kind = section +└── _index.md <-- kind = home +``` + +```go-html-template +{{ .IsHome }} +``` + +[page kind]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/IsMenuCurrent.md b/content/en/methods/page/IsMenuCurrent.md new file mode 100644 index 000000000..61283fd8b --- /dev/null +++ b/content/en/methods/page/IsMenuCurrent.md @@ -0,0 +1,29 @@ +--- +title: IsMenuCurrent +description: Reports whether the given page object matches the page object associated with the given menu entry in the given menu. +categories: [] +keywords: [] +action: + related: + - methods/page/HasMenuCurrent + returnType: bool + signatures: [PAGE.IsMenuCurrent MENU MENUENTRY] +aliases: [/functions/ismenucurrent] +--- + +```go-html-template +{{ $currentPage := . }} +{{ range site.Menus.main }} + {{ if $currentPage.IsMenuCurrent .Menu . }} + <a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a> + {{ else if $currentPage.HasMenuCurrent .Menu . }} + <a class="ancestor" aria-current="true" href="{{ .URL }}">{{ .Name }}</a> + {{ else }} + <a href="{{ .URL }}">{{ .Name }}</a> + {{ end }} +{{ end }} +``` + +See [menu templates] for a complete example. + +[menu templates]: /templates/menu-templates/#example diff --git a/content/en/methods/page/IsNode.md b/content/en/methods/page/IsNode.md new file mode 100644 index 000000000..dfdf435c5 --- /dev/null +++ b/content/en/methods/page/IsNode.md @@ -0,0 +1,36 @@ +--- +title: IsNode +description: Reports whether the given page is a node. +categories: [] +keywords: [] +action: + related: + - methods/page/IsHome + - methods/page/IsPage + - methods/page/IsSection + returnType: bool + signatures: [PAGE.IsNode] +--- + +The `IsNode` method on a `Page` object returns `true` if the [page kind] is `home`, `section`, `taxonomy`, or `term`. + +It returns `false` is the page kind is `page`. + +```text +content/ +├── books/ +│ ├── book-1/ +│ │ └── index.md <-- kind = page, node = false +│ ├── book-2.md <-- kind = page, node = false +│ └── _index.md <-- kind = section, node = true +├── tags/ +│ ├── fiction/ +│ │ └── _index.md <-- kind = term, node = true +│ └── _index.md <-- kind = taxonomy, node = true +└── _index.md <-- kind = home, node = true +``` + +```go-html-template +{{ .IsNode }} +``` +[page kind]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/IsPage.md b/content/en/methods/page/IsPage.md new file mode 100644 index 000000000..672ee61f4 --- /dev/null +++ b/content/en/methods/page/IsPage.md @@ -0,0 +1,31 @@ +--- +title: IsPage +description: Reports whether the given page is a regular page. +categories: [] +keywords: [] +action: + related: + - methods/page/IsHome + - methods/page/IsNode + - methods/page/IsSection + returnType: bool + signatures: [PAGE.IsPage] +--- + +The `IsPage` method on a `Page` object returns `true` if the [page kind] is `page`. + +```text +content/ +├── books/ +│ ├── book-1/ +│ │ └── index.md <-- kind = page +│ ├── book-2.md <-- kind = page +│ └── _index.md <-- kind = section +└── _index.md <-- kind = home +``` + +```go-html-template +{{ .IsPage }} +``` + +[page kind]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/IsSection.md b/content/en/methods/page/IsSection.md new file mode 100644 index 000000000..b02e58a45 --- /dev/null +++ b/content/en/methods/page/IsSection.md @@ -0,0 +1,31 @@ +--- +title: IsSection +description: Reports whether the given page is a section page. +categories: [] +keywords: [] +action: + related: + - methods/page/IsHome + - methods/page/IsNode + - methods/page/IsPage + returnType: bool + signatures: [PAGE.IsSection] +--- + +The `IsSection` method on a `Page` object returns `true` if the [page kind] is `section`. + +```text +content/ +├── books/ +│ ├── book-1/ +│ │ └── index.md <-- kind = page +│ ├── book-2.md <-- kind = page +│ └── _index.md <-- kind = section +└── _index.md <-- kind = home +``` + +```go-html-template +{{ .IsSection }} +``` + +[page kind]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/IsTranslated.md b/content/en/methods/page/IsTranslated.md new file mode 100644 index 000000000..6a8f3f69e --- /dev/null +++ b/content/en/methods/page/IsTranslated.md @@ -0,0 +1,59 @@ +--- +title: IsTranslated +description: Reports whether the given page has one or more translations. +categories: [] +keywords: [] +action: + related: + - methods/page/Translations + - methods/page/AllTranslations + - methods/page/TranslationKey + returnType: bool + signatures: [PAGE.IsTranslated] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ └── book-1.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +└── _index.md +``` + +When rendering content/en/books/book-1.md: + +```go-html-template +{{ .IsTranslated }} → true +``` + +When rendering content/en/books/book-2.md: + +```go-html-template +{{ .IsTranslated }} → false +``` diff --git a/content/en/methods/page/Keywords.md b/content/en/methods/page/Keywords.md new file mode 100644 index 000000000..5ad37ce51 --- /dev/null +++ b/content/en/methods/page/Keywords.md @@ -0,0 +1,46 @@ +--- +title: Keywords +description: Returns a slice of keywords as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: '[]string' + signatures: [PAGE.Keywords] +--- + +By default, Hugo evaluates the keywords when creating collections of [related content]. + +[related content]: /content-management/related + +{{< code-toggle file=content/recipes/sushi.md fm=true >}} +title = 'How to make spicy tuna hand rolls' +keywords = ['tuna','sriracha','nori','rice'] +{{< /code-toggle >}} + +To list the keywords within a template: + +```go-html-template +{{ range .Keywords }} + {{ . }} +{{ end }} +``` + +Or use the [delimit] function: + +```go-html-template +{{ delimit .Keywords ", " ", and " }} → tuna, sriracha, nori, and rice +``` + +[delimit]: /functions/collections/delimit + +Keywords are also a useful [taxonomy]: + +{{< code-toggle file=hugo >}} +[taxonomies] +tag = 'tags' +keyword = 'keywords' +category = 'categories' +{{< /code-toggle >}} + +[taxonomy]: /content-management/taxonomies diff --git a/content/en/methods/page/Kind.md b/content/en/methods/page/Kind.md new file mode 100644 index 000000000..d901e9a7d --- /dev/null +++ b/content/en/methods/page/Kind.md @@ -0,0 +1,35 @@ +--- +title: Kind +description: Returns the kind of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Type + returnType: string + signatures: [PAGE.Kind] +--- + +The [page kind] is one of `home`, `page`, `section`, `taxonomy`, or `term`. + +```text +content/ +├── books/ +│ ├── book-1/ +│ │ └── index.md <-- kind = page +│ ├── book-2.md <-- kind = page +│ └── _index.md <-- kind = section +├── tags/ +│ ├── fiction/ +│ │ └── _index.md <-- kind = term +│ └── _index.md <-- kind = taxonomy +└── _index.md <-- kind = home +``` + +To get the value within a template: + +```go-html-template +{{ .Kind }} +``` + +[page kind]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/Language.md b/content/en/methods/page/Language.md new file mode 100644 index 000000000..4e65107da --- /dev/null +++ b/content/en/methods/page/Language.md @@ -0,0 +1,65 @@ +--- +title: Language +description: Returns the language object for the given page. +categories: [] +keywords: [] +action: + related: + - methods/site/Language + returnType: langs.Language + signatures: [PAGE.Language] +--- + +The `Language` method on a `Page` object returns the language object for the given page. The language object points to the language definition in the site configuration. + +You can also use the `Language` method on a `Site` object. See [details]. + +## Methods + +The examples below assume the following in your site configuration: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +weight = 2 +{{< /code-toggle >}} + +Lang +: (`string`) The language tag as defined by [RFC 5646]. + +```go-html-template +{{ .Language.Lang }} → de +``` + +LanguageCode +: (`string`) The language code from the site configuration. + +```go-html-template +{{ .Language.LanguageCode }} → de-DE +``` + +LanguageDirection +: (`string`) The language direction from the site configuration, either `ltr` or `rtl`. + +```go-html-template +{{ .Language.LanguageDirection }} → ltr +``` + +LanguageName +: (`string`) The language name from the site configuration. + +```go-html-template +{{ .Language.LanguageName }} → Deutsch +``` + +Weight +: (`int`) The language weight from the site configuration which determines its order in the slice of languages returned by the `Languages` method on a `Site` object. + +```go-html-template +{{ .Language.Weight }} → 2 +``` + +[details]: /methods/site/language +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 diff --git a/content/en/methods/page/Lastmod.md b/content/en/methods/page/Lastmod.md new file mode 100644 index 000000000..c1692233d --- /dev/null +++ b/content/en/methods/page/Lastmod.md @@ -0,0 +1,40 @@ +--- +title: Lastmod +description: Returns the last modification date of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Date + - methods/page/ExpiryDate + - methods/page/PublishDate + - methods/page/GitInfo + returnType: time.Time + signatures: [PAGE.Lastmod] +--- + +Set the last modification date in front matter: + +{{< code-toggle file=content/news/article-1.md fm=true >}} +title = 'Article 1' +lastmod = 2023-10-19T00:40:04-07:00 +{{< /code-toggle >}} + +The last modification date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods]. + +```go-html-template +{{ .Lastmod | time.Format ":date_medium" }} → Oct 19, 2023 +``` + +In the example above we explicitly set the last modification date in front matter. With Hugo's default configuration, the `Lastmod` method returns the front matter value. This behavior is configurable, allowing you to: + +- Set the last modification date to the Author Date of the last Git commit for that file. See [`GitInfo`] for details. +- Set fallback values if the last modification date is not defined in front matter. + +Learn more about [date configuration]. + +[`gitinfo`]: /methods/page/gitinfo +[`time.format`]: /functions/time/format +[date configuration]: /getting-started/configuration/#configure-dates +[time methods]: /methods/time +[time.time]: https://pkg.go.dev/time#time diff --git a/content/en/methods/page/Layout.md b/content/en/methods/page/Layout.md new file mode 100644 index 000000000..3d0cdc437 --- /dev/null +++ b/content/en/methods/page/Layout.md @@ -0,0 +1,40 @@ +--- +title: Layout +description: Returns the layout for the given page as defined in front matter. +categories: [] +keywords: [] +action: + related: + - methods/page/Type + returnType: string + signatures: [PAGE.Layout] +--- + +Specify the `layout` field in front matter to target a particular template. See [details]. + +[details]: /templates/lookup-order/#target-a-template + +{{< code-toggle file=content/contact.md >}} +title = 'Contact' +layout = 'contact' +{{< /code-toggle >}} + +Hugo will render the page using contact.html. + +```text +layouts/ +└── _default/ + ├── baseof.html + ├── contact.html + ├── home.html + ├── list.html + └── single.html +``` + +Although rarely used within a template, you can access the value with: + +```go-html-template +{{ .Layout }} +``` + +The `Layout` method returns an empty string if the `layout` field in front matter is not defined. diff --git a/content/en/methods/page/Len.md b/content/en/methods/page/Len.md new file mode 100644 index 000000000..d4270bda3 --- /dev/null +++ b/content/en/methods/page/Len.md @@ -0,0 +1,15 @@ +--- +title: Len +description: Returns the length, in bytes, of the rendered content of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Content + returnType: int + signatures: [PAGE.Len] +--- + +```go-html-template +{{ .Len }} → 42 +``` diff --git a/content/en/methods/page/LinkTitle.md b/content/en/methods/page/LinkTitle.md new file mode 100644 index 000000000..746e433bb --- /dev/null +++ b/content/en/methods/page/LinkTitle.md @@ -0,0 +1,30 @@ +--- +title: LinkTitle +description: Returns the link title of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Title + returnType: string + signatures: [PAGE.LinkTitle] +--- + +The `LinkTitle` method returns the `linkTitle` field as defined in front matter, falling back to the value returned by the [`Title`] method. + +[`Title`]: /methods/page/title + +{{< code-toggle file=content/articles/healthy-desserts.md fm=true >}} +title = 'Seventeen delightful recipes for healthy desserts' +linkTitle = 'Dessert recipes' +{{< /code-toggle >}} + +```go-html-template +{{ .LinkTitle }} → Dessert recipes +``` + +As demonstrated above, defining a link title in front matter is advantageous when the page title is long. Use it when generating anchor elements in your templates: + +```go-html-template +<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> +``` diff --git a/content/en/methods/page/Next.md b/content/en/methods/page/Next.md new file mode 100644 index 000000000..3c9e3495a --- /dev/null +++ b/content/en/methods/page/Next.md @@ -0,0 +1,53 @@ +--- +title: Next +description: Returns the next page in a global page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Prev + - methods/page/NextInSection + - methods/page/PrevInSection + - methods/pages/Next + - methods/pages/Prev + returnType: hugolib.pageState + signatures: [PAGE.Next] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .Next }} + <a href="{{ .RelPermalink }}">Prev</a> +{{ end }} + +{{ with .Prev }} + <a href="{{ .RelPermalink }}">Next</a> +{{ end }} +``` + +## Compare to Pages methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --git a/content/en/methods/page/NextInSection.md b/content/en/methods/page/NextInSection.md new file mode 100644 index 000000000..b48ddcc62 --- /dev/null +++ b/content/en/methods/page/NextInSection.md @@ -0,0 +1,71 @@ +--- +title: NextInSection +description: Returns the next page within a section, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/PrevInSection + - methods/page/Next + - methods/page/Prev + - methods/pages/Next + - methods/pages/Prev + returnType: hugolib.pageState + signatures: [PAGE.NextInSection] +--- + +The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── books/ +│ ├── _index.md +│ ├── book-1.md +│ ├── book-2.md +│ └── book-3.md +├── films/ +│ ├── _index.md +│ ├── film-1.md +│ ├── film-2.md +│ └── film-3.md +└── _index.md +``` + +When you visit book-2: + +- The `PrevInSection` method points to book-3 +- The `NextInSection` method points to book-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .NextInSection }} + <a href="{{ .RelPermalink }}">Previous in section</a> +{{ end }} + +{{ with .PrevInSection }} + <a href="{{ .RelPermalink }}">Next in section</a> +{{ end }} +``` + +{{% note %}} +The navigation sort order may be different than the page collection sort order. +{{% /note %}} + +With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence: + +1. Page [weight] +2. Page [date] (descending) +3. Page [linkTitle], falling back to page [title] +4. Page file path if the page is backed by a file + +For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice. + +[date]: /methods/page/date +[weight]: /methods/page/weight +[linkTitle]: /methods/page/linktitle +[title]: /methods/page/title diff --git a/content/en/methods/page/OutputFormats.md b/content/en/methods/page/OutputFormats.md new file mode 100644 index 000000000..03343cf8c --- /dev/null +++ b/content/en/methods/page/OutputFormats.md @@ -0,0 +1,40 @@ +--- +title: OutputFormats +description: Returns a slice of OutputFormat objects, each representing one of the output formats enabled for the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/AlternativeOutputFormats + returnType: '[]OutputFormat' + signatures: [PAGE.OutputFormats] +toc: true +--- + +{{% include "methods/page/_common/output-format-definition.md" %}} + +The `OutputFormats` method on a `Page` object returns a slice of `OutputFormat` objects, each representing one of the output formats enabled for the given page. See [details](/templates/output-formats/). + +## Methods + +{{% include "methods/page/_common/output-format-methods.md" %}} + +## Example + +To link to the RSS feed for the current page: + +```go-html-template +{{ with .OutputFormats.Get "rss" -}} + <a href="{{ .RelPermalink }}">RSS Feed</a> +{{ end }} +``` + +On the site's home page, Hugo renders this to: + +```html +<a href="/index.xml">RSS Feed</a> +``` + +Please see the [link to output formats] section to understand the importance of the construct above. + +[link to output formats]: /templates/output-formats/#link-to-output-formats diff --git a/content/en/methods/page/Page.md b/content/en/methods/page/Page.md new file mode 100644 index 000000000..2c0536bee --- /dev/null +++ b/content/en/methods/page/Page.md @@ -0,0 +1,40 @@ +--- +title: Page +description: Returns the Page object of the given page. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.pageState + signatures: [PAGE.Page] +--- + +This is a convenience method, useful within partial templates that are called from both [shortcodes] and page templates. + +{{< code file=layouts/shortcodes/foo.html >}} +{{ partial "my-partial.html" . }} +{{< /code >}} + +When the shortcode calls the partial, it passes the current [context] (the dot). The context includes identifiers such as `Page`, `Params`, `Inner`, and `Name`. + +{{< code file=layouts/_default/single.html >}} +{{ partial "my-partial.html" . }} +{{< /code >}} + +When the page template calls the partial, it also passes the current context (the dot). But in this case, the dot _is_ the `Page` object. + +{{< code file=layouts/partials/my-partial.html >}} +The page title is: {{ .Page.Title }} +{{< /code >}} + +To handle both scenarios, the partial template must be able to access the `Page` object with `Page.Page`. + +{{% note %}} +And yes, that means you can do `.Page.Page.Page.Page.Title` too. + +But don't. +{{% /note %}} + + +[context]: getting-started/glossary/#context +[shortcodes]: /getting-started/glossary/#shortcode diff --git a/content/en/methods/page/Pages.md b/content/en/methods/page/Pages.md new file mode 100644 index 000000000..2f329eeec --- /dev/null +++ b/content/en/methods/page/Pages.md @@ -0,0 +1,90 @@ +--- +title: Pages +description: Returns a collection of regular pages within the current section, and section pages of immediate descendant sections. +categories: [] +keywords: [] +action: + related: + - methods/page/RegularPages + - methods/page/RegularPagesRecursive + returnType: page.Pages + signatures: [PAGE.Pages] +--- + +The `Pages` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context]. + +Range through the page collection in your template: + +```go-html-template +{{ range .Pages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +Consider this content structure: + +```text +content/ +├── lessons/ +│ ├── lesson-1/ +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── lesson-2/ +│ │ ├── resources/ +│ │ │ ├── task-list.md +│ │ │ └── worksheet.md +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── _index.md +│ ├── grading-policy.md +│ └── lesson-plan.md +├── _index.md +├── contact.md +└── legal.md +``` + +When rendering the home page, the `Pages` method returns: + + contact.md + legal.md + lessons/_index.md + +When rendering the lessons page, the `Pages` method returns: + + lessons/grading-policy.md + lessons/lesson-plan.md + lessons/lesson-1/_index.md + lessons/lesson-2/_index.md + +When rendering lesson-1, the `Pages` method returns: + + lessons/lesson-1/part-1.md + lessons/lesson-1/part-2.md + +When rendering lesson-2, the `Pages` method returns: + + lessons/lesson-2/part-1.md + lessons/lesson-2/part-2.md + lessons/lesson-2/resources/task-list.md + lessons/lesson-2/resources/worksheet.md + +In the last example, the collection includes pages in the resources subdirectory. That directory is not a [section]---it does not contain an _index.md file. Its contents are part of the lesson-2 section. + +{{% note %}} +When used with a `Site` object, the `Pages` method recursively returns all pages within the site. See [details]. + +[details]: /methods/site/pages +{{% /note %}} + +```go-html-template +{{ range .Site.Pages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +[collection]: /getting-started/glossary/#collection +[context]: /getting-started/glossary/#context +[page kinds]: /getting-started/glossary/#page-kind +[section]: /getting-started/glossary/#section diff --git a/content/en/methods/page/Paginate.md b/content/en/methods/page/Paginate.md new file mode 100644 index 000000000..6b43b99dd --- /dev/null +++ b/content/en/methods/page/Paginate.md @@ -0,0 +1,50 @@ +--- +title: Paginate +description: Paginates a collection of pages. +categories: [] +keywords: [] +action: + related: + - methods/page/Paginator + returnType: page.Pager + signatures: ['PAGE.Paginate COLLECTION [N]'] +--- + +[Pagination] is the process of splitting a list page into two or more pagers, where each pager contains a subset of the page collection and navigation links to other pagers. + +By default, the number of elements on each pager is determined by the value of the `paginate` setting in your site configuration. The default value is `10`. Override the value in your site configuration by providing a second argument, an integer, when calling the `Paginate` method. + +{{% note %}} +There is also a `Paginator` method on `Page` objects, but it can neither filter nor sort the page collection. + +The `Paginate` method is more flexible. +{{% /note %}} + +You can invoke pagination on the home page template, [`section`] templates, [`taxonomy`] templates, and [`term`] templates. + +{{< code file=layouts/_default/list.html >}} +{{ $pages := where .Site.RegularPages "Section" "articles" }} +{{ $pages = $pages.ByTitle }} +{{ range (.Paginate $pages 7).Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +{{ template "_internal/pagination.html" . }} +{{< /code >}} + +In the example above, we: + +1. Build a page collection +2. Sort the collection by title +3. Paginate the collection, with 7 elements per pager +4. Range over the paginated page collection, rendering a link to each page +5. Call the internal "pagination" template to create the navigation links between pagers. + +{{% note %}} +Please note that the results of pagination are cached. Once you have invoked either the `Paginator` or `Paginate` method, the paginated collection is immutable. Additional invocations of these methods will have no effect. +{{% /note %}} + +[context]: /getting-started/glossary/#context +[pagination]: /templates/pagination/ +[`section`]: /getting-started/glossary/#section +[`taxonomy`]: /getting-started/glossary/#taxonomy +[`term`]: /getting-started/glossary/#term diff --git a/content/en/methods/page/Paginator.md b/content/en/methods/page/Paginator.md new file mode 100644 index 000000000..b1540286a --- /dev/null +++ b/content/en/methods/page/Paginator.md @@ -0,0 +1,42 @@ +--- +title: Paginator +description: Paginates the collection of regular pages received in context. +categories: [] +keywords: [] +action: + related: + - methods/page/Paginate + returnType: page.Pager + signatures: [PAGE.Paginator] +--- + +[Pagination] is the process of splitting a list page into two or more pagers, where each pager contains a subset of the page collection and navigation links to other pagers. The number of elements on each pager is determined by the value of the `paginate` setting in your site configuration. The default value is `10`. + +You can invoke pagination on the home page template, [`section`] templates, [`taxonomy`] templates, and [`term`] templates. Each of these receive a collection of regular pages in [context]. When you invoke the `Paginator` method, it paginates the page collection received in context. + +{{< code file=layouts/_default/list.html >}} +{{ range .Paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +{{ template "_internal/pagination.html" . }} +{{< /code >}} + +In the example above, the internal "pagination" template creates the navigation links between pagers. + +{{% note %}} +Although simple to invoke, with the `Paginator` method you can neither filter nor sort the page collection. It acts upon the page collection received in context. + +The [`Paginate`] method is more flexible, and strongly recommended. + +[`paginate`]: /methods/page/paginate +{{% /note %}} + +{{% note %}} +Please note that the results of pagination are cached. Once you have invoked either the `Paginator` or `Paginate` method, the paginated collection is immutable. Additional invocations of these methods will have no effect. +{{% /note %}} + +[context]: /getting-started/glossary/#context +[pagination]: /templates/pagination/ +[`section`]: /getting-started/glossary/#section +[`taxonomy`]: /getting-started/glossary/#taxonomy +[`term`]: /getting-started/glossary/#term diff --git a/content/en/methods/page/Param.md b/content/en/methods/page/Param.md new file mode 100644 index 000000000..b2932d981 --- /dev/null +++ b/content/en/methods/page/Param.md @@ -0,0 +1,47 @@ +--- +title: Param +description: Returns a page parameter with the given key, falling back to a site parameter if present. +categories: [] +keywords: [] +action: + related: [] + returnType: any + signatures: [PAGE.Param KEY] +aliases: [/functions/param] +--- + +The `Param` method on a `Page` object looks for the given `KEY` in page parameters, and returns the corresponding value. If it cannot find the `KEY` in page parameters, it looks for the `KEY` in site parameters. If it cannot find the `KEY` in either location, the `Param` method returns `nil`. + +Site and theme developers commonly set parameters at the site level, allowing content authors to override those parameters at the page level. + +For example, to show a table of contents on every page, but allow authors to hide the table of contents as needed: + +Configuration: + +{{< code-toggle file=hugo >}} +[params] +display_toc = true +{{< /code-toggle >}} + +Content: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +date = 2023-01-01 +draft = false +display_toc = false +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ if .Param "display_toc" }} + {{ .TableOfContents }} +{{ end }} +``` + +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: + +```go-html-template +{{ or .Params.foo site.Params.foo }} +``` diff --git a/content/en/methods/page/Params.md b/content/en/methods/page/Params.md new file mode 100644 index 000000000..ce624c394 --- /dev/null +++ b/content/en/methods/page/Params.md @@ -0,0 +1,43 @@ +--- +title: Params +description: Returns a map of custom parameters as defined in the front matter of the given page. +categories: [] +keywords: [] +action: + related: + - functions/collections/IndexFunction + - methods/site/Params + - methods/page/Param + returnType: maps.Params + signatures: [PAGE.Params] +--- + +With this front matter: + +{{< code-toggle file=content/news/annual-conference.md >}} +title = 'Annual conference' +date = 2023-10-17T15:11:37-07:00 +display_related = true +event-date = '2023' +[params.author] + email = '[email protected]' + name = 'John Smith' +{{< /code-toggle >}} + +The `title` and `date` fields are standard parameters---the other fields are user-defined. + +Access the custom parameters by [chaining] the [identifiers]: + +```go-html-template +{{ .Params.display_related }} → true +{{ .Params.author.name }} → John Smith +``` + +In the template example above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function: + +```go-html-template +{{ index .Params "event-date" }} → 2023 +``` +[`index`]: /functions/collections/indexfunction +[chaining]: /getting-started/glossary/#chain +[identifiers]: /getting-started/glossary/#identifier diff --git a/content/en/methods/page/Parent.md b/content/en/methods/page/Parent.md new file mode 100644 index 000000000..dbd2cb9b3 --- /dev/null +++ b/content/en/methods/page/Parent.md @@ -0,0 +1,60 @@ +--- +title: Parent +description: Returns the Page object of the parent section of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Sections + returnType: hugolib.pageState + signatures: [PAGE.Parent] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +The parent section of a regular page is the [current section]. + +[current section]: /methods/page/currentsection +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- parent: auctions +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- parent: 2023-11 +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- parent: home +│ ├── bidding.md +│ └── payment.md <-- parent: auctions +├── books/ +│ ├── _index.md <-- parent: home +│ ├── book-1.md +│ └── book-2.md <-- parent: books +├── films/ +│ ├── _index.md <-- parent: home +│ ├── film-1.md +│ └── film-2.md <-- parent: films +└── _index.md <-- parent: nil +``` + +In the example above, note the parent section of the home page is nil. Code defensively by verifying existence of the parent section before calling methods on its `Page` object. To create a link to the parent section page of the current page: + +```go-html-template +{{ with .Parent }} + <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> +{{ end }} +``` diff --git a/content/en/methods/page/Permalink.md b/content/en/methods/page/Permalink.md new file mode 100644 index 000000000..be6df5aad --- /dev/null +++ b/content/en/methods/page/Permalink.md @@ -0,0 +1,25 @@ +--- +title: Permalink +description: Returns the permalink of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/RelPermalink + returnType: string + signatures: [PAGE.Permalink] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +title = 'Documentation' +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ $page := .Site.GetPage "/about" }} +{{ $page.RelPermalink }} → https://example.org/docs/about/ +``` diff --git a/content/en/methods/page/Plain.md b/content/en/methods/page/Plain.md new file mode 100644 index 000000000..6fdf60b62 --- /dev/null +++ b/content/en/methods/page/Plain.md @@ -0,0 +1,28 @@ +--- +title: Plain +description: Returns the rendered content of the given page, removing all HTML tags. +categories: [] +keywords: [] +action: + related: + - methods/page/Content + - methods/page/RawContent + - methods/page/PlainWords + - methods/page/RenderShortcodes + returnType: string + signatures: [PAGE.Plain] +--- + +The `Plain` method on a `Page` object renders markdown and [shortcodes] to HTML, then strips the HTML [tags]. It does not strip HTML [entities]. The plain content does not include front matter. + +To prevent Go's [html/template] package from escaping HTML entities, pass the result through the [`htmlUnescape`] function. + +```go-html-template +{{ .Plain | htmlUnescape }} +``` + +[shortcodes]: /getting-started/glossary/#shortcode +[html/template]: https://pkg.go.dev/html/template +[entities]: https://developer.mozilla.org/en-US/docs/Glossary/Entity +[tags]: https://developer.mozilla.org/en-US/docs/Glossary/Tag +[`htmlUnescape`]: /functions/ diff --git a/content/en/methods/page/PlainWords.md b/content/en/methods/page/PlainWords.md new file mode 100644 index 000000000..4bc79d241 --- /dev/null +++ b/content/en/methods/page/PlainWords.md @@ -0,0 +1,36 @@ +--- +title: PlainWords +description: Calls the Plain method, splits the result into a slice of words, and returns the slice. +categories: [] +keywords: [] +action: + related: + - methods/page/Content + - methods/page/RawContent + - methods/page/Plain + returnType: '[]string' + signatures: [PAGE.PlainWords] +--- + +The `PlainWords` method on a `Page` object calls the [`Plain`] method, then uses Go's [`strings.Fields`] function to split the result into words. + +{{% note %}} +_Fields splits the string s around each instance of one or more consecutive white space characters, as defined by [`unicode.IsSpace`], returning a slice of substrings of s or an empty slice if s contains only white space._ + +[`unicode.IsSpace`]: https://pkg.go.dev/unicode#IsSpace +{{% /note %}} + +As a result, elements within the slice may contain leading or trailing punctuation. + +```go-html-template +{{ .PlainWords }} +``` + +To determine the approximate number of unique words on a page: + +```go-html-template +{{ .PlainWords | uniq }} → 42 +``` + +[`Plain`]: /methods/page/plain +[`strings.Fields`]: https://pkg.go.dev/strings#Fields diff --git a/content/en/methods/page/Prev.md b/content/en/methods/page/Prev.md new file mode 100644 index 000000000..cde83b0f2 --- /dev/null +++ b/content/en/methods/page/Prev.md @@ -0,0 +1,53 @@ +--- +title: Prev +description: Returns the previous page in a global page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Next + - methods/page/PrevInSection + - methods/page/NextInSection + - methods/pages/Prev + - methods/pages/Next + returnType: hugolib.pageState + signatures: [PAGE.Prev] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .Next }} + <a href="{{ .RelPermalink }}">Prev</a> +{{ end }} + +{{ with .Prev }} + <a href="{{ .RelPermalink }}">Next</a> +{{ end }} +``` + +## Compare to Pages methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --git a/content/en/methods/page/PrevInSection.md b/content/en/methods/page/PrevInSection.md new file mode 100644 index 000000000..30b813350 --- /dev/null +++ b/content/en/methods/page/PrevInSection.md @@ -0,0 +1,72 @@ +--- +title: PrevInSection +description: Returns the previous page within a section, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/NextInSection + - methods/page/Next + - methods/pages/Next + - methods/page/Prev + - methods/pages/Prev + returnType: hugolib.pageState + signatures: [PAGE.PrevInSection] +--- + + +The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── books/ +│ ├── _index.md +│ ├── book-1.md +│ ├── book-2.md +│ └── book-3.md +├── films/ +│ ├── _index.md +│ ├── film-1.md +│ ├── film-2.md +│ └── film-3.md +└── _index.md +``` + +When you visit book-2: + +- The `PrevInSection` method points to book-3 +- The `NextInSection` method points to book-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .NextInSection }} + <a href="{{ .RelPermalink }}">Previous in section</a> +{{ end }} + +{{ with .PrevInSection }} + <a href="{{ .RelPermalink }}">Next in section</a> +{{ end }} +``` + +{{% note %}} +The navigation sort order may be different than the page collection sort order. +{{% /note %}} + +With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence: + +1. Page [weight] +2. Page [date] (descending) +3. Page [linkTitle], falling back to page [title] +4. Page file path if the page is backed by a file + +For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice. + +[date]: /methods/page/date +[weight]: /methods/page/weight +[linkTitle]: /methods/page/linktitle +[title]: /methods/page/title diff --git a/content/en/methods/page/PublishDate.md b/content/en/methods/page/PublishDate.md new file mode 100644 index 000000000..b1c0717a9 --- /dev/null +++ b/content/en/methods/page/PublishDate.md @@ -0,0 +1,35 @@ +--- +title: PublishDate +description: Returns the publish date of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Date + - methods/page/ExpiryDate + - methods/page/LastMod + returnType: time.Time + signatures: [PAGE.PublishDate] +--- + +By default, Hugo excludes pages with future publish dates when building your site. To include future pages, use the `--buildFuture` command line flag. + +Set the publish date in front matter: + +{{< code-toggle file=content/news/article-1.md fm=true >}} +title = 'Article 1' +publishDate = 2023-10-19T00:40:04-07:00 +{{< /code-toggle >}} + +The publish date is a [time.Time] value. Format and localize the value with the [`time.Format`] function, or use it with any of the [time methods]. + +```go-html-template +{{ .PublishDate | time.Format ":date_medium" }} → Oct 19, 2023 +``` + +In the example above we explicitly set the publish date in front matter. With Hugo's default configuration, the `PublishDate` method returns the front matter value. This behavior is configurable, allowing you to set fallback values if the publish date is not defined in front matter. See [details]. + +[`time.Format`]: /functions/time/format +[details]: /getting-started/configuration/#configure-dates +[time methods]: /methods/time +[time.Time]: https://pkg.go.dev/time#Time diff --git a/content/en/methods/page/RawContent.md b/content/en/methods/page/RawContent.md new file mode 100644 index 000000000..258a294d0 --- /dev/null +++ b/content/en/methods/page/RawContent.md @@ -0,0 +1,31 @@ +--- +title: RawContent +description: Returns the raw content of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Content + - methods/page/Plain + - methods/page/PlainWords + - methods/page/RenderShortcodes + returnType: string + signatures: [PAGE.RawContent] +--- + +The `RawContent` method on a `Page` object returns the raw content. The raw content does not include front matter. + +```go-html-template +{{ .RawContent }} +``` + +This is useful when rendering a page in a plain text [output format]. + +{{% note %}} +[Shortcodes] within the content are not rendered. To get the raw content with shortcodes rendered, use the [`RenderShortcodes`] method on a `Page` object. + +[shortcodes]: /getting-started/glossary/#shortcode +[`RenderShortcodes`]: /methods/page/rendershortcodes +{{% /note %}} + +[output format]: /templates/output-formats diff --git a/content/en/methods/page/ReadingTime.md b/content/en/methods/page/ReadingTime.md new file mode 100644 index 000000000..531824b9b --- /dev/null +++ b/content/en/methods/page/ReadingTime.md @@ -0,0 +1,49 @@ +--- +title: ReadingTime +description: Returns the estimated reading time, in minutes, for the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/WordCount + - methods/page/FuzzyWordCount + returnType: int + signatures: [PAGE.ReadingTime] +--- + +The estimated reading time is calculated by dividing the number of words in the content by the reading speed. + +By default, Hugo assumes a reading speed of 212 words per minute. For CJK languages, it assumes 500 words per minute. + +```go-html-template +{{ printf "Estimated reading time: %d minutes" .ReadingTime }} +``` + +Reading speed varies by language. Create language-specific estimated reading times on your multilingual site using site parameters. + +{{< code-toggle file=hugo >}} +[languages] + [languages.de] + contentDir = 'content/de' + languageCode = 'de-DE' + languageName = 'Deutsch' + weight = 2 + [languages.de.params] + reading_speed = 179 + [languages.en] + contentDir = 'content/en' + languageCode = 'en-US' + languageName = 'English' + weight = 1 + [languages.en.params] + reading_speed = 228 +{{< /code-toggle >}} + +Then in your template: + +```go-html-template +{{ $readingTime := div (float .WordCount) .Site.Params.reading_speed }} +{{ $readingTime = math.Ceil $readingTime }} +``` + +We cast the `.WordCount` to a float to obtain a float when we divide by the reading speed. Then round up to the nearest integer. diff --git a/content/en/methods/page/Ref.md b/content/en/methods/page/Ref.md new file mode 100644 index 000000000..e3c5569a4 --- /dev/null +++ b/content/en/methods/page/Ref.md @@ -0,0 +1,44 @@ +--- +title: Ref +description: Returns the absolute URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +action: + related: + - methods/page/RelRef + - functions/urls/RelRef + - functions/urls/Ref + returnType: string + signatures: [PAGE.Ref OPTIONS] +--- + +The map of option contains: + +path +: (`string`) The path to the page, relative to the content directory. Required. + +lang +: (`string`) The language (site) to search for the page. Default is the current language. Optional. + +outputFormat +: (`string`) The output format to search for the page. Default is the current output format. Optional. + +The examples below show the rendered output when visiting a page on the English language version of the site: + +```go-html-template +{{ $opts := dict "path" "/books/book-1" }} +{{ .Ref $opts }} → https://example.org/en/books/book-1/ + +{{ $opts := dict "path" "/books/book-1" "lang" "de" }} +{{ .Ref $opts }} → https://example.org/de/books/book-1/ + +{{ $opts := dict "path" "/books/book-1" "lang" "de" "outputFormat" "json" }} +{{ .Ref $opts }} → https://example.org/de/books/book-1/index.json +``` + +By default, Hugo will throw an error and fail the build if it cannot resolve the path. You can change this to a warning in your site configuration, and specify a URL to return when the path cannot be resolved. + +{{< code-toggle file=hugo >}} +refLinksErrorLevel = 'warning' +refLinksNotFoundURL = '/some/other/url' +{{< /code-toggle >}} diff --git a/content/en/methods/page/RegularPages.md b/content/en/methods/page/RegularPages.md new file mode 100644 index 000000000..b0ca7b1e1 --- /dev/null +++ b/content/en/methods/page/RegularPages.md @@ -0,0 +1,87 @@ +--- +title: RegularPages +description: Returns a collection of regular pages within the current section. +categories: [] +keywords: [] +action: + related: + - methods/page/Pages + - methods/page/RegularPagesRecursive + returnType: page.Pages + signatures: [PAGE.RegularPages] +--- + +The `RegularPages` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context]. + +Range through the page collection in your template: + +```go-html-template +{{ range .RegularPages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +Consider this content structure: + +```text +content/ +├── lessons/ +│ ├── lesson-1/ +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── lesson-2/ +│ │ ├── resources/ +│ │ │ ├── task-list.md +│ │ │ └── worksheet.md +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── _index.md +│ ├── grading-policy.md +│ └── lesson-plan.md +├── _index.md +├── contact.md +└── legal.md +``` + +When rendering the home page, the `RegularPages` method returns: + + contact.md + legal.md + +When rendering the lessons page, the `RegularPages` method returns: + + lessons/grading-policy.md + lessons/lesson-plan.md + +When rendering lesson-1, the `RegularPages` method returns: + + lessons/lesson-1/part-1.md + lessons/lesson-1/part-2.md + +When rendering lesson-2, the `RegularPages` method returns: + + lessons/lesson-2/part-1.md + lessons/lesson-2/part-2.md + lessons/lesson-2/resources/task-list.md + lessons/lesson-2/resources/worksheet.md + +In the last example, the collection includes pages in the resources subdirectory. That directory is not a [section]---it does not contain an _index.md file. Its contents are part of the lesson-2 section. + +{{% note %}} +When used with the `Site` object, the `RegularPages` method recursively returns all regular pages within the site. See [details]. + +[details]: /methods/site/regularpages +{{% /note %}} + +```go-html-template +{{ range .Site.RegularPages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +[collection]: /getting-started/glossary/#collection +[context]: /getting-started/glossary/#context +[page kinds]: /getting-started/glossary/#page-kind +[section]: /getting-started/glossary/#section diff --git a/content/en/methods/page/RegularPagesRecursive.md b/content/en/methods/page/RegularPagesRecursive.md new file mode 100644 index 000000000..3dac8c85e --- /dev/null +++ b/content/en/methods/page/RegularPagesRecursive.md @@ -0,0 +1,90 @@ +--- +title: RegularPagesRecursive +description: Returns a collection of regular pages within the current section, and regular pages within all descendant sections. +categories: [] +keywords: [] +action: + related: + - methods/page/Pages + - methods/page/RegularPages + returnType: page.Pages + signatures: [PAGE.RegularPagesRecursive] +--- + +The `RegularPagesRecursive` method on a `Page` object is available to these [page kinds]: `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection] in [context]. + +Range through the page collection in your template: + +```go-html-template +{{ range .RegularPagesRecursive.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +Consider this content structure: + +```text +content/ +├── lessons/ +│ ├── lesson-1/ +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── lesson-2/ +│ │ ├── resources/ +│ │ │ ├── task-list.md +│ │ │ └── worksheet.md +│ │ ├── _index.md +│ │ ├── part-1.md +│ │ └── part-2.md +│ ├── _index.md +│ ├── grading-policy.md +│ └── lesson-plan.md +├── _index.md +├── contact.md +└── legal.md +``` + +When rendering the home page, the `RegularPagesRecursive` method returns: + + contact.md + lessons/grading-policy.md + legal.md + lessons/lesson-plan.md + lessons/lesson-2/part-1.md + lessons/lesson-1/part-1.md + lessons/lesson-2/part-2.md + lessons/lesson-1/part-2.md + lessons/lesson-2/resources/task-list.md + lessons/lesson-2/resources/worksheet.md + +When rendering the lessons page, the `RegularPagesRecursive` method returns: + + lessons/grading-policy.md + lessons/lesson-plan.md + lessons/lesson-2/part-1.md + lessons/lesson-1/part-1.md + lessons/lesson-2/part-2.md + lessons/lesson-1/part-2.md + lessons/lesson-2/resources/task-list.md + lessons/lesson-2/resources/worksheet.md + +When rendering lesson-1, the `RegularPagesRecursive` method returns: + + lessons/lesson-1/part-1.md + lessons/lesson-1/part-2.md + +When rendering lesson-2, the `RegularPagesRecursive` method returns: + + lessons/lesson-2/part-1.md + lessons/lesson-2/part-2.md + lessons/lesson-2/resources/task-list.md + lessons/lesson-2/resources/worksheet.md + +{{% note %}} +The `RegularPagesRecursive` method in not available on a `Site` object. +{{% /note %}} + +[collection]: /getting-started/glossary/#collection +[context]: /getting-started/glossary/#context +[page kinds]: /getting-started/glossary/#page-kind diff --git a/content/en/methods/page/RelPermalink.md b/content/en/methods/page/RelPermalink.md new file mode 100644 index 000000000..8a5972ccc --- /dev/null +++ b/content/en/methods/page/RelPermalink.md @@ -0,0 +1,25 @@ +--- +title: RelPermalink +description: Returns the relative permalink of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Permalink + returnType: string + signatures: [PAGE.RelPermalink] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +title = 'Documentation' +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ $page := .Site.GetPage "/about" }} +{{ $page.Permalink }} → /docs/about/ +``` diff --git a/content/en/methods/page/RelRef.md b/content/en/methods/page/RelRef.md new file mode 100644 index 000000000..4c635e0e2 --- /dev/null +++ b/content/en/methods/page/RelRef.md @@ -0,0 +1,44 @@ +--- +title: RelRef +description: Returns the relative URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +action: + related: + - methods/page/Ref + - functions/urls/Ref + - functions/urls/RelRef + returnType: string + signatures: [PAGE.RelRef OPTIONS] +--- + +The map of option contains: + +path +: (`string`) The path to the page, relative to the content directory. Required. + +lang +: (`string`) The language (site) to search for the page. Default is the current language. Optional. + +outputFormat +: (`string`) The output format to search for the page. Default is the current output format. Optional. + +The examples below show the rendered output when visiting a page on the English language version of the site: + +```go-html-template +{{ $opts := dict "path" "/books/book-1" }} +{{ .RelRef $opts }} → /en/books/book-1/ + +{{ $opts := dict "path" "/books/book-1" "lang" "de" }} +{{ .RelRef $opts }} → /de/books/book-1/ + +{{ $opts := dict "path" "/books/book-1" "lang" "de" "outputFormat" "json" }} +{{ .RelRef $opts }} → /de/books/book-1/index.json +``` + +By default, Hugo will throw an error and fail the build if it cannot resolve the path. You can change this to a warning in your site configuration, and specify a URL to return when the path cannot be resolved. + +{{< code-toggle file=hugo >}} +refLinksErrorLevel = 'warning' +refLinksNotFoundURL = '/some/other/url' +{{< /code-toggle >}} diff --git a/content/en/methods/page/Render.md b/content/en/methods/page/Render.md new file mode 100644 index 000000000..bc3f58352 --- /dev/null +++ b/content/en/methods/page/Render.md @@ -0,0 +1,75 @@ +--- +title: Render +description: Renders the given template with the given page as context. +categories: [] +keywords: [] +action: + related: + - functions/partials/Include + - functions/partials/IncludeCached + returnType: template.HTML + signatures: [PAGE.Render NAME] +aliases: [/functions/render] +--- + +Typically used when ranging over a page collection, the `Render` method on a `Page` object renders the given template, passing the given page as context. + +```go-html-template +{{ range site.RegularPages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> + {{ .Render "summary" }} +{{ end }} +``` + +In the example above, note that the template ("summary") is identified by its file name without directory or extension. + +Although similar to the [`partial`] function, there are key differences. + +`Render` method|`partial` function| +:--|:-- +The `Page` object is automatically passed to the given template. You cannot pass additional context.| You must specify the context, allowing you to pass a combination of objects, slices, maps, and scalars. +The path to the template is determined by the [content type].|You must specify the path to the template, relative to the layouts/partials directory. + +Consider this layout structure: + +```text +layouts/ +├── _default/ +│ ├── baseof.html +│ ├── home.html +│ ├── li.html <-- used for other content types +│ ├── list.html +│ ├── single.html +│ └── summary.html +└── books/ + ├── li.html <-- used when content type is "books" + └── summary.html +``` + +And this template: + +```go-html-template +<ul> + {{ range site.RegularPages.ByDate }} + {{ .Render "li" }} + {{ end }} +</ul> +``` + +When rendering content of type "books" the `Render` method calls: + +```text +layouts/books/li.html +``` + +For all other content types the `Render` methods calls: + +```text +layouts/_default/li.html +``` + +See [content views] for more examples. + +[content views]: /templates/views +[`partial`]: /functions/partials/include +[content type]: /getting-started/glossary/#content-type diff --git a/content/en/methods/page/RenderShortcodes.md b/content/en/methods/page/RenderShortcodes.md new file mode 100644 index 000000000..4636bf8f5 --- /dev/null +++ b/content/en/methods/page/RenderShortcodes.md @@ -0,0 +1,78 @@ +--- +title: RenderShortcodes +description: Renders all shortcodes in the content of the given page, preserving the surrounding markup. +categories: [] +keywords: [] +action: + related: + - methods/page/RenderString + - methods/page/Content + - methods/page/RawContent + - methods/page/Plain + - methods/page/PlainWords + returnType: template.HTML + signatures: [PAGE.RenderShortcodes] +toc: true +--- + +{{< new-in 0.117.0 >}} + +Use this method in shortcode templates to compose a page from multiple content files, while preserving a global context for footnotes and the table of contents. + +For example: + +{{< code file=layouts/shortcodes/include.html >}} +{{ $p := site.GetPage (.Get 0) }} +{{ $p.RenderShortcodes }} +{{< /code >}} + +Then in your markdown: + +{{< code file=content/about.md lang=md >}} +{{%/* include "/snippets/services.md" */%}} +{{%/* include "/snippets/values.md" */%}} +{{%/* include "/snippets/leadership.md" */%}} +{{< /code >}} + +Each of the included markdown files can contain calls to other shortcodes. + +## Shortcode notation + +In the example above it's important to understand the difference between the two delimiters used when calling a shortcode: + +- `{{</* myshortcode */>}}` tells Hugo that the rendered shortcode does not need further processing. For example, the shortcode content is HTML. +- `{{%/* myshortcode */%}}` tells Hugo that the rendered shortcode needs further processing. For example, the shortcode content is markdown. + +Use the latter for the "include" shortcode described above. + +## Further explanation + +To understand what is returned by the `RenderShortcodes` method, consider this content file + +{{< code file=content/about.md lang=text >}} ++++ +title = 'About' +date = 2023-10-07T12:28:33-07:00 ++++ + +{{</* ref "privacy" */>}} + +An *emphasized* word. +{{< /code >}} + +With this template code: + +```go-html-template +{{ $p := site.GetPage "/about" }} +{{ $p.RenderShortcodes }} +``` + +Hugo renders this:; + +```html +https://example.org/privacy/ + +An *emphasized* word. +``` + +Note that the shortcode within the content file was rendered, but the surrounding markdown was preserved. diff --git a/content/en/methods/page/RenderString.md b/content/en/methods/page/RenderString.md new file mode 100644 index 000000000..5782cd2b1 --- /dev/null +++ b/content/en/methods/page/RenderString.md @@ -0,0 +1,51 @@ +--- +title: RenderString +description: Renders markup to HTML. +categories: [] +keywords: [] +action: + related: + - methods/page/RenderShortcodes + - functions/transform/Markdownify + returnType: template.HTML + signatures: ['PAGE.RenderString [OPTIONS] MARKUP'] +aliases: [/functions/renderstring] +--- + +```go-html-template +{{ $s := "An *emphasized* word" }} +{{ $s | .RenderString }} → An <em>emphasized</em> word +``` + +This method takes an optional map of options: + +display +: (`string`) Specify either `inline` or `block`. If `inline`, removes surrounding `p` tags from short snippets. Default is `inline`. + +markup +: (`string`) Specify a [markup identifier] for the provided markup. Default is the `markup` front matter value, falling back to the value derived from the page's file extension. + +Render with the default markup renderer: + +```go-html-template +{{ $s := "An *emphasized* word" }} +{{ $s | .RenderString }} → An <em>emphasized</em> word + +{{ $opts := dict "display" "block" }} +{{ $s | .RenderString $opts }} → <p>An <em>emphasized</em> word</p> +``` + +Render with [Pandoc]: + +```go-html-template +{{ $s := "H~2~O" }} + +{{ $opts := dict "markup" "pandoc" }} +{{ $s | .RenderString $opts }} → H<sub>2</sub>O + +{{ $opts := dict "display" "block" "markup" "pandoc" }} +{{ .RenderString $opts $s }} → <p>H<sub>2</sub>O</p> +``` + +[markup identifier]: /content-management/formats/#list-of-content-formats +[pandoc]: https://www.pandoc.org/ diff --git a/content/en/methods/page/Resources.md b/content/en/methods/page/Resources.md new file mode 100644 index 000000000..a9fa3dab2 --- /dev/null +++ b/content/en/methods/page/Resources.md @@ -0,0 +1,81 @@ +--- +title: Resources +description: Returns a collection of page resources. +categories: [] +keywords: [] +action: + related: + - functions/resources/ByType + - functions/resources/Get + - functions/resources/GetMatch + - functions/resources/GetRemote + - functions/resources/Match + returnType: resource.Resources + signatures: [PAGE.Resources] +toc: true +--- + +The `Resources` method on a `Page` object returns a collection of page resources. A page resource is a file within a [page bundle]. + +To work with global or remote resources, see the [`resources`] functions. + +## Methods + +ByType +: (`resource.Resources`) Returns a collection of page resources of the given [media type], or nil if none found. The media type is typically one of `image`, `text`, `audio`, `video`, or `application`. + +```go-html-template +{{ range .Resources.ByType "image" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.ByType`] function. + +Get +: (`resource.Resource`) Returns a page resource from the given path, or nil if none found. + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.Get`] function. + +GetMatch +: (`resource.Resource`) Returns the first page resource from paths matching the given [glob pattern], or nil if none found. + +```go-html-template +{{ with .Resources.GetMatch "images/*.jpg" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.GetMatch`] function. + +Match +: (`resource.Resources`) Returns a collection of page resources from paths matching the given [glob pattern], or nil if none found. + +```go-html-template +{{ range .Resources.Match "images/*.jpg" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.Match`] function. + +## Pattern matching + +With the `GetMatch` and `Match` methods, Hugo determines a match using a case-insensitive [glob pattern]. + +{{% include "functions/_common/glob-patterns.md" %}} + +[`resources.ByType`]: /functions/resources/ByType +[`resources.GetMatch`]: /functions/resources/ByType +[`resources.Get`]: /functions/resources/ByType +[`resources.Match`]: /functions/resources/ByType +[`resources`]: /functions/resources +[glob pattern]: https://github.com/gobwas/glob#example +[media type]: https://en.wikipedia.org/wiki/Media_type +[page bundle]: /getting-started/glossary/#page-bundle diff --git a/content/en/methods/page/Scratch.md b/content/en/methods/page/Scratch.md new file mode 100644 index 000000000..f9ce7f7fb --- /dev/null +++ b/content/en/methods/page/Scratch.md @@ -0,0 +1,23 @@ +--- +title: Scratch +description: Creates a "scratch pad" on the given page to store and manipulate data. +categories: [] +keywords: [] +action: + related: + - methods/page/Store + - functions/collections/NewScratch + returnType: maps.Scratch + signatures: [PAGE.Scratch] +aliases: [/extras/scratch/,/doc/scratch/,/functions/scratch] +--- + +The `Scratch` method on a `Page` object creates a [scratch pad] to store and manipulate data. To create a scratch pad that is not reset on server rebuilds, use the [`Store`] method instead. + +To create a locally scoped scratch pad that is not attached to a `Page` object, use the [`newScratch`] function. + +[`Store`]: /methods/page/store +[`newScratch`]: functions/collections/newscratch +[scratch pad]: /getting-started/glossary/#scratch-pad + +{{% include "methods/page/_common/scratch-methods.md" %}} diff --git a/content/en/methods/page/Section.md b/content/en/methods/page/Section.md new file mode 100644 index 000000000..30c8a9837 --- /dev/null +++ b/content/en/methods/page/Section.md @@ -0,0 +1,54 @@ +--- +title: Section +description: Returns the name of the top level section in which the given page resides. +categories: [] +keywords: [] +action: + related: + - methods/page/Type + returnType: string + signatures: [PAGE.Section] +--- + +With this content structure: + +```text +content/ +├── lessons/ +│ ├── math/ +│ │ ├── _index.md +│ │ ├── lesson-1.md +│ │ └── lesson-2.md +│ └── _index.md +└── _index.md +``` + +When rendering lesson-1.md: + +```go-html-template +{{ .Section }} → lessons +``` + +In the example above "lessons" is the top level section. + +The `Section` method is often used with the [`where`] function to build a page collection. + +```go-html-template +{{ range where .Site.RegularPages "Section" "lessons" }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +This is similar to using the [`Type`] method with the `where` function + +```go-html-template +{{ range where .Site.RegularPages "Type" "lessons" }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +However, if the `type` field in front matter has been defined on one or more pages, the page collection based on `Type` will be different than the page collection based on `Section`. + + +[`where`]: /functions/collections/where +[`Type`]: /methods/page/type diff --git a/content/en/methods/page/Sections.md b/content/en/methods/page/Sections.md new file mode 100644 index 000000000..d64440038 --- /dev/null +++ b/content/en/methods/page/Sections.md @@ -0,0 +1,69 @@ +--- +title: Sections +description: Returns a collection of section pages, one for each immediate descendant section of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + returnType: page.Pages + signatures: [PAGE.Sections] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +With this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- front matter: weight = 202311 +│ │ ├── auction-1.md +│ │ └── auction-2.md +│ ├── 2023-12/ +│ │ ├── _index.md <-- front matter: weight = 202312 +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- front matter: weight = 30 +│ ├── bidding.md +│ └── payment.md +├── books/ +│ ├── _index.md <-- front matter: weight = 10 +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── _index.md <-- front matter: weight = 20 +│ ├── film-1.md +│ └── film-2.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ range .Sections.ByWeight }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +On the home page, Hugo renders: + +```html +<h2><a href="/films/">Films</a></h2> +<h2><a href="/books/">Books</a></h2> +<h2><a href="/auctions/">Auctions</a></h2> +``` + +On the auctions page, Hugo renders: + +```html +<h2><a href="/auctions/2023-11/">Auctions in November 2023</a></h2> +<h2><a href="/auctions/2023-12/">Auctions in December 2023</a></h2> +``` diff --git a/content/en/methods/page/Site.md b/content/en/methods/page/Site.md new file mode 100644 index 000000000..34748facd --- /dev/null +++ b/content/en/methods/page/Site.md @@ -0,0 +1,19 @@ +--- +title: Site +description: Returns the Site object. +categories: [] +keywords: [] +action: + related: + - methods/page/Sites + returnType: page.siteWrapper + signatures: [PAGE.Site] +--- + +See [Site methods]. + +[Site methods]: /methods/site + +```go-html-template +{{ .Site.Title }} +``` diff --git a/content/en/methods/page/Sitemap.md b/content/en/methods/page/Sitemap.md new file mode 100644 index 000000000..08ff3f5d0 --- /dev/null +++ b/content/en/methods/page/Sitemap.md @@ -0,0 +1,70 @@ +--- +title: Sitemap +description: Returns the sitemap settings for the given page as defined in front matter, falling back to the sitemap settings as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: config.SitemapConfig + signatures: [PAGE.Sitemap] +toc: true +--- + +Access to the `Sitemap` method on a `Page` object is restricted to [sitemap templates]. + +## Methods + +ChangeFreq +: (`string`) How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. Default is "" (change frequency omitted from rendered sitemap). + +```go-html-template +{{ .Sitemap.ChangeFreq }} +``` + +Priority +: (`float`) The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. Default is -1 (priority omitted from rendered sitemap). + +```go-html-template +{{ .Sitemap.Priority }} +``` + +## Example + +With this site configuration: + +{{< code-toggle file=hugo >}} +[sitemap] +changeFreq = 'monthly' +{{< /code-toggle >}} + +And this content: + +{{< code-toggle file=content/news.md fm=true >}} +title = 'News' +[sitemap] +changeFreq = 'hourly' +{{< /code-toggle >}} + +And this simplistic sitemap template: + +{{< code file=layouts/_default/sitemap.xml >}} +{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} +<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" + xmlns:xhtml="http://www.w3.org/1999/xhtml"> + {{ range .Pages }} + <url> + <loc>{{ .Permalink }}</loc> + {{ if not .Lastmod.IsZero }} + <lastmod>{{ .Lastmod.Format "2006-01-02T15:04:05-07:00" | safeHTML }}</lastmod> + {{ end }} + {{ with .Sitemap.ChangeFreq }} + <changefreq>{{ . }}</changefreq> + {{ end }} + </url> + {{ end }} +</urlset> +{{< /code >}} + +The change frequency will be `hourly` for the news page, and `monthly` for other pages. + +[sitemap templates]: /templates/sitemap-template/ diff --git a/content/en/methods/page/Sites.md b/content/en/methods/page/Sites.md new file mode 100644 index 000000000..1fbdfcdcd --- /dev/null +++ b/content/en/methods/page/Sites.md @@ -0,0 +1,69 @@ +--- +title: Sites +description: Returns a collection of all Site objects, one for each language, ordered by language weight. +categories: [] +keywords: [] +action: + related: + - methods/page/Site + returnType: page.Sites + signatures: [PAGE.Sites] +--- + +This is a convenience method to access `.Site.Sites`. + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = false + +[languages.de] +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +title = 'Projekt Dokumentation' +weight = 1 + +[languages.en] +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +title = 'Project Documentation' +weight = 2 +{{< /code-toggle >}} + +This template: + +```go-html-template +<ul> + {{ range .Sites }} + <li><a href="{{ .Home.Permalink }}">{{ .Title }}</a></li> + {{ end }} +</ul> +``` + +Produces a list of links to each home page: + +```html +<ul> + <li><a href="https://example.org/de/">Projekt Dokumentation</a></li> + <li><a href="https://example.org/en/">Project Documentation</a></li> +</ul> +``` + +To render a link to home page of the primary (first) language: + +```go-html-template +{{ with .Sites.First }} + <a href="{{ .Home.Permalink }}">{{ .Title }}</a> +{{ end }} +``` + +This is equivalent to: + +```go-html-template +{{ with index .Sites 0 }} + <a href="{{ .Home.Permalink }}">{{ .Title }}</a> +{{ end }} +``` diff --git a/content/en/methods/page/Slug.md b/content/en/methods/page/Slug.md new file mode 100644 index 000000000..9fdb09b57 --- /dev/null +++ b/content/en/methods/page/Slug.md @@ -0,0 +1,25 @@ +--- +title: Slug +description: Returns the URL slug of the given page as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [PAGE.Slug] +--- + +{{< code-toggle file=content/recipes/spicy-tuna-hand-rolls.md fm=true >}} +title = 'How to make spicy tuna hand rolls' +slug = 'sushi' +{{< /code-toggle >}} + +This page will be served from: + + https://example.org/recipes/sushi + +To get the slug value within a template: + +```go-html-template +{{ .Slug }} → sushi +``` diff --git a/content/en/methods/page/Store.md b/content/en/methods/page/Store.md new file mode 100644 index 000000000..04e1d5256 --- /dev/null +++ b/content/en/methods/page/Store.md @@ -0,0 +1,97 @@ +--- +title: Store +description: Creates a persistent "scratch pad" on the given page to store and manipulate data. +categories: [] +keywords: [] +action: + related: + - methods/page/scratch + - functions/collections/NewScratch + returnType: maps.Scratch + signatures: [PAGE.Store] +aliases: [/functions/store] +--- + +The `Store` method on a `Page` object creates a persistent [scratch pad] to store and manipulate data. In contrast with the [`Scratch`] method, the scratch pad created by the `Store` method is not reset on server rebuilds. + +To create a locally scoped scratch pad that is not attached to a `Page` object, use the [`newScratch`] function. + +[`Scratch`]: /methods/page/scratch +[`newScratch`]: functions/collections/newscratch +[scratch pad]: /getting-started/glossary/#scratch-pad + +## 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.Set "greeting" "Hello" }} +{{ .Store.Add "greeting" "Welcome" }} +{{ .Store.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ .Store.Set "total" 3 }} +{{ .Store.Add "total" 7 }} +{{ .Store.Get "total" }} → 10 +``` + +```go-html-template +{{ .Store.Set "greetings" (slice "Hello") }} +{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }} +{{ .Store.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 +{{ .Store.SetInMap "greetings" "english" "Hello" }} +{{ .Store.SetInMap "greetings" "french" "Bonjour" }} +{{ .Store.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 +{{ .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" }} +``` diff --git a/content/en/methods/page/Summary.md b/content/en/methods/page/Summary.md new file mode 100644 index 000000000..37ce86589 --- /dev/null +++ b/content/en/methods/page/Summary.md @@ -0,0 +1,29 @@ +--- +title: Summary +description: Returns the content summary of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Truncated + - methods/page/Description + returnType: template.HTML + signatures: [PAGE.Summary] +--- + +There are three ways to define the [content summary]: + +1. Let Hugo create the summary based on the first 70 words. You can change the number of words by setting the `summaryLength` in your site configuration. +2. Manually split the content with a `<--more-->` tag in markdown. Everything before the tag is included in the summary. +3. Create a `summary` field in front matter. + +To list the pages in a section with a summary beneath each link: + +```go-html-template +{{ range .Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> + {{ .Summary }} +{{ end }} +``` + +[content summary]: /content-management/summaries diff --git a/content/en/methods/page/TableOfContents.md b/content/en/methods/page/TableOfContents.md new file mode 100644 index 000000000..2ab182e8c --- /dev/null +++ b/content/en/methods/page/TableOfContents.md @@ -0,0 +1,47 @@ +--- +title: TableOfContents +description: Returns a table of contents for the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Fragments + returnType: template.HTML + signatures: [PAGE.TableOfContents] +--- + +The `TableOfContents` method on a `Page` object returns an ordered or unordered list of the markdown [ATX] and [setext] headings within the page content. + +[atx]: https://spec.commonmark.org/0.30/#atx-headings +[setext]: https://spec.commonmark.org/0.30/#setext-headings + +This template code: + +```go-html-template +{{ .TableOfContents }} +``` + +Produces this HTML: + +```html +<nav id="TableOfContents"> + <ul> + <li><a href="#section-1">Section 1</a> + <ul> + <li><a href="#section-11">Section 1.1</a></li> + <li><a href="#section-12">Section 1.2</a></li> + </ul> + </li> + <li><a href="#section-2">Section 2</a></li> + </ul> +</nav> +``` + +By default, the `TableOfContents` method returns an unordered list of level 2 and level 3 headings. You can adjust this in your site configuration: + +{{< code-toggle file=hugo >}} +[markup.tableOfContents] +endLevel = 3 +ordered = false +startLevel = 2 +{{< /code-toggle >}} diff --git a/content/en/methods/page/Title.md b/content/en/methods/page/Title.md new file mode 100644 index 000000000..52e46ff44 --- /dev/null +++ b/content/en/methods/page/Title.md @@ -0,0 +1,38 @@ +--- +title: Title +description: Returns the title of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/LinkTitle + returnType: string + signatures: [PAGE.Title] +--- + +With pages backed by a file, the `Title` method returns the `title` field as defined in front matter: + +{{< code-toggle file=content/about.md fm=true >}} +title = 'About us' +{{< /code-toggle >}} + +```go-html-template +{{ .Title }} → About us +``` + +With section pages not backed by a file, the `Title` method returns the section name, pluralized and converted to title case. + +To disable [pluralization]: + +{{< code-toggle file=hugo >}} +pluralizeListTitles = false +{{< /code-toggle >}} + +To change the [title case style], specify one of `ap`, `chicago`, `go`, `firstupper`, or `none`: + +{{< code-toggle file=hugo >}} +titleCaseStyle = "ap" +{{< /code-toggle >}} + +[pluralization]: /functions/inflect/pluralize +[title case style]: /getting-started/configuration/#configure-title-case diff --git a/content/en/methods/page/TranslationKey.md b/content/en/methods/page/TranslationKey.md new file mode 100644 index 000000000..a9e4b97e9 --- /dev/null +++ b/content/en/methods/page/TranslationKey.md @@ -0,0 +1,74 @@ +--- +title: TranslationKey +description: Returns the translation key of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Translations + - methods/page/AllTranslations + - methods/page/IsTranslated + returnType: string + signatures: [PAGE.TranslationKey] +--- + +The translation key creates a relationship between all translations of a given page. The translation key is derived from the file path, or from the `translationKey` parameter if defined in front matter. + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ ├── buch-1.md +│ │ └── book-2.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +└── _index.md +``` + +And this front matter: + +{{< code-toggle file=content/en/books/book-1.md fm=true >}} +title = 'Book 1' +translationKey = 'foo' +{{< /code-toggle >}} + +{{< code-toggle file=content/de/books/buch-1.md fm=true >}} +title = 'Buch 1' +translationKey = 'foo' +{{< /code-toggle >}} + +When rendering either either of the pages above: + +```go-html-template +{{ .TranslationKey }} → page/foo +``` + +If the front matter of Book 2, in both languages, does not include a translation key: + +```go-html-template +{{ .TranslationKey }} → page/books/book-2 +``` diff --git a/content/en/methods/page/Translations.md b/content/en/methods/page/Translations.md new file mode 100644 index 000000000..7aaee75ab --- /dev/null +++ b/content/en/methods/page/Translations.md @@ -0,0 +1,88 @@ +--- +title: Translations +description: Returns all translation of the given page, excluding the current language. +categories: [] +keywords: [] +action: + related: + - methods/page/AllTranslations + - methods/page/IsTranslated + - methods/page/TranslationKey + returnType: page.Pages + signatures: [PAGE.Translations] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 + +[languages.fr] +contentDir = 'content/fr' +languageCode = 'fr-FR' +languageName = 'Français' +weight = 3 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── fr/ +│ ├── books/ +│ │ └── book-1.md +│ └── _index.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ with .Translations }} + <ul> + {{ range . }} + {{ $lang := .Language.LanguageName}} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }} ({{ $lang }})</a></li> + {{ end }} + </ul> +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of the English site: + +```html +<ul> + <li><a href="/de/books/book-1/">Book 1 (Deutsch)</a></li> + <li><a href="/fr/books/book-1/">Book 1 (Français)</a></li> +</ul> +``` + +Hugo will render this list on the "Book 2" page of the English site: + +```html +<ul> + <li><a href="/de/books/book-1/">Book 1 (Deutsch)</a></li> +</ul> +``` diff --git a/content/en/methods/page/Truncated.md b/content/en/methods/page/Truncated.md new file mode 100644 index 000000000..e6051f0cd --- /dev/null +++ b/content/en/methods/page/Truncated.md @@ -0,0 +1,35 @@ +--- +title: Truncated +description: Reports whether the content length exceeds the summary length. +categories: [] +keywords: [] +action: + related: + - methods/page/Summary + returnType: bool + signatures: [PAGE.Truncated] +--- + +There are three ways to define the [content summary]: + +1. Let Hugo create the summary based on the first 70 words. You can change the number of words by setting the `summaryLength` in your site configuration. +2. Manually split the content with a `<--more-->` tag in markdown. Everything before the tag is included in the summary. +3. Create a `summary` field in front matter. + +{{% note %}} +The `Truncated` method returns `false` if you define the summary in front matter. +{{% /note %}} + +The `Truncated` method returns `true` if the content length exceeds the summary length. This is useful for rendering a "read more" link: + +```go-html-template +{{ range .Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> + {{ .Summary }} + {{ if .Truncated }} + <a href="{{ .RelPermalink }}">Read more...</a> + {{ end }} +{{ end }} +``` + +[content summary]: /content-management/summaries diff --git a/content/en/methods/page/Type.md b/content/en/methods/page/Type.md new file mode 100644 index 000000000..b7c62372b --- /dev/null +++ b/content/en/methods/page/Type.md @@ -0,0 +1,56 @@ +--- +title: Type +description: Returns the content type of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Kind + - methods/page/Layout + - methods/page/Type + returnType: string + signatures: [PAGE.Type] +--- + +The `Type` method on a `Page` object returns the [content type] of the given page. The content type is defined by the `type` field in front matter, or inferred from the top-level directory name if the `type` field in front matter is not defined. + +With this content structure: + +```text +content/ +├── auction/ +│ ├── _index.md +│ ├── item-1.md +│ └── item-2.md <-- front matter: type = books +├── books/ +│ ├── _index.md +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── _index.md +│ ├── film-1.md +│ └── film-2.md +└── _index.md +``` + +To list the books, regardless of [section]: + +```go-html-template +{{ range where .Site.RegularPages.ByTitle "Type" "books" }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +Hugo renders this to; + +```html +<h2><a href="/books/book-1/">Book 1</a></h2> +<h2><a href="/books/book-2/">Book 2</a></h2> +<h2><a href="/auction/item-2/">Item 2</a></h2> +``` + +The `type` field in front matter is also useful for targeting a template. See [details]. + +[content type]: /getting-started/glossary/#content-type +[details]: /templates/lookup-order/#target-a-template +[section]: /getting-started/glossary/#section diff --git a/content/en/methods/page/Weight.md b/content/en/methods/page/Weight.md new file mode 100644 index 000000000..75c75db86 --- /dev/null +++ b/content/en/methods/page/Weight.md @@ -0,0 +1,27 @@ +--- +title: Weight +description: Returns the weight of the given page as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [PAGE.Weight] +--- + +The `Weight` method on a `Page` object returns the [weight] of the given page as defined in front matter. + +[weight]: /getting-started/glossary/#weight + +{{< code-toggle file=content/recipes/sushi.md fm=true >}} +title = 'How to make spicy tuna hand rolls' +weight = 42 +{{< /code-toggle >}} + +Page weight controls the position of a page within a collection that is sorted by weight. Assign weights using non-zero integers. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted elements are placed at the end of the collection. + +Although rarely used within a template, you can access the value with: + +```go-html-template +{{ .Weight }} → 42 +``` diff --git a/content/en/methods/page/WordCount.md b/content/en/methods/page/WordCount.md new file mode 100644 index 000000000..bb1fdcf94 --- /dev/null +++ b/content/en/methods/page/WordCount.md @@ -0,0 +1,20 @@ +--- +title: WordCount +description: Returns the number of words in the content of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/FuzzyWordCount + - methods/page/ReadingTime + returnType: int + signatures: [PAGE.WordCount] +--- + +```go-html-template +{{ .WordCount }} → 103 +``` + +To round up to nearest multiple of 100, use the [`FuzzyWordCount`] method. + +[`FuzzyWordCount`]: /methods/page/fuzzywordcount diff --git a/content/en/methods/page/_common/_index.md b/content/en/methods/page/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/content/en/methods/page/_common/_index.md @@ -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. +--> diff --git a/content/en/methods/page/_common/definition-of-section.md b/content/en/methods/page/_common/definition-of-section.md new file mode 100644 index 000000000..7dc600789 --- /dev/null +++ b/content/en/methods/page/_common/definition-of-section.md @@ -0,0 +1,5 @@ +--- +# Do not remove front matter. +--- + +A _section_ is a top-level content directory, or any content directory with an _index.md file. diff --git a/content/en/methods/page/_common/output-format-definition.md b/content/en/methods/page/_common/output-format-definition.md new file mode 100644 index 000000000..25944464a --- /dev/null +++ b/content/en/methods/page/_common/output-format-definition.md @@ -0,0 +1,11 @@ +--- +# Do not remove front matter. +--- + +Hugo generates one or more files per page when building a site. For example, when rendering home, [section], [taxonomy], and [term] pages, Hugo generates an HTML file and an RSS file. Both HTML and RSS are built-in _output formats_. Create multiple output formats, and control generation based on [page kind], or by enabling one or more output formats for one or more pages. See [details]. + +[section]: /getting-started/glossary/#section +[taxonomy]: /getting-started/glossary/#taxonomy +[term]: /getting-started/glossary/#term +[page kind]: /getting-started/glossary/#page-kind +[details]: /templates/output-formats diff --git a/content/en/methods/page/_common/output-format-methods.md b/content/en/methods/page/_common/output-format-methods.md new file mode 100644 index 000000000..5e7111fe5 --- /dev/null +++ b/content/en/methods/page/_common/output-format-methods.md @@ -0,0 +1,27 @@ +--- +# Do not remove front matter. +--- + +Get IDENTIFIER +: (`any`) Returns the `OutputFormat` object with the given identifier. + +MediaType +: (`media.Type`) Returns the media type of the output format. + +MediaType.MainType +: (`string`) Returns the main type of the output format's media type. + +MediaType.SubType +: (`string`) Returns the subtype of the current format's media type. + +Name +: (`string`) Returns the output identifier of the output format. + +Permalink +: (`string`) Returns the permalink of the page generated by the current output format. + +Rel +: (`string`) Returns the `rel` value of the output format, either the default or as defined in the site configuration. + +RelPermalink +: (`string`) Returns the relative permalink of the page generated by the current output format. diff --git a/content/en/methods/page/_common/scratch-methods.md b/content/en/methods/page/_common/scratch-methods.md new file mode 100644 index 000000000..c09b4aadc --- /dev/null +++ b/content/en/methods/page/_common/scratch-methods.md @@ -0,0 +1,79 @@ +--- +# Do not remove front matter. +--- + +## Methods + +Set +: Sets the value of a given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +``` + +Get +: Gets the value of a given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.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 +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.Add "greeting" "Welcome" }} +{{ .Scratch.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ .Scratch.Set "total" 3 }} +{{ .Scratch.Add "total" 7 }} +{{ .Scratch.Get "total" }} → 10 +``` + +```go-html-template +{{ .Scratch.Set "greetings" (slice "Hello") }} +{{ .Scratch.Add "greetings" (slice "Welcome" "Cheers") }} +{{ .Scratch.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 +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +{{ .Scratch.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 +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +{{ .Scratch.DeleteInMap "greetings" "english" }} +{{ .Scratch.Get "greetings" }} → map[french:Bonjour] +``` + +GetSortedMapValues +: Returns 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 +: Removes the given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.Delete "greeting" }} +``` diff --git a/content/en/methods/page/_index.md b/content/en/methods/page/_index.md new file mode 100644 index 000000000..278541c5a --- /dev/null +++ b/content/en/methods/page/_index.md @@ -0,0 +1,12 @@ +--- +title: Page methods +linkTitle: Page +description: Use these methods with a Page object. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods with a Page object. |