diff options
author | Bjørn Erik Pedersen <[email protected]> | 2023-12-04 15:24:01 +0100 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2023-12-04 15:24:01 +0100 |
commit | d19ed4d4e69f51873135f05a51831d25ecc2071e (patch) | |
tree | 74dfd9af2b0f4a6c0933266c50ceaa569d388c71 /docs/content/en/methods | |
parent | 9f978d387f8b7cb6bc03fe6b4dd52bb16862a784 (diff) | |
parent | 35dec7c96f7ee3eb17dd444f7067f0c776fb56ae (diff) | |
download | hugo-d19ed4d4e69f51873135f05a51831d25ecc2071e.tar.gz hugo-d19ed4d4e69f51873135f05a51831d25ecc2071e.zip |
Merge commit '35dec7c96f7ee3eb17dd444f7067f0c776fb56ae'
Diffstat (limited to 'docs/content/en/methods')
253 files changed, 10801 insertions, 0 deletions
diff --git a/docs/content/en/methods/_common/_index.md b/docs/content/en/methods/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/content/en/methods/_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/docs/content/en/methods/_common/next-prev-on-page-vs-next-prev-on-pages.md b/docs/content/en/methods/_common/next-prev-on-page-vs-next-prev-on-pages.md new file mode 100644 index 000000000..4ae3a0f39 --- /dev/null +++ b/docs/content/en/methods/_common/next-prev-on-page-vs-next-prev-on-pages.md @@ -0,0 +1,37 @@ +--- +# Do not remove front matter. +--- + +The `Next` and `Prev` methods on a `Pages` object are more flexible than the `Next` and `Prev` methods on a `Page` object. + +||Page collection|Custom sort order +:--|:--|:-: +[`PAGES.Next`] and [`PAGES.Prev`]|locally defined|✔️ +[`PAGE.Next`] and [`PAGE.Prev`]|globally defined|❌ + +[`PAGES.Next`]: /methods/pages/next +[`PAGES.Prev`]: /methods/pages/prev +[`PAGE.Next`]: /methods/page/next +[`PAGE.Prev`]: /methods/page/prev + +locally defined +: Build the page collection every time you call `PAGES.Next` and `PAGES.Prev`. Navigation between pages is relative to the current page's position within the local collection, independent of the global collection. + +With a local collection, the navigation sort order is the same as the collection sort order. + +globally defined +: Build the page collection once, on a list page. Navigation between pages is relative to the current page's position within the global collection. + +With a global collection, the navigation sort order is fixed, using Hugo's default sort order. In order of precedence: + +1. Page [weight] +2. Page [date] (descending) +3. Page [linkTitle], falling back to page [title] +4. Page file path if the page is backed by a file + +For example, with a global collection sorted by title, the navigation sort order will use Hugo's default sort order. This is probably not what you want or expect. For this reason, the `Next` and `Prev` methods on a `Pages` object are generally a better choice. + +[date]: /methods/page/date +[weight]: /methods/page/weight +[linkTitle]: /methods/page/linktitle +[title]: /methods/page/title diff --git a/docs/content/en/methods/_index.md b/docs/content/en/methods/_index.md new file mode 100644 index 000000000..c12bd9d4d --- /dev/null +++ b/docs/content/en/methods/_index.md @@ -0,0 +1,16 @@ +--- +title: Methods +linkTitle: Overview +description: A list of Hugo template methods including examples. +categories: [] +keywords: [] +menu: + docs: + identifier: methods-overview + parent: methods + weight: 10 +weight: 10 +showSectionMenu: true +--- + +Use these methods within your templates. diff --git a/docs/content/en/methods/duration/Abs.md b/docs/content/en/methods/duration/Abs.md new file mode 100644 index 000000000..d035f97b6 --- /dev/null +++ b/docs/content/en/methods/duration/Abs.md @@ -0,0 +1,17 @@ +--- +title: Abs +description: Returns the absolute value of the given time.Duration value. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: time.Duration + signatures: [DURATION.Abs] +--- + +```go-html-template +{{ $d = time.ParseDuration "-3h" }} +{{ $d.Abs }} → 3h0m0s +``` diff --git a/docs/content/en/methods/duration/Hours.md b/docs/content/en/methods/duration/Hours.md new file mode 100644 index 000000000..5b2d893b9 --- /dev/null +++ b/docs/content/en/methods/duration/Hours.md @@ -0,0 +1,17 @@ +--- +title: Hours +description: Returns the time.Duration value as a floating point number of hours. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: float64 + signatures: [DURATION.Hours] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Hours }} → 3.5420833333333333 +``` diff --git a/docs/content/en/methods/duration/Microseconds.md b/docs/content/en/methods/duration/Microseconds.md new file mode 100644 index 000000000..c8b210c94 --- /dev/null +++ b/docs/content/en/methods/duration/Microseconds.md @@ -0,0 +1,17 @@ +--- +title: Microseconds +description: Returns the time.Duration value as an integer microsecond count. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: int64 + signatures: [DURATION.Microseconds] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Microseconds }} → 12751500000 +``` diff --git a/docs/content/en/methods/duration/Milliseconds.md b/docs/content/en/methods/duration/Milliseconds.md new file mode 100644 index 000000000..32809027a --- /dev/null +++ b/docs/content/en/methods/duration/Milliseconds.md @@ -0,0 +1,17 @@ +--- +title: Milliseconds +description: Returns the time.Duration value as an integer millisecond count. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: int64 + signatures: [DURATION.Milliseconds] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Milliseconds }} → 12751500 +``` diff --git a/docs/content/en/methods/duration/Minutes.md b/docs/content/en/methods/duration/Minutes.md new file mode 100644 index 000000000..d3e57fba5 --- /dev/null +++ b/docs/content/en/methods/duration/Minutes.md @@ -0,0 +1,17 @@ +--- +title: Minutes +description: Returns the time.Duration value as a floating point number of minutes. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: float64 + signatures: [DURATION.Minutes] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Minutes }} → 212.525 +``` diff --git a/docs/content/en/methods/duration/Nanoseconds.md b/docs/content/en/methods/duration/Nanoseconds.md new file mode 100644 index 000000000..66d2981f2 --- /dev/null +++ b/docs/content/en/methods/duration/Nanoseconds.md @@ -0,0 +1,17 @@ +--- +title: Nanoseconds +description: Returns the time.Duration value as an integer nanosecond count. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: int64 + signatures: [DURATION.Nanoseconds] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Nanoseconds }} → 12751500000000 +``` diff --git a/docs/content/en/methods/duration/Round.md b/docs/content/en/methods/duration/Round.md new file mode 100644 index 000000000..0722a6076 --- /dev/null +++ b/docs/content/en/methods/duration/Round.md @@ -0,0 +1,20 @@ +--- +title: Round +description: Returns the result of rounding DURATION1 to the nearest multiple of DURATION2. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: + signatures: [DURATION1.Round DURATION2] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} + +{{ $d.Round (time.ParseDuration "2h") }} → 4h0m0s +{{ $d.Round (time.ParseDuration "3m") }} → 3h33m0s +{{ $d.Round (time.ParseDuration "4s") }} → 3h32m32s +``` diff --git a/docs/content/en/methods/duration/Seconds.md b/docs/content/en/methods/duration/Seconds.md new file mode 100644 index 000000000..d23d5ec15 --- /dev/null +++ b/docs/content/en/methods/duration/Seconds.md @@ -0,0 +1,17 @@ +--- +title: Seconds +description: Returns the time.Duration value as a floating point number of seconds. +categories: [] +keywords: [] +action: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: float64 + signatures: [DURATION.Seconds] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} +{{ $d.Seconds }} → 12751.5 +``` diff --git a/docs/content/en/methods/duration/Truncate.md b/docs/content/en/methods/duration/Truncate.md new file mode 100644 index 000000000..795fcad76 --- /dev/null +++ b/docs/content/en/methods/duration/Truncate.md @@ -0,0 +1,21 @@ +--- +title: Truncate +description: Returns the result of rounding DURATION1 toward zero to a multiple of DURATION2. +categories: [] +keywords: [] +action: + related: + related: + - functions/time/Duration + - functions/time/ParseDuration + returnType: time.Duration + signatures: [DURATION1.Truncate DURATION2] +--- + +```go-html-template +{{ $d = time.ParseDuration "3.5h2.5m1.5s" }} + +{{ $d.Truncate (time.ParseDuration "2h") }} → 2h0m0s +{{ $d.Truncate (time.ParseDuration "3m") }} → 3h30m0s +{{ $d.Truncate (time.ParseDuration "4s") }} → 3h32m28s +``` diff --git a/docs/content/en/methods/duration/_index.md b/docs/content/en/methods/duration/_index.md new file mode 100644 index 000000000..9fc4f814c --- /dev/null +++ b/docs/content/en/methods/duration/_index.md @@ -0,0 +1,12 @@ +--- +title: Duration methods +linkTitle: Duration +description: Use these methods with time.Duration values. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods with time.Duration values. diff --git a/docs/content/en/methods/menu-entry/Children.md b/docs/content/en/methods/menu-entry/Children.md new file mode 100644 index 000000000..af2af6dce --- /dev/null +++ b/docs/content/en/methods/menu-entry/Children.md @@ -0,0 +1,67 @@ +--- +title: Children +description: Returns a collection of child menu entries, if any, under the given menu entry. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/HasChildren + returnType: navigation.Menu + signatures: [MENUENTRY.Children] +--- + +Use the `Children` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menu.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menu.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +And this template: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li> + <a href="{{ .URL }}">{{ .Name }}</a> + {{ if .HasChildren }} + <ul> + {{ range .Children }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} + </ul> + {{ end }} + </li> + {{ end }} +</ul> +``` + +Hugo renders this HTML: + +```html +<ul> + <li> + <a href="/products/">Products</a> + <ul> + <li><a href="/products/product-1/">Product 1</a></li> + <li><a href="/products/product-2/">Product 2</a></li> + </ul> + </li> +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/HasChildren.md b/docs/content/en/methods/menu-entry/HasChildren.md new file mode 100644 index 000000000..d906987e8 --- /dev/null +++ b/docs/content/en/methods/menu-entry/HasChildren.md @@ -0,0 +1,67 @@ +--- +title: HasChildren +description: Reports whether the given menu entry has child menu entries. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/Children + returnType: bool + signatures: [MENUENTRY.HasChildren] +--- + +Use the `HasChildren` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menu.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menu.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +And this template: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li> + <a href="{{ .URL }}">{{ .Name }}</a> + {{ if .HasChildren }} + <ul> + {{ range .Children }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} + </ul> + {{ end }} + </li> + {{ end }} +</ul> +``` + +Hugo renders this HTML: + +```html +<ul> + <li> + <a href="/products/">Products</a> + <ul> + <li><a href="/products/product-1/">Product 1</a></li> + <li><a href="/products/product-2/">Product 2</a></li> + </ul> + </li> +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/Identifier.md b/docs/content/en/methods/menu-entry/Identifier.md new file mode 100644 index 000000000..a4d7e129e --- /dev/null +++ b/docs/content/en/methods/menu-entry/Identifier.md @@ -0,0 +1,44 @@ +--- +title: Identifier +description: Returns the `identifier` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Identifier] +--- + +The `Identifier` method returns the `identifier` property of the menu entry. If you define the menu entry [automatically], it returns the page's section. + +[automatically]: /content-management/menus/#define-automatically + +{{< code-toggle file=hugo >}} +[[menu.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + +[[menu.main]] +identifier = 'contact' +name = 'Contact' +pageRef = '/contact' +weight = 20 +{{< /code-toggle >}} + +This example uses the `Identifier` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ or (T .Identifier) .Name }}</a></li> + {{ end }} +</ul> +``` + +{{% note %}} +In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables. + +[details]: /content-management/menus/#properties-front-matter +{{% /note %}} diff --git a/docs/content/en/methods/menu-entry/KeyName.md b/docs/content/en/methods/menu-entry/KeyName.md new file mode 100644 index 000000000..8031441b9 --- /dev/null +++ b/docs/content/en/methods/menu-entry/KeyName.md @@ -0,0 +1,39 @@ +--- +title: KeyName +description: Returns the `identifier` property of the given menu entry, falling back to its `name` property. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.KeyName] +--- + +In this menu definition, the second entry does not contain an `identifier`, so the `Identifier` method returns its `name` property instead: + +{{< code-toggle file=hugo >}} +[[menu.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +weight = 20 +{{< /code-toggle >}} + +This example uses the `KeyName` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ or (T (.KeyName | lower)) .Name }}</a></li> + {{ end }} +</ul> +``` + +In the example above, we need to pass the value returned by `.KeyName` through the [`lower`] function because the keys in the translation table are lowercase. + +[`lower`]: functions/strings/tolower diff --git a/docs/content/en/methods/menu-entry/Menu.md b/docs/content/en/methods/menu-entry/Menu.md new file mode 100644 index 000000000..6827519bd --- /dev/null +++ b/docs/content/en/methods/menu-entry/Menu.md @@ -0,0 +1,24 @@ +--- +title: Menu +description: Returns the identifier of the menu that contains the given menu entry. +categories: [] +keywords: [] +action: + related: + - methods/page/IsMenuCurrent + - methods/page/HasMenuCurrent + returnType: string + signatures: [MENUENTRY.Menu] +--- + +```go-html-template +{{ range .Site.Menus.main }} + {{ .Menu }} → main +{{ end }} +``` + +Use this method with the [`IsMenuCurrent`] and [`HasMenuCurrent`] methods on a `Page` object to set "active" and "ancestor" classes on a rendered entry. See [this example]. + +[`HasMenuCurrent`]: /methods/page/hasmenucurrent +[`IsMenuCurrent`]: /methods/page/ismenucurrent +[this example]: /templates/menu-templates/#example diff --git a/docs/content/en/methods/menu-entry/Name.md b/docs/content/en/methods/menu-entry/Name.md new file mode 100644 index 000000000..d722da07c --- /dev/null +++ b/docs/content/en/methods/menu-entry/Name.md @@ -0,0 +1,28 @@ +--- +title: Name +description: Returns the `name` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Name] +--- + +If you define the menu entry [automatically], the `Name` method returns the page’s [`LinkTitle`], falling back to its [`Title`]. + +If you define the menu entry [in front matter] or [in site configuration], the `Name` method returns the `name` property, falling back to the page’s `LinkTitle`, then to its `Title`. + +[`LinkTitle`]: /methods/page/linktitle +[`Title`]: /methods/page/title +[automatically]: /content-management/menus/#define-automatically +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/#define-in-site-configuration + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/Page.md b/docs/content/en/methods/menu-entry/Page.md new file mode 100644 index 000000000..9b23f7b73 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Page.md @@ -0,0 +1,53 @@ +--- +title: Page +description: Returns the Page object associated with the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.pageState + signatures: [MENUENTRY.Page] +--- + +Regardless of how you [define menu entries], an entry associated with a page has access to its [methods]. + +In this menu definition, the first two entries are associated with a page, the last entry is not: + +{{< code-toggle file=hugo >}} +[[menu.main]] +pageRef = '/about' +weight = 10 + +[[menu.main]] +pageRef = '/contact' +weight = 20 + +[[menu.main]] +name = 'Hugo' +url = 'https://gohugo.io' +weight = 30 +{{< /code-toggle >}} + +In this example, if the menu entry is associated with a page, we use page's [`RelPermalink`] and [`LinkTitle`] when rendering the anchor element. + +If the entry is not associated with a page, we use its `url` and `name` properties. + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + {{ with .Page }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ else }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} + {{ end }} +</ul> +``` + +See the [menu templates] section for more information. + +[`LinkTitle`]: /methods/page/linktitle +[`RelPermalink`]: /methods/page/relpermalink +[define menu entries]: /content-management/menus/ +[menu templates]: /templates/menu-templates/#page-references +[methods]: /methods/page diff --git a/docs/content/en/methods/menu-entry/Params.md b/docs/content/en/methods/menu-entry/Params.md new file mode 100644 index 000000000..1486c12cb --- /dev/null +++ b/docs/content/en/methods/menu-entry/Params.md @@ -0,0 +1,62 @@ +--- +title: Params +description: Returns the `params` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: maps.Params + signatures: [MENUENTRY.Params] +--- + +When you define menu entries [in site configuration] or [in front matter], you can include a `params` key to attach additional information to the entry. For example: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'About' +pageRef = '/about' +weight = 10 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +weight = 20 + +[[menu.main]] +name = 'Hugo' +url = 'https://gohugo.io' +weight = 30 +[menu.main.params] + rel = 'external' +{{< /code-toggle >}} + +With this template: + + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li> + <a href="{{ .URL }}" {{ with .Params.rel }}rel="{{ . }}"{{ end }}> + {{ .Name }} + </a> + </li> + {{ end }} +</ul> +``` + +Hugo renders: + +```html +<ul> + <li><a href="/about/">About</a></li> + <li><a href="/contact/">Contact</a></li> + <li><a href="https://gohugo.io" rel="external">Hugo</a></li> +</ul> +``` + +See the [menu templates] section for more information. + +[menu templates]: /templates/menu-templates/#menu-entry-parameters +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/ diff --git a/docs/content/en/methods/menu-entry/Parent.md b/docs/content/en/methods/menu-entry/Parent.md new file mode 100644 index 000000000..897712831 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Parent.md @@ -0,0 +1,51 @@ +--- +title: Parent +description: Returns the `parent` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Parent] +--- + +With this menu definition: + +{{< code-toggle file=hugo >}} +[menu] +[[menu.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menu.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menu.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +This template renders the nested menu, listing the `parent` property next each of the child entries: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li> + <a href="{{ .URL }}">{{ .Name }}</a> + {{ if .HasChildren }} + <ul> + {{ range .Children }} + <li><a href="{{ .URL }}">{{ .Name }}</a> ({{ .Parent }})</li> + {{ end }} + </ul> + {{ end }} + </li> + {{ end }} +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/Post.md b/docs/content/en/methods/menu-entry/Post.md new file mode 100644 index 000000000..b2fa2da5b --- /dev/null +++ b/docs/content/en/methods/menu-entry/Post.md @@ -0,0 +1,13 @@ +--- +title: Post +description: Returns the `post` property of the given menu entry. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/Pre + returnType: template.HTML + signatures: [MENUENTRY.Post] +--- + +{{% include "methods/menu-entry/_common/pre-post.md" %}} diff --git a/docs/content/en/methods/menu-entry/Pre.md b/docs/content/en/methods/menu-entry/Pre.md new file mode 100644 index 000000000..df7c8f16e --- /dev/null +++ b/docs/content/en/methods/menu-entry/Pre.md @@ -0,0 +1,13 @@ +--- +title: Pre +description: Returns the `pre` property of the given menu entry. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/Post + returnType: template.HTML + signatures: [MENUENTRY.Pre] +--- + +{{% include "methods/menu-entry/_common/pre-post.md" %}} diff --git a/docs/content/en/methods/menu-entry/Title.md b/docs/content/en/methods/menu-entry/Title.md new file mode 100644 index 000000000..c1eec2cc0 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Title.md @@ -0,0 +1,28 @@ +--- +title: Title +description: Returns the `title` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Title] +--- + +If you define the menu entry [automatically], the `Title` method returns the page’s [`LinkTitle`], falling back to its [`Title`]. + +If you define the menu entry [in front matter] or [in site configuration], the `Name` method returns the `title` property, falling back to the page’s `LinkTitle`, then to its `Title`. + +[`LinkTitle`]: /methods/page/linktitle +[`Title`]: /methods/page/title +[automatically]: /content-management/menus/#define-automatically +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/#define-in-site-configuration + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ .Title }}</a></li> + {{ end }} +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/URL.md b/docs/content/en/methods/menu-entry/URL.md new file mode 100644 index 000000000..c2b314b58 --- /dev/null +++ b/docs/content/en/methods/menu-entry/URL.md @@ -0,0 +1,23 @@ +--- +title: URL +description: Returns the relative permalink of the page associated with the given menu entry, else its `url` property. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.URL] +--- + +For menu entries associated with a page, the `URL` method returns the page's [`RelPermalink`], otherwise it returns the entry's `url` property. + + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +[`RelPermalink`]: /methods/page/relpermalink diff --git a/docs/content/en/methods/menu-entry/Weight.md b/docs/content/en/methods/menu-entry/Weight.md new file mode 100644 index 000000000..7b0c24ae8 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Weight.md @@ -0,0 +1,31 @@ +--- +title: Weight +description: Returns the `weight` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [MENUENTRY.Weight] +--- + +If you define the menu entry [automatically], the `Weight` method returns the page’s [`Weight`]. + +If you define the menu entry [in front matter] or [in site configuration], the `Weight` method returns the `weight` property, falling back to the page’s `Weight`. + +[`Weight`]: /methods/page/weight +[automatically]: /content-management/menus/#define-automatically +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/#define-in-site-configuration + +In this contrived example, we limit the number of menu entries based on weight: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + {{ if le .Weight 42 }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} + {{ end }} +</ul> +``` diff --git a/docs/content/en/methods/menu-entry/_common/_index.md b/docs/content/en/methods/menu-entry/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/content/en/methods/menu-entry/_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/docs/content/en/methods/menu-entry/_common/pre-post.md b/docs/content/en/methods/menu-entry/_common/pre-post.md new file mode 100644 index 000000000..8cc787ea9 --- /dev/null +++ b/docs/content/en/methods/menu-entry/_common/pre-post.md @@ -0,0 +1,39 @@ +--- +# Do not remove front matter. +--- + +In this site configuration we enable rendering of [emoji shortcodes], and add emoji shortcodes before (pre) and after (post) each menu entry: + +{{< code-toggle file=hugo >}} +enableEmoji = true + +[[menu.main]] +name = 'About' +pageRef = '/about' +post = ':point_left:' +pre = ':point_right:' +weight = 10 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +post = ':arrow_left:' +pre = ':arrow_right:' +weight = 20 +{{< /code-toggle >}} + +To render the menu: + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li> + {{ .Pre | markdownify }} + <a href="{{ .URL }}">{{ .Name }}</a> + {{ .Post | markdownify }} + </li> + {{ end }} +</ul> +``` + +[emoji shortcodes]: /quick-reference/emojis/ diff --git a/docs/content/en/methods/menu-entry/_index.md b/docs/content/en/methods/menu-entry/_index.md new file mode 100644 index 000000000..d89663593 --- /dev/null +++ b/docs/content/en/methods/menu-entry/_index.md @@ -0,0 +1,12 @@ +--- +title: Menu entry methods +linkTitle: Menu entry +description: Use these methods in your menu templates. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods in your menu templates. diff --git a/docs/content/en/methods/menu/ByName.md b/docs/content/en/methods/menu/ByName.md new file mode 100644 index 000000000..3f1c52b2e --- /dev/null +++ b/docs/content/en/methods/menu/ByName.md @@ -0,0 +1,65 @@ +--- +title: ByName +description: Returns the given menu with its entries sorted by name. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.ByName] +--- + +The `Sort` method returns the given menu with its entries sorted by `name`. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menu.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by `name`: + +```go-html-template +<ul> + {{ range .Site.Menus.main.ByName }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/about/">About</a></li> + <li><a href="/contact">Contact</a></li> + <li><a href="/services/">Services</a></li> +</ul> +``` + +You can also sort menu entries using the [`sort`] function. For example, to sort by `name` in descending order: + +```go-html-template +<ul> + {{ range sort .Site.Menus.main "Name" "desc" }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. + +[`sort`]: /functions/collections/sort diff --git a/docs/content/en/methods/menu/ByWeight.md b/docs/content/en/methods/menu/ByWeight.md new file mode 100644 index 000000000..c915914db --- /dev/null +++ b/docs/content/en/methods/menu/ByWeight.md @@ -0,0 +1,76 @@ +--- +title: ByWeight +description: Returns the given menu with its entries sorted by weight, then by name, then by identifier. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.ByWeight] +--- + +The `ByWeight` method returns the given menu with its entries sorted by [`weight`], then by `name`, then by `identifier`. This is the default sort order. + +[`weight`]: /getting-started/glossary/#weight + +Consider this menu definition: + +{{< code-toggle file=hugo >}} +[[menu.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 20 + +[[menu.main]] +identifier = 'services' +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menu.main]] +identifier = 'contact' +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by `weight`, then by `name`, then by `identifier`: + +```go-html-template +<ul> + {{ range .Site.Menus.main.ByWeight }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/services/">Services</a></li> + <li><a href="/about/">About</a></li> + <li><a href="/contact">Contact</a></li> +</ul> +``` + +{{% note %}} +In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables. + +[details]: /content-management/menus/#properties-front-matter +{{% /note %}} + +You can also sort menu entries using the [`sort`] function. For example, to sort by `weight` in descending order: + +```go-html-template +<ul> + {{ range sort .Site.Menus.main "Weight" "desc" }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. + +[`sort`]: /functions/collections/sort diff --git a/docs/content/en/methods/menu/Limit.md b/docs/content/en/methods/menu/Limit.md new file mode 100644 index 000000000..12263e811 --- /dev/null +++ b/docs/content/en/methods/menu/Limit.md @@ -0,0 +1,50 @@ +--- +title: Limit +description: Returns the given menu, limited to the first N entries. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.Limit N] +--- + +The `Limit` method returns the given menu, limited to the first N entries. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menu.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by name, and limit to the first 2 entries: + +```go-html-template +<ul> + {{ range .Site.Menus.main.ByName.Limit 2 }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/about/">About</a></li> + <li><a href="/contact">Contact</a></li> +</ul> +``` diff --git a/docs/content/en/methods/menu/Reverse.md b/docs/content/en/methods/menu/Reverse.md new file mode 100644 index 000000000..989132d60 --- /dev/null +++ b/docs/content/en/methods/menu/Reverse.md @@ -0,0 +1,51 @@ +--- +title: Reverse +description: Returns the given menu, reversing the sort order of its entries. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.Reverse] +--- + +The `Reverse` method returns the given menu, reversing the sort order of its entries. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menu.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menu.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by name in descending order: + +```go-html-template +<ul> + {{ range .Site.Menus.main.ByName.Reverse }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/services/">Services</a></li> + <li><a href="/contact">Contact</a></li> + <li><a href="/about/">About</a></li> +</ul> +``` diff --git a/docs/content/en/methods/menu/_index.md b/docs/content/en/methods/menu/_index.md new file mode 100644 index 000000000..f5b925fd6 --- /dev/null +++ b/docs/content/en/methods/menu/_index.md @@ -0,0 +1,12 @@ +--- +title: Menu methods +linkTitle: Menu +description: Use these methods when ranging through menu entries. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods when ranging through menu entries. diff --git a/docs/content/en/methods/page/Aliases.md b/docs/content/en/methods/page/Aliases.md new file mode 100644 index 000000000..15e73384b --- /dev/null +++ b/docs/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/docs/content/en/methods/page/AllTranslations.md b/docs/content/en/methods/page/AllTranslations.md new file mode 100644 index 000000000..b9c156127 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/AlternativeOutputFormats.md b/docs/content/en/methods/page/AlternativeOutputFormats.md new file mode 100644 index 000000000..b48d1adf4 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Ancestors.md b/docs/content/en/methods/page/Ancestors.md new file mode 100644 index 000000000..3bf36d9aa --- /dev/null +++ b/docs/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/docs/content/en/methods/page/BundleType.md b/docs/content/en/methods/page/BundleType.md new file mode 100644 index 000000000..77d1d72eb --- /dev/null +++ b/docs/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/docs/content/en/methods/page/CodeOwners.md b/docs/content/en/methods/page/CodeOwners.md new file mode 100644 index 000000000..ec7e5c8bf --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Content.md b/docs/content/en/methods/page/Content.md new file mode 100644 index 000000000..40a057f02 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/CurrentSection.md b/docs/content/en/methods/page/CurrentSection.md new file mode 100644 index 000000000..03cb9eb3d --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Data.md b/docs/content/en/methods/page/Data.md new file mode 100644 index 000000000..4eccde6ff --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Date.md b/docs/content/en/methods/page/Date.md new file mode 100644 index 000000000..83192f94c --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Description.md b/docs/content/en/methods/page/Description.md new file mode 100644 index 000000000..fbb43b8b5 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Draft.md b/docs/content/en/methods/page/Draft.md new file mode 100644 index 000000000..fd55a9bc9 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Eq.md b/docs/content/en/methods/page/Eq.md new file mode 100644 index 000000000..1be416295 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/ExpiryDate.md b/docs/content/en/methods/page/ExpiryDate.md new file mode 100644 index 000000000..353546449 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/File.md b/docs/content/en/methods/page/File.md new file mode 100644 index 000000000..c39d1a64d --- /dev/null +++ b/docs/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/docs/content/en/methods/page/FirstSection.md b/docs/content/en/methods/page/FirstSection.md new file mode 100644 index 000000000..f757aa2d2 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Fragments.md b/docs/content/en/methods/page/Fragments.md new file mode 100644 index 000000000..bae1c7d03 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/FuzzyWordCount.md b/docs/content/en/methods/page/FuzzyWordCount.md new file mode 100644 index 000000000..600ad48d5 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/GetPage.md b/docs/content/en/methods/page/GetPage.md new file mode 100644 index 000000000..ed072932a --- /dev/null +++ b/docs/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/docs/content/en/methods/page/GetTerms.md b/docs/content/en/methods/page/GetTerms.md new file mode 100644 index 000000000..3020e4c2e --- /dev/null +++ b/docs/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/docs/content/en/methods/page/GitInfo.md b/docs/content/en/methods/page/GitInfo.md new file mode 100644 index 000000000..88137614c --- /dev/null +++ b/docs/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/docs/content/en/methods/page/HasMenuCurrent.md b/docs/content/en/methods/page/HasMenuCurrent.md new file mode 100644 index 000000000..68b645905 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/HasShortcode.md b/docs/content/en/methods/page/HasShortcode.md new file mode 100644 index 000000000..81268ecba --- /dev/null +++ b/docs/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/docs/content/en/methods/page/HeadingsFiltered.md b/docs/content/en/methods/page/HeadingsFiltered.md new file mode 100644 index 000000000..a39c48da1 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/InSection.md b/docs/content/en/methods/page/InSection.md new file mode 100644 index 000000000..b98fbc808 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsAncestor.md b/docs/content/en/methods/page/IsAncestor.md new file mode 100644 index 000000000..ca23c0868 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsDescendant.md b/docs/content/en/methods/page/IsDescendant.md new file mode 100644 index 000000000..f1042564e --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsHome.md b/docs/content/en/methods/page/IsHome.md new file mode 100644 index 000000000..b688f88c0 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsMenuCurrent.md b/docs/content/en/methods/page/IsMenuCurrent.md new file mode 100644 index 000000000..61283fd8b --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsNode.md b/docs/content/en/methods/page/IsNode.md new file mode 100644 index 000000000..dfdf435c5 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsPage.md b/docs/content/en/methods/page/IsPage.md new file mode 100644 index 000000000..672ee61f4 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsSection.md b/docs/content/en/methods/page/IsSection.md new file mode 100644 index 000000000..b02e58a45 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/IsTranslated.md b/docs/content/en/methods/page/IsTranslated.md new file mode 100644 index 000000000..6a8f3f69e --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Keywords.md b/docs/content/en/methods/page/Keywords.md new file mode 100644 index 000000000..5ad37ce51 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Kind.md b/docs/content/en/methods/page/Kind.md new file mode 100644 index 000000000..d901e9a7d --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Language.md b/docs/content/en/methods/page/Language.md new file mode 100644 index 000000000..4e65107da --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Lastmod.md b/docs/content/en/methods/page/Lastmod.md new file mode 100644 index 000000000..c1692233d --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Layout.md b/docs/content/en/methods/page/Layout.md new file mode 100644 index 000000000..3d0cdc437 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Len.md b/docs/content/en/methods/page/Len.md new file mode 100644 index 000000000..d4270bda3 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/LinkTitle.md b/docs/content/en/methods/page/LinkTitle.md new file mode 100644 index 000000000..746e433bb --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Next.md b/docs/content/en/methods/page/Next.md new file mode 100644 index 000000000..3c9e3495a --- /dev/null +++ b/docs/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/docs/content/en/methods/page/NextInSection.md b/docs/content/en/methods/page/NextInSection.md new file mode 100644 index 000000000..b48ddcc62 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/OutputFormats.md b/docs/content/en/methods/page/OutputFormats.md new file mode 100644 index 000000000..03343cf8c --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Page.md b/docs/content/en/methods/page/Page.md new file mode 100644 index 000000000..2c0536bee --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Pages.md b/docs/content/en/methods/page/Pages.md new file mode 100644 index 000000000..2f329eeec --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Paginate.md b/docs/content/en/methods/page/Paginate.md new file mode 100644 index 000000000..6b43b99dd --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Paginator.md b/docs/content/en/methods/page/Paginator.md new file mode 100644 index 000000000..b1540286a --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Param.md b/docs/content/en/methods/page/Param.md new file mode 100644 index 000000000..b2932d981 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Params.md b/docs/content/en/methods/page/Params.md new file mode 100644 index 000000000..ce624c394 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Parent.md b/docs/content/en/methods/page/Parent.md new file mode 100644 index 000000000..dbd2cb9b3 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Permalink.md b/docs/content/en/methods/page/Permalink.md new file mode 100644 index 000000000..be6df5aad --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Plain.md b/docs/content/en/methods/page/Plain.md new file mode 100644 index 000000000..6fdf60b62 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/PlainWords.md b/docs/content/en/methods/page/PlainWords.md new file mode 100644 index 000000000..4bc79d241 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Prev.md b/docs/content/en/methods/page/Prev.md new file mode 100644 index 000000000..cde83b0f2 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/PrevInSection.md b/docs/content/en/methods/page/PrevInSection.md new file mode 100644 index 000000000..30b813350 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/PublishDate.md b/docs/content/en/methods/page/PublishDate.md new file mode 100644 index 000000000..b1c0717a9 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RawContent.md b/docs/content/en/methods/page/RawContent.md new file mode 100644 index 000000000..258a294d0 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/ReadingTime.md b/docs/content/en/methods/page/ReadingTime.md new file mode 100644 index 000000000..531824b9b --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Ref.md b/docs/content/en/methods/page/Ref.md new file mode 100644 index 000000000..e3c5569a4 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RegularPages.md b/docs/content/en/methods/page/RegularPages.md new file mode 100644 index 000000000..b0ca7b1e1 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RegularPagesRecursive.md b/docs/content/en/methods/page/RegularPagesRecursive.md new file mode 100644 index 000000000..3dac8c85e --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RelPermalink.md b/docs/content/en/methods/page/RelPermalink.md new file mode 100644 index 000000000..8a5972ccc --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RelRef.md b/docs/content/en/methods/page/RelRef.md new file mode 100644 index 000000000..4c635e0e2 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Render.md b/docs/content/en/methods/page/Render.md new file mode 100644 index 000000000..bc3f58352 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RenderShortcodes.md b/docs/content/en/methods/page/RenderShortcodes.md new file mode 100644 index 000000000..4636bf8f5 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/RenderString.md b/docs/content/en/methods/page/RenderString.md new file mode 100644 index 000000000..5782cd2b1 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Resources.md b/docs/content/en/methods/page/Resources.md new file mode 100644 index 000000000..a9fa3dab2 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Scratch.md b/docs/content/en/methods/page/Scratch.md new file mode 100644 index 000000000..f9ce7f7fb --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Section.md b/docs/content/en/methods/page/Section.md new file mode 100644 index 000000000..30c8a9837 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Sections.md b/docs/content/en/methods/page/Sections.md new file mode 100644 index 000000000..d64440038 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Site.md b/docs/content/en/methods/page/Site.md new file mode 100644 index 000000000..34748facd --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Sitemap.md b/docs/content/en/methods/page/Sitemap.md new file mode 100644 index 000000000..08ff3f5d0 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Sites.md b/docs/content/en/methods/page/Sites.md new file mode 100644 index 000000000..1fbdfcdcd --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Slug.md b/docs/content/en/methods/page/Slug.md new file mode 100644 index 000000000..9fdb09b57 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Store.md b/docs/content/en/methods/page/Store.md new file mode 100644 index 000000000..04e1d5256 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Summary.md b/docs/content/en/methods/page/Summary.md new file mode 100644 index 000000000..37ce86589 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/TableOfContents.md b/docs/content/en/methods/page/TableOfContents.md new file mode 100644 index 000000000..2ab182e8c --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Title.md b/docs/content/en/methods/page/Title.md new file mode 100644 index 000000000..52e46ff44 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/TranslationKey.md b/docs/content/en/methods/page/TranslationKey.md new file mode 100644 index 000000000..a9e4b97e9 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Translations.md b/docs/content/en/methods/page/Translations.md new file mode 100644 index 000000000..7aaee75ab --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Truncated.md b/docs/content/en/methods/page/Truncated.md new file mode 100644 index 000000000..e6051f0cd --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Type.md b/docs/content/en/methods/page/Type.md new file mode 100644 index 000000000..b7c62372b --- /dev/null +++ b/docs/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/docs/content/en/methods/page/Weight.md b/docs/content/en/methods/page/Weight.md new file mode 100644 index 000000000..75c75db86 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/WordCount.md b/docs/content/en/methods/page/WordCount.md new file mode 100644 index 000000000..bb1fdcf94 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_common/_index.md b/docs/content/en/methods/page/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_common/definition-of-section.md b/docs/content/en/methods/page/_common/definition-of-section.md new file mode 100644 index 000000000..7dc600789 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_common/output-format-definition.md b/docs/content/en/methods/page/_common/output-format-definition.md new file mode 100644 index 000000000..25944464a --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_common/output-format-methods.md b/docs/content/en/methods/page/_common/output-format-methods.md new file mode 100644 index 000000000..5e7111fe5 --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_common/scratch-methods.md b/docs/content/en/methods/page/_common/scratch-methods.md new file mode 100644 index 000000000..c09b4aadc --- /dev/null +++ b/docs/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/docs/content/en/methods/page/_index.md b/docs/content/en/methods/page/_index.md new file mode 100644 index 000000000..278541c5a --- /dev/null +++ b/docs/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. diff --git a/docs/content/en/methods/pages/ByDate.md b/docs/content/en/methods/pages/ByDate.md new file mode 100644 index 000000000..eb4e86535 --- /dev/null +++ b/docs/content/en/methods/pages/ByDate.md @@ -0,0 +1,31 @@ +--- +title: ByDate +description: Returns the given page collection sorted by date in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByExpiryDate + - methods/pages/ByLastMod + - methods/pages/ByPublishDate + returnType: page.Pages + signatures: [PAGES.ByDate] +--- + +When sorting by date, the value is determined by your [site configuration], defaulting to the `date` field in front matter. + +[site configuration]: /getting-started/configuration/#configure-dates + +```go-html-template +{{ range .Pages.ByDate }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByDate.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByExpiryDate.md b/docs/content/en/methods/pages/ByExpiryDate.md new file mode 100644 index 000000000..41753c340 --- /dev/null +++ b/docs/content/en/methods/pages/ByExpiryDate.md @@ -0,0 +1,31 @@ +--- +title: ByExpiryDate +description: Returns the given page collection sorted by expiration date in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByDate + - methods/pages/ByLastMod + - methods/pages/ByPublishDate + returnType: page.Pages + signatures: [PAGES.ByExpiryDate] +--- + +When sorting by expiration date, the value is determined by your [site configuration], defaulting to the `expiryDate` field in front matter. + +[site configuration]: /getting-started/configuration/#configure-dates + +```go-html-template +{{ range .Pages.ByExpiryDate }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByExpiryDate.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByLanguage.md b/docs/content/en/methods/pages/ByLanguage.md new file mode 100644 index 000000000..30d87f954 --- /dev/null +++ b/docs/content/en/methods/pages/ByLanguage.md @@ -0,0 +1,24 @@ +--- +title: ByLanguage +description: Returns the given page collection sorted by language in ascending order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGES.ByLanguage] +--- + +```go-html-template +{{ range .Site.AllPages.ByLanguage }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Site.AllPages.ByLanguage.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByLastmod.md b/docs/content/en/methods/pages/ByLastmod.md new file mode 100644 index 000000000..385093134 --- /dev/null +++ b/docs/content/en/methods/pages/ByLastmod.md @@ -0,0 +1,31 @@ +--- +title: ByLastmod +description: Returns the given page collection sorted by last modification date in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByDate + - methods/pages/ByExpiryDate + - methods/pages/ByPublishDate + returnType: page.Pages + signatures: [PAGES.ByLastmod] +--- + +When sorting by last modification date, the value is determined by your [site configuration], defaulting to the `lastmod` field in front matter. + +[site configuration]: /getting-started/configuration/#configure-dates + +```go-html-template +{{ range .Pages.ByLastmod }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByLastmod.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByLength.md b/docs/content/en/methods/pages/ByLength.md new file mode 100644 index 000000000..602b548c2 --- /dev/null +++ b/docs/content/en/methods/pages/ByLength.md @@ -0,0 +1,24 @@ +--- +title: ByLength +description: Returns the given page collection sorted by content length in ascending order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGES.ByLength] +--- + +```go-html-template +{{ range .Pages.ByLength }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByLength.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByLinkTitle.md b/docs/content/en/methods/pages/ByLinkTitle.md new file mode 100644 index 000000000..073b1e1ba --- /dev/null +++ b/docs/content/en/methods/pages/ByLinkTitle.md @@ -0,0 +1,26 @@ +--- +title: ByLinkTitle +description: Returns the given page collection sorted by link title in ascending order, falling back to title if link title is not defined. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByTitle + - methods/pages/ByParam + returnType: page.Pages + signatures: [PAGES.ByLinkTitle] +--- + +```go-html-template +{{ range .Pages.ByLinkTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByLinkTitle.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByParam.md b/docs/content/en/methods/pages/ByParam.md new file mode 100644 index 000000000..9a919cc88 --- /dev/null +++ b/docs/content/en/methods/pages/ByParam.md @@ -0,0 +1,36 @@ +--- +title: ByParam +description: Returns the given page collection sorted by the given parameter in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByTitle + - methods/pages/ByLinkTitle + returnType: page.Pages + signatures: [PAGES.ByParam PARAM] +--- + +If the given parameter is not present in front matter, Hugo will use the matching parameter in your site configuration if present. + +```go-html-template +{{ range .Pages.ByParam "author" }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range (.Pages.ByParam "author").Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +If the targeted parameter is nested, access the field using dot notation: + +```go-html-template +{{ range .Pages.ByParam "author.last_name" }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByPublishDate.md b/docs/content/en/methods/pages/ByPublishDate.md new file mode 100644 index 000000000..e622636a2 --- /dev/null +++ b/docs/content/en/methods/pages/ByPublishDate.md @@ -0,0 +1,31 @@ +--- +title: ByPublishDate +description: Returns the given page collection sorted by publish date in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByDate + - methods/pages/ByExpiryDate + - methods/pages/ByLastMod + returnType: page.Pages + signatures: [PAGES.ByPublishDate] +--- + +When sorting by publish date, the value is determined by your [site configuration], defaulting to the `publishDate` field in front matter. + +[site configuration]: /getting-started/configuration/#configure-dates + +```go-html-template +{{ range .Pages.ByPublishDate }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByPublishDate.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByTitle.md b/docs/content/en/methods/pages/ByTitle.md new file mode 100644 index 000000000..ee54d5cda --- /dev/null +++ b/docs/content/en/methods/pages/ByTitle.md @@ -0,0 +1,26 @@ +--- +title: ByTitle +description: Returns the given page collection sorted by title in ascending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/ByLinkTitle + - methods/pages/ByParam + returnType: page.Pages + signatures: [PAGES.ByTitle] +--- + +```go-html-template +{{ range .Pages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByTitle.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/ByWeight.md b/docs/content/en/methods/pages/ByWeight.md new file mode 100644 index 000000000..4eafee11f --- /dev/null +++ b/docs/content/en/methods/pages/ByWeight.md @@ -0,0 +1,28 @@ +--- +title: ByWeight +description: Returns the given page collection sorted by weight in ascending order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGES.ByWeight] +--- + +Assign a [weight] to a page using the `weight` field in front matter. The weight must be a non-zero integer. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted pages are placed at the end of the collection. + +[weight]: /getting-started/glossary/#weight + +```go-html-template +{{ range .Pages.ByWeight }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByWeight.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/GroupBy.md b/docs/content/en/methods/pages/GroupBy.md new file mode 100644 index 000000000..b46a39bdf --- /dev/null +++ b/docs/content/en/methods/pages/GroupBy.md @@ -0,0 +1,36 @@ +--- +title: GroupBy +description: Returns the given page collection grouped by the given field in ascending order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.PagesGroup + signatures: ['PAGES.GroupBy FIELD [SORT]'] +--- + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +```go-html-template +{{ range .Pages.GroupBy "Section" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in descending order: + +```go-html-template +{{ range .Pages.GroupBy "Section" "desc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/GroupByDate.md b/docs/content/en/methods/pages/GroupByDate.md new file mode 100644 index 000000000..8b5fcd6f1 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByDate.md @@ -0,0 +1,68 @@ +--- +title: GroupByDate +description: Returns the given page collection grouped by date in descending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/GroupByExpiryDate + - methods/pages/GroupByLastMod + - methods/pages/GroupByParamDate + - methods/pages/GroupByPublishDate + returnType: page.PagesGroup + signatures: ['PAGES.GroupByDate LAYOUT [SORT]'] +--- + +When grouping by date, the value is determined by your [site configuration], defaulting to the `date` field in front matter. + +The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[localized]: /getting-started/glossary/#localization +[site configuration]: /getting-started/configuration/#configure-dates + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +To group content by year and month: + +```go-html-template +{{ range .Pages.GroupByDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByDate "January 2006" "asc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +The pages within each group will also be sorted by date, either ascending or descending depending on the grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title: + +```go-html-template +{{ range .Pages.GroupByDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} diff --git a/docs/content/en/methods/pages/GroupByExpiryDate.md b/docs/content/en/methods/pages/GroupByExpiryDate.md new file mode 100644 index 000000000..a9b248297 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByExpiryDate.md @@ -0,0 +1,68 @@ +--- +title: GroupByExpiryDate +description: Returns the given page collection grouped by expiration date in descending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/GroupByDate + - methods/pages/GroupByLastMod + - methods/pages/GroupByParamDate + - methods/pages/GroupByPublishDate + returnType: page.PagesGroup + signatures: ['PAGES.GroupByExpiryDate LAYOUT [SORT]'] +--- + +When grouping by expiration date, the value is determined by your [site configuration], defaulting to the `expiryDate` field in front matter. + +The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[localized]: /getting-started/glossary/#localization +[site configuration]: /getting-started/configuration/#configure-dates + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +To group content by year and month: + +```go-html-template +{{ range .Pages.GroupByExpiryDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByExpiryDate "January 2006" "asc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +The pages within each group will also be sorted by expiration date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title: + +```go-html-template +{{ range .Pages.GroupByExpiryDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} diff --git a/docs/content/en/methods/pages/GroupByLastmod.md b/docs/content/en/methods/pages/GroupByLastmod.md new file mode 100644 index 000000000..877692521 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByLastmod.md @@ -0,0 +1,68 @@ +--- +title: GroupByLastmod +description: Returns the given page collection grouped by last modification date in descending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/GroupByDate + - methods/pages/GroupByExpiryDate + - methods/pages/GroupByParamDate + - methods/pages/GroupByPublishDate + returnType: page.PagesGroup + signatures: ['PAGES.GroupByLastmod LAYOUT [SORT]'] +--- + +When grouping by last modification date, the value is determined by your [site configuration], defaulting to the `lastmod` field in front matter. + +The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[localized]: /getting-started/glossary/#localization +[site configuration]: /getting-started/configuration/#configure-dates + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +To group content by year and month: + +```go-html-template +{{ range .Pages.GroupByLastmod "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByLastmod "January 2006" "asc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +The pages within each group will also be sorted by last modification date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title: + +```go-html-template +{{ range .Pages.GroupByLastmod "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} diff --git a/docs/content/en/methods/pages/GroupByParam.md b/docs/content/en/methods/pages/GroupByParam.md new file mode 100644 index 000000000..9c63ab902 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByParam.md @@ -0,0 +1,36 @@ +--- +title: GroupByParam +description: Returns the given page collection grouped by the given parameter in ascending order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.PagesGroup + signatures: ['PAGES.GroupByParam PARAM [SORT]'] +--- + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +```go-html-template +{{ range .Pages.GroupByParam "color" }} + <p>{{ .Key | title }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in descending order: + +```go-html-template +{{ range .Pages.GroupByParam "color" "desc" }} + <p>{{ .Key | title }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/GroupByParamDate.md b/docs/content/en/methods/pages/GroupByParamDate.md new file mode 100644 index 000000000..c7fedbb1a --- /dev/null +++ b/docs/content/en/methods/pages/GroupByParamDate.md @@ -0,0 +1,65 @@ +--- +title: GroupByParamDate +description: Returns the given page collection grouped by the given date parameter in descending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/GroupByDate + - methods/pages/GroupByExpiryDate + - methods/pages/GroupByLastMod + - methods/pages/GroupByPublishDate + returnType: page.PagesGroup + signatures: ['PAGES.GroupByParamDate PARAM LAYOUT [SORT]'] +--- + +The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[localized]: /getting-started/glossary/#localization + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +To group content by year and month: + +```go-html-template +{{ range .Pages.GroupByParamDate "eventDate" "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByParamDate "eventDate" "January 2006" "asc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +The pages within each group will also be sorted by the parameter date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title: + +```go-html-template +{{ range .Pages.GroupByParamDate "eventDate" "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} diff --git a/docs/content/en/methods/pages/GroupByPublishDate.md b/docs/content/en/methods/pages/GroupByPublishDate.md new file mode 100644 index 000000000..f6603e858 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByPublishDate.md @@ -0,0 +1,68 @@ +--- +title: GroupByPublishDate +description: Returns the given page collection grouped by publish date in descending order. +categories: [] +keywords: [] +action: + related: + - methods/pages/GroupByDate + - methods/pages/GroupByExpiryDate + - methods/pages/GroupByLastMod + - methods/pages/GroupByParamDate + returnType: page.PagesGroup + signatures: ['PAGES.GroupByPublishDate LAYOUT [SORT]'] +--- + +When grouping by publish date, the value is determined by your [site configuration], defaulting to the `publishDate` field in front matter. + +The [layout string] has the same format as the layout string for the [`time.Format`] function. The resulting group key is [localized] for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[localized]: /getting-started/glossary/#localization +[site configuration]: /getting-started/configuration/#configure-dates + +{{% include "methods/pages/_common/group-sort-order.md" %}} + +To group content by year and month: + +```go-html-template +{{ range .Pages.GroupByPublishDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByPublishDate "January 2006" "asc" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +The pages within each group will also be sorted by publish date, either ascending or descending depending on your grouping option. To sort the pages within each group, use one of the sorting methods. For example, to sort the pages within each group by title: + +```go-html-template +{{ range .Pages.GroupByPublishDate "January 2006" }} + <p>{{ .Key }}</p> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} diff --git a/docs/content/en/methods/pages/Len.md b/docs/content/en/methods/pages/Len.md new file mode 100644 index 000000000..0a5989a1a --- /dev/null +++ b/docs/content/en/methods/pages/Len.md @@ -0,0 +1,14 @@ +--- +title: Len +description: Returns the number of pages in the given page collection. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [PAGES.Len] +--- + +```go-html-template +{{ .Pages.Len }} → 42 +``` diff --git a/docs/content/en/methods/pages/Limit.md b/docs/content/en/methods/pages/Limit.md new file mode 100644 index 000000000..bf889fd7e --- /dev/null +++ b/docs/content/en/methods/pages/Limit.md @@ -0,0 +1,16 @@ +--- +title: Limit +description: Returns the first N pages from the given page collection. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGES.Limit NUMBER] +--- + +```go-html-template +{{ range .Pages.Limit 3 }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/Next.md b/docs/content/en/methods/pages/Next.md new file mode 100644 index 000000000..638822e5d --- /dev/null +++ b/docs/content/en/methods/pages/Next.md @@ -0,0 +1,55 @@ +--- +title: Next +description: Returns the next page in a local page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/pages/Prev + - methods/page/Next + - methods/page/NextInSection + - methods/page/Prev + - methods/page/PrevInSection + returnType: hugolib.pageState + signatures: [PAGES.Next PAGE] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect. + +With this content structure and the page collection sorted by weight in ascending order: + +```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 +{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }} + +{{ with $pages.Next . }} + <a href="{{ .RelPermalink }}">Previous</a> +{{ end }} + +{{ with $pages.Prev . }} + <a href="{{ .RelPermalink }}">Next</a> +{{ end }} +``` + +## Compare to Page methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --git a/docs/content/en/methods/pages/Prev.md b/docs/content/en/methods/pages/Prev.md new file mode 100644 index 000000000..3a4dcfd1d --- /dev/null +++ b/docs/content/en/methods/pages/Prev.md @@ -0,0 +1,55 @@ +--- +title: Prev +description: Returns the previous page in a local page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/pages/Next + - methods/page/Next + - methods/page/NextInSection + - methods/page/Prev + - methods/page/PrevInSection + returnType: hugolib.pageStates + signatures: [PAGES.Prev PAGE] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect. + +With this content structure and the page collection sorted by weight in ascending order: + +```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 +{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }} + +{{ with $pages.Next . }} + <a href="{{ .RelPermalink }}">Previous</a> +{{ end }} + +{{ with $pages.Prev . }} + <a href="{{ .RelPermalink }}">Next</a> +{{ end }} +``` + +## Compare to Page methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --git a/docs/content/en/methods/pages/Related.md b/docs/content/en/methods/pages/Related.md new file mode 100644 index 000000000..1cee88745 --- /dev/null +++ b/docs/content/en/methods/pages/Related.md @@ -0,0 +1,79 @@ +--- +title: Related +description: Returns a collection of pages related to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/HeadingsFiltered + - functions/collections/KeyVals + returnType: page.Pages + signatures: + - PAGES.Related PAGE + - PAGES.Related OPTIONS +--- + +Based on front matter, Hugo uses several factors to identify content related to the given page. Use the default [related content configuration], or tune the results to the desired indices and parameters. See [details]. + +The argument passed to the `Related` method may be a `Page` or an options map. For example, to pass the current page: + +{{< code file=layouts/_default/single.html >}} +{{ with .Site.RegularPages.Related . | first 5 }} + <p>Related pages:</p> + <ul> + {{ range . }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +{{< /code >}} + +To pass an options map: + +{{< code file=layouts/_default/single.html >}} +{{ $opts := dict + "document" . + "indices" (slice "tags" "keywords") +}} +{{ with .Site.RegularPages.Related $opts | first 5 }} + <p>Related pages:</p> + <ul> + {{ range . }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +{{< /code >}} + + +## Options + +indices +: (`slice`) The indices to search within. + +document +: (`page`) The page for which to find related content. Required when specifying an options map. + +namedSlices +: (`slice`) The keywords to search for, expressed as a slice of `KeyValues` using the [`keyVals`] function. + +[`keyVals`]: /functions/collections/keyvals/ + +fragments +: (`slice`) A list of special keywords that is used for indices configured as type "fragments". This will match the [fragment] identifiers of the documents. + +A contrived example using all of the above: + +```go-html-template +{{ $page := . }} +{{ $opts := dict + "indices" (slice "tags" "keywords") + "document" $page + "namedSlices" (slice (keyVals "tags" "hugo" "rocks") (keyVals "date" $page.Date)) + "fragments" (slice "heading-1" "heading-2") +}} +``` + +[details]: /content-management/related/ +[fragment]: /getting-started/glossary/#fragment +[related content configuration]: /content-management/related/ diff --git a/docs/content/en/methods/pages/Reverse.md b/docs/content/en/methods/pages/Reverse.md new file mode 100644 index 000000000..e03e0ea47 --- /dev/null +++ b/docs/content/en/methods/pages/Reverse.md @@ -0,0 +1,16 @@ +--- +title: Reverse +description: Returns the given page collection in reverse order. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Pages + signatures: [PAGES.Reverse] +--- + +```go-html-template +{{ range .Pages.ByDate.Reverse }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/pages/_common/_index.md b/docs/content/en/methods/pages/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/content/en/methods/pages/_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/docs/content/en/methods/pages/_common/group-sort-order.md b/docs/content/en/methods/pages/_common/group-sort-order.md new file mode 100644 index 000000000..bb5be82f6 --- /dev/null +++ b/docs/content/en/methods/pages/_common/group-sort-order.md @@ -0,0 +1,5 @@ +--- +# Do not remove front matter. +--- + +For the optional sort order, specify either `asc` for ascending order, or `desc` for descending order. diff --git a/docs/content/en/methods/pages/_index.md b/docs/content/en/methods/pages/_index.md new file mode 100644 index 000000000..d8a64f5d5 --- /dev/null +++ b/docs/content/en/methods/pages/_index.md @@ -0,0 +1,13 @@ +--- +title: Pages methods +linkTitle: Pages +description: Use these methods with a collection of Page objects. +categories: [] +keywords: [] +menu: + docs: + parent: methods +aliases: [/variables/pages] +--- + +Use these methods with a collection of Page objects. diff --git a/docs/content/en/methods/resource/Colors.md b/docs/content/en/methods/resource/Colors.md new file mode 100644 index 000000000..1452d558f --- /dev/null +++ b/docs/content/en/methods/resource/Colors.md @@ -0,0 +1,22 @@ +--- +title: Colors +description: Applicable to images, returns a slice of the most dominant colors using a simple histogram method. +categories: [] +keywords: [] +action: + related: [] + returnType: '[]string' + signatures: [RESOURCE.Colors] +--- + +{{< new-in 0.104.0 >}} + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Colors }} → [#bebebd #514947 #768a9a #647789 #90725e #a48974] +{{ end }} +``` + +This method is fast, but if you also scale down your images, it would be good for performance to extract the colors from the scaled image. + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Content.md b/docs/content/en/methods/resource/Content.md new file mode 100644 index 000000000..a5945ff65 --- /dev/null +++ b/docs/content/en/methods/resource/Content.md @@ -0,0 +1,61 @@ +--- +title: Content +description: Returns the content of the given resource. +categories: [] +keywords: [] +action: + related: [] + returnType: any + signatures: [RESOURCE.Content] +toc: +--- + +The `Content` method on a `Resource` object returns `template.HTML` when the resource type is `page`, otherwise it returns a `string`. + +[resource type]: /methods/resource/resourcetype + +{{< code file=assets/quotations/kipling.txt >}} +He travels the fastest who travels alone. +{{< /code >}} + +To get the content: + +```go-html-template +{{ with resources.Get "quotations/kipling.txt" }} + {{ .Content }} → He travels the fastest who travels alone. +{{ end }} +``` + +To get the size in bytes: + +```go-html-template +{{ with resources.Get "quotations/kipling.txt" }} + {{ .Content | len }} → 42 +{{ end }} +``` + +To create an inline image: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + <img src="data:{{ .MediaType.Type }};base64,{{ .Content | base64Encode }}"> +{{ end }} +``` + +To create inline CSS: + +```go-html-template +{{ with resources.Get "css/style.css" }} + <style>{{ .Content | safeCSS }}</style> +{{ end }} +``` + +To create inline JavaScript: + +```go-html-template +{{ with resources.Get "js/script.js" }} + <script>{{ .Content | safeJS }}</script> +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Crop.md b/docs/content/en/methods/resource/Crop.md new file mode 100644 index 000000000..711fc07b0 --- /dev/null +++ b/docs/content/en/methods/resource/Crop.md @@ -0,0 +1,48 @@ +--- +title: Crop +description: Applicable to images, returns an image resource cropped to the given dimensions without resizing. +categories: [] +keywords: [] +action: + related: + - methods/resource/Fit + - methods/resource/Fill + - methods/resource/Resize + - methods/resource/Process + - functions/images/Process + returnType: images.ImageResource + signatures: [RESOURCE.Crop SPEC] +toc: true +--- + +Crop an image to match the given dimensions without resizing. You must provide both width and height. + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Crop "200x200" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +{{% include "/methods/resource/_common/processing-spec.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Crop "200x200 topright webp q85 lanczos" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="crop 200x200 topright webp q85 lanczos" + example=true +>}} diff --git a/docs/content/en/methods/resource/Data.md b/docs/content/en/methods/resource/Data.md new file mode 100644 index 000000000..0fbaf6199 --- /dev/null +++ b/docs/content/en/methods/resource/Data.md @@ -0,0 +1,53 @@ +--- +title: Data +description: Applicable to resources returned by the resources.GetRemote function, returns information from the HTTP response. +categories: [] +keywords: [] +action: + related: + - functions/resources/GetRemote + - methods/resource/Err + returnType: map + signatures: [RESOURCE.Data] +--- + +The `Data` method on a resource returned by the [`resources.GetRemote`] function returns information from the HTTP response. + +[`resources.GetRemote`]: functions/resources/getremote + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ with resources.GetRemote $url }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} + {{ with .Data }} + {{ .ContentLength }} → 42764 + {{ .ContentType }} → image/jpeg + {{ .Status }} → 200 OK + {{ .StatusCode }} → 200 + {{ .TransferEncoding }} → [] + {{ end }} + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $url }} +{{ end }} +``` + +ContentLength +: (`int`) The content length in bytes. + +ContentType +: (`string`) The content type. + +Status +: (`string`) The HTTP status text. + +StatusCode +: (`int`) The HTTP status code. + +TransferEncoding +: (`string`) The transfer encoding. + + +[`resources.GetRemote`]: functions/resources/getremote diff --git a/docs/content/en/methods/resource/Err.md b/docs/content/en/methods/resource/Err.md new file mode 100644 index 000000000..f4b410aa7 --- /dev/null +++ b/docs/content/en/methods/resource/Err.md @@ -0,0 +1,56 @@ +--- +title: Err +description: Applicable to resources returned by the resources.GetRemote function, returns an error message if the HTTP request fails, else nil. +categories: [] +keywords: [] +action: + related: + - functions/resources/GetRemote + - methods/resource/Data + returnType: resource.resourceError + signatures: [RESOURCE.Err] +--- + +The `Err` method on a resource returned by the [`resources.GetRemote`] function returns an error message if the HTTP request fails, else nil. If you do not handle the error yourself, Hugo will fail the build. + +[`resources.GetRemote`]: functions/resources/getremote + +In this example we send an HTTP request to a nonexistent domain: + +```go-html-template +{{ $url := "https://broken-example.org/images/a.jpg" }} +{{ with resources.GetRemote $url }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $url }} +{{ end }} +``` + +The code above captures the error from the HTTP request, then fails the build: + +```text +ERROR error calling resources.GetRemote: Get "https://broken-example.org/images/a.jpg": dial tcp: lookup broken-example.org on 127.0.0.53:53: no such host +``` + +To log an error as a warning instead of an error: + +```go-html-template +{{ $url := "https://broken-example.org/images/a.jpg" }} +{{ with resources.GetRemote $url }} + {{ with .Err }} + {{ warnf "%s" . }} + {{ else }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $url }} +{{ end }} +``` + +{{% note %}} +An HTTP response with a 404 status code is not an HTTP request error. To handle 404 status codes, code defensively using the nested `with-else-end` construct as shown above. +{{% /note %}} diff --git a/docs/content/en/methods/resource/Exif.md b/docs/content/en/methods/resource/Exif.md new file mode 100644 index 000000000..75071153a --- /dev/null +++ b/docs/content/en/methods/resource/Exif.md @@ -0,0 +1,78 @@ +--- +title: Exif +description: Applicable to images, returns an EXIF object containing image metadata. +categories: [] +keywords: [] +action: + related: [] + returnType: exif.ExifInfo + signatures: [RESOURCE.Exif] +toc: true +--- + +Applicable to images, the `Exif` method on an image `Resource` object returns an [EXIF] object containing image metadata. + +## Methods + +Date +: (`time.Time`) Returns the image creation date/time. Format with the [`time.Format`]function. + +Lat +: (`float64`) Returns the GPS latitude in degrees. + +Long +: (`float64`) Returns the GPS longitude in degrees. + +Tags +: (`exif.Tags`) Returns a collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration]. + +## Examples + +To list the creation date, location, and EXIF tags: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} + <p>Date: {{ .Date }}</p> + <p>Lat/Long: {{ .Lat }}/{{ .Long }}</p> + {{ with .Tags }} + <p>Tags</p> + <table> + <thead> + <tr><th>Tag</th><th>Value</th></tr> + </thead> + <tbody> + {{ range $k, $v := . }} + <tr><td>{{ $k }}</td><td>{{ $v }}</td></tr> + {{ end }} + </tbody> + </table> + {{ end }} + {{ end }} +{{ end }} +``` + +To list specific values: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} + <ul> + {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }} + {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.FormatNumber 2 . }}</li>{{ end }} + {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.FormatNumber 2 . }}</li>{{ end }} + {{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }} + {{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }} + {{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }} + {{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }} + {{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }} + </ul> + {{ end }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +[exif]: https://en.wikipedia.org/wiki/Exif +[site configuration]: /content-management/image-processing/#exif-data +[`time.Format`]: /functions/time/format diff --git a/docs/content/en/methods/resource/Fill.md b/docs/content/en/methods/resource/Fill.md new file mode 100644 index 000000000..8bbaf93ee --- /dev/null +++ b/docs/content/en/methods/resource/Fill.md @@ -0,0 +1,48 @@ +--- +title: Fill +description: Applicable to images, returns an image resource cropped and resized to the given dimensions. +categories: [] +keywords: [] +action: + related: + - methods/resource/Crop + - methods/resource/Fit + - methods/resource/Resize + - methods/resource/Process + - functions/images/Process + returnType: images.ImageResource + signatures: [RESOURCE.Fill SPEC] +toc: true +--- + +Crop and resize an image to match the given dimensions. You must provide both width and height. + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Fill "200x200" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +{{% include "/methods/resource/_common/processing-spec.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Fill "200x200 top webp q85 lanczos" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="fill 200x200 top webp q85 lanczos" + example=true +>}} diff --git a/docs/content/en/methods/resource/Filter.md b/docs/content/en/methods/resource/Filter.md new file mode 100644 index 000000000..329168da7 --- /dev/null +++ b/docs/content/en/methods/resource/Filter.md @@ -0,0 +1,68 @@ +--- +title: Filter +description: Applicable to images, applies one or more image filters to the given image resource. +categories: [] +keywords: [] +action: + related: + - functions/images/Filter + returnType: resources.resourceAdapter + signatures: [RESOURCE.Filter FILTER...] +toc: true +--- + +Apply one or more [image filters](#image-filters) to the given image. + +To apply a single filter: + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Filter images.Grayscale }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +To apply two or more filters, executing from left to right: + +```go-html-template +{{ $filters := slice + images.Grayscale + (images.GaussianBlur 8) +}} +{{ with resources.Get "images/original.jpg" }} + {{ with .Filter $filters }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +You can also apply image filters using the [`images.Filter`] function. + +[`images.Filter`]: /functions/images/filter + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Filter images.Grayscale }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Grayscale" + filterArgs="" + example=true +>}} + +## Image filters + +Use any of these filters with the `Filter` method. + +{{< list-pages-in-section path=/functions/images filter=functions_images_no_filters filterType=exclude >}} diff --git a/docs/content/en/methods/resource/Fit.md b/docs/content/en/methods/resource/Fit.md new file mode 100644 index 000000000..13354fe5a --- /dev/null +++ b/docs/content/en/methods/resource/Fit.md @@ -0,0 +1,48 @@ +--- +title: Fit +description: Applicable to images, returns an image resource downscaled to fit the given dimensions while maintaining aspect ratio. +categories: [] +keywords: [] +action: + related: + - methods/resource/Crop + - methods/resource/Fill + - methods/resource/Resize + - methods/resource/Process + - functions/images/Process + returnType: images.ImageResource + signatures: [RESOURCE.Fit SPEC] +toc: true +--- + +Downscale an image to fit the given dimensions while maintaining aspect ratio. You must provide both width and height. + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Fit "200x200" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +{{% include "/methods/resource/_common/processing-spec.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Fit "300x175 webp q85 lanczos" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="fit 300x175 webp q85 lanczos" + example=true +>}} diff --git a/docs/content/en/methods/resource/Height.md b/docs/content/en/methods/resource/Height.md new file mode 100644 index 000000000..dcaf6c514 --- /dev/null +++ b/docs/content/en/methods/resource/Height.md @@ -0,0 +1,27 @@ +--- +title: Height +description: Applicable to images, returns the height of the given resource. +categories: [] +keywords: [] +action: + related: + - methods/resource/Width + returnType: int + signatures: [RESOURCE.Height] +--- + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Height }} → 400 +{{ end }} +``` + +Use the `Width` and `Height` methods together when rendering an `img` element: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}"> +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Key.md b/docs/content/en/methods/resource/Key.md new file mode 100644 index 000000000..15927aea9 --- /dev/null +++ b/docs/content/en/methods/resource/Key.md @@ -0,0 +1,45 @@ +--- +title: Key +description: Returns the unique key for the given resource, equivalent to its publishing path. +categories: [] +keywords: [] +action: + related: + - methods/resource/Permalink + - methods/resource/RelPermalink + - methods/resource/Publish + returnType: string + signatures: [RESOURCE.Key] +--- + +By way of example, consider this site configuration: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +And this template: + +```go-html-template + {{ with resources.Get "images/a.jpg" }} + {{ with resources.Copy "foo/bar/b.jpg" . }} + {{ .Key }} → foo/bar/b.jpg + + {{ .Name }} → images/a.jpg + {{ .Title }} → images/a.jpg + + {{ .RelPermalink }} → /docs/foo/bar/b.jpg + {{ end }} + {{ end }} +``` + +We used the [`resources.Copy`] function to change the publishing path. The `Key` method returns the updated path, but note that it is different than the value returned by [`RelPermalink`]. The `RelPermalink` value includes the subdirectory segment of the `baseURL` in the site configuration. + +The `Key` method is useful if you need to get the resource's publishing path without publishing the resource. Unlike the `Permalink`, `RelPermalink`, or `Publish` methods, calling `Key` will not publish the resource. + + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +[`Permalink`]: /methods/resource/permalink +[`RelPermalink`]: /methods/resource/relpermalink +[`resources.Copy`]: /functions/resources/copy diff --git a/docs/content/en/methods/resource/MediaType.md b/docs/content/en/methods/resource/MediaType.md new file mode 100644 index 000000000..6dea8706c --- /dev/null +++ b/docs/content/en/methods/resource/MediaType.md @@ -0,0 +1,52 @@ +--- +title: MediaType +description: Returns a media type object for the given resource. +categories: [] +keywords: [] +action: + related: [] + returnType: media.Type + signatures: [RESOURCE.MediaType] +--- + +The `MediaType` method on a `Resource` object returns an object with additional methods. + +## Methods + +Type +: (`string`) The resource's media type. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .MediaType.Type }} → image/jpeg +{{ end }} +``` + +MainType +: (`string`) The main type of the resource’s media type. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .MediaType.MainType }} → image +{{ end }} +``` + +SubType +: (`string`) The subtype of the resource’s media type. This may or may not correspond to the file suffix. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .MediaType.SubType }} → jpeg +{{ end }} +``` + +Suffixes +: (`slice`) A slice of possible file suffixes for the resource’s media type. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .MediaType.Suffixes }} → [jpg jpeg jpe jif jfif] +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Name.md b/docs/content/en/methods/resource/Name.md new file mode 100644 index 000000000..01b75e5b2 --- /dev/null +++ b/docs/content/en/methods/resource/Name.md @@ -0,0 +1,82 @@ +--- +title: Name +description: Returns the name of the given resource as optionally defined in front matter, falling back to a relative path or hashed file name depending on resource type. +categories: [] +keywords: [] +action: + related: + - methods/resource/Title + returnType: string + signatures: [RESOURCE.Name] +toc: true +--- + +The value returned by the `Name` method on a `Resource` object depends on the resource type. + +## Global resource + +With a [global resource], the `Name` method returns the path to the resource, relative to the assets directory. + +```text +assets/ +└── images/ + └── a.jpg +``` + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Name }} → images/a.jpg +{{ end }} +``` + +## Page resource + +With a [page resource], the `Name` method returns the path to the resource, relative to the page bundle. + +```text +content/ +├── posts/ +│ ├── post-1/ +│ │ ├── images/ +│ │ │ └── a.jpg +│ │ └── index.md +│ └── _index.md +└── _index.md +``` + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + {{ .Name }} → images/a.jpg +{{ end }} +``` + +If you create an element in the `resources` array in front matter, the `Name` method returns the value of the `name` parameter: + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'Post 1' +[[resources]] +src = 'images/a.jpg' +name = 'cat' +title = 'Felix the cat' +[resources.params] +temperament = 'malicious' +{{< /code-toggle >}} + +```go-html-template +{{ with .Resources.Get "cat" }} + {{ .Name }} → cat +{{ end }} +``` +## Remote resource + +With a [remote resource], the `Name` method returns a hashed file name. + +```go-html-template +{{ with resources.GetRemote "https://example.org/images/a.jpg" }} + {{ .Name }} → a_18432433023265451104.jpg +{{ end }} +``` + +[global resource]: /getting-started/glossary/#global-resource +[page resource]: /getting-started/glossary/#page-resource +[remote resource]: /getting-started/glossary/#remote-resource diff --git a/docs/content/en/methods/resource/Params.md b/docs/content/en/methods/resource/Params.md new file mode 100644 index 000000000..275182c46 --- /dev/null +++ b/docs/content/en/methods/resource/Params.md @@ -0,0 +1,65 @@ +--- +title: Params +description: Returns a map of resource parameters as defined in front matter. +categories: [] +keywords: [] +action: + related: [] + returnType: map + signatures: [RESOURCE.Params] +--- + +Use the `Params` method with [page resources]. It is not applicable to either [global] or [remote] resources. + +[global]: /getting-started/glossary/#global-resource +[page resources]: /getting-started/glossary/#page-resource +[remote]: /getting-started/glossary/#remote-resource + +With this content structure: + +```text +content/ +├── posts/ +│ ├── cats/ +│ │ ├── images/ +│ │ │ └── a.jpg +│ │ └── index.md +│ └── _index.md +└── _index.md +``` + +And this front matter: + +{{< code-toggle file=content/posts/cats.md fm=true >}} +title = 'Cats' +[[resources]] + src = 'images/a.jpg' + title = 'Felix the cat' + [resources.params] + alt = 'Photograph of black cat' + temperament = 'vicious' +{{< /code-toggle >}} + +And this template: + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + <figure> + <img alt="{{ .Params.alt }}" src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}"> + <figcaption>{{ .Title }} is {{ .Params.temperament }}</figcaption> + </figure> +{{ end }} +``` + +Hugo renders: + +```html +<figure> + <img alt="Photograph of black cat" src="/posts/post-1/images/a.jpg" width="600" height="400"> + <figcaption>Felix the cat is vicious</figcaption> +</figure> +``` + +See the [page resources] section for more information. + +[page resources]: /content-management/page-resources diff --git a/docs/content/en/methods/resource/Permalink.md b/docs/content/en/methods/resource/Permalink.md new file mode 100644 index 000000000..ab0ad41b0 --- /dev/null +++ b/docs/content/en/methods/resource/Permalink.md @@ -0,0 +1,25 @@ +--- +title: Permalink +description: Publishes the given resource and returns its permalink. +categories: [] +keywords: [] +action: + related: + - methods/resource/RelPermalink + - methods/resource/Publish + - methods/resource/Key + returnType: string + signatures: [RESOURCE.Permalink] +--- + +The `Permalink` method on a `Resource` object writes the resource to the publish directory, typically `public`, and returns its [permalink]. + +[permalink]: /getting-started/glossary/#permalink + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Permalink }} → https://example.org/images/a.jpg +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Process.md b/docs/content/en/methods/resource/Process.md new file mode 100644 index 000000000..3c88492df --- /dev/null +++ b/docs/content/en/methods/resource/Process.md @@ -0,0 +1,66 @@ +--- +title: Process +description: Applicable to images, returns an image resource processed with the given specification. +categories: [] +keywords: [] +action: + related: + - methods/resource/Crop + - methods/resource/Fit + - methods/resource/Fill + - methods/resource/Resize + - functions/images/Process + returnType: images.ImageResource + signatures: [RESOURCE.Process SPEC] +toc: true +--- + +Process an image with the given specification. The specification can contain an optional action, one of `crop`, `fill`, `fit`, or `resize`. This means that you can use this method instead of [`Crop`], [`Fill`], [`Fit`], or [`Resize`]. + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Process "crop 200x200" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +You can also use this method to apply simple transformations such as rotation and conversion: + +```go-html-template +{{/* Rotate 90 degrees counter-clockwise. */}} +{{ $image := $image.Process "r90" }} + +{{/* Convert to WebP. */}} +{{ $image := $image.Process "webp" }} +``` + +The `Process` method is also available as a filter, which is more effective if you need to apply multiple filters to an image. See [`images.Process`]. + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +{{% include "/methods/resource/_common/processing-spec.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Process "crop 200x200 topright webp q85 lanczos" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="crop 200x200 topright webp q85 lanczos" + example=true +>}} + +[`Crop`]: /methods/resource/crop +[`Fill`]: /methods/resource/fill +[`Fit`]: /methods/resource/fit +[`Resize`]: /methods/resource/resize +[`images.Process`]: /functions/images/process diff --git a/docs/content/en/methods/resource/Publish.md b/docs/content/en/methods/resource/Publish.md new file mode 100644 index 000000000..b090bfe5a --- /dev/null +++ b/docs/content/en/methods/resource/Publish.md @@ -0,0 +1,35 @@ +--- +title: Publish +description: Publishes the given resource. +categories: [] +keywords: [] +action: + related: + - methods/resource/Permalink + - methods/resource/RelPermalink + - methods/resource/Key + returnType: nil + signatures: [RESOURCE.Publish] +--- + +The `Publish` method on a `Resource` object writes the resource to the publish directory, typically `public`. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Publish }} +{{ end }} +``` + +The `Permalink` and `RelPermalink` methods also publish a resource. `Publish` is a convenience method for publishing without a return value. For example, this: + +```go-html-template +{{ $resource.Publish }} +``` + +Instead of this: + +```go-html-template +{{ $noop := $resource.Permalink }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/RelPermalink.md b/docs/content/en/methods/resource/RelPermalink.md new file mode 100644 index 000000000..2b96c35d7 --- /dev/null +++ b/docs/content/en/methods/resource/RelPermalink.md @@ -0,0 +1,25 @@ +--- +title: RelPermalink +description: Publishes the given resource and returns its relative permalink. +categories: [] +keywords: [] +action: + related: + - methods/resource/Permalink + - methods/resource/Publish + - methods/resource/Key + returnType: string + signatures: [RESOURCE.RelPermalink] +--- + +The `Permalink` method on a `Resource` object writes the resource to the publish directory, typically `public`, and returns its [relative permalink]. + +[relative permalink]: /getting-started/glossary/#relative-permalink + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .RelPermalink }} → /images/a.jpg +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Resize.md b/docs/content/en/methods/resource/Resize.md new file mode 100644 index 000000000..4ba054bb5 --- /dev/null +++ b/docs/content/en/methods/resource/Resize.md @@ -0,0 +1,49 @@ +--- +title: Resize +description: Applicable to images, returns an image resource resized to the given width and/or height. +categories: [] +keywords: [] +action: + related: + - methods/resource/Crop + - methods/resource/Fit + - methods/resource/Fill + - methods/resource/Process + - functions/images/Process + returnType: images.ImageResource + signatures: [RESOURCE.Resize SPEC] +--- + +Resize an image to the given width and/or height. + +If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio. + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Resize "300x" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +{{% include "/methods/resource/_common/processing-spec.md" %}} + +## Example + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Resize "300x webp q85 lanczos" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="resize 300x webp q85 lanczos" + example=true +>}} diff --git a/docs/content/en/methods/resource/ResourceType.md b/docs/content/en/methods/resource/ResourceType.md new file mode 100644 index 000000000..db52e7b10 --- /dev/null +++ b/docs/content/en/methods/resource/ResourceType.md @@ -0,0 +1,43 @@ +--- +title: ResourceType +description: Returns the main type of the given resource's media type. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [RESOURCE.ResourceType] +--- + +Common resource types include `audio`, `image`, `text`, and `video`. + +```go-html-template +{{ with resources.Get "image/a.jpg" }} + {{ .ResourceType }} → image + {{ .MediaType.MainType }} → image +{{ end }} +``` + +When working with content files, the resource type is `page`. + +```text +content/ +├── lessons/ +│ ├── lesson-1/ +│ │ ├── _objectives.md <-- resource type = page +│ │ ├── _topics.md <-- resource type = page +│ │ ├── _example.jpg <-- resource type = image +│ │ └── index.md +│ └── _index.md +└── _index.md +``` + +With the structure above, we can range through page resources of type `page` to build content: + +{{< code file=layouts/lessons/single.html >}} +{{ range .Resources.ByType "page" }} + {{ .Content }} +{{ end }} +{{< /code >}} + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/Title.md b/docs/content/en/methods/resource/Title.md new file mode 100644 index 000000000..e30f86d2e --- /dev/null +++ b/docs/content/en/methods/resource/Title.md @@ -0,0 +1,95 @@ +--- +title: Title +description: Returns the title of the given resource as optionally defined in front matter, falling back to a relative path or hashed file name depending on resource type. +categories: [] +keywords: [] +action: + related: + - methods/resource/Name + returnType: string + signatures: [RESOURCE.Title] +toc: true +--- + +The value returned by the `Title` method on a `Resource` object depends on the resource type. + +## Global resource + +With a [global resource], the `Title` method returns the path to the resource, relative to the assets directory. + +```text +assets/ +└── images/ + └── a.jpg +``` + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Title }} → images/a.jpg +{{ end }} +``` + +## Page resource + +With a [page resource], the `Title` method returns the path to the resource, relative to the page bundle. + +```text +content/ +├── posts/ +│ ├── post-1/ +│ │ ├── images/ +│ │ │ └── a.jpg +│ │ └── index.md +│ └── _index.md +└── _index.md +``` + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + {{ .Title }} → images/a.jpg +{{ end }} +``` + +If you create an element in the `resources` array in front matter, the `Title` method returns the value of the `title` parameter: + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'Post 1' +[[resources]] +src = 'images/a.jpg' +name = 'cat' +title = 'Felix the cat' +[resources.params] +temperament = 'malicious' +{{< /code-toggle >}} + +```go-html-template +{{ with .Resources.Get "cat" }} + {{ .Title }} → Felix the cat +{{ end }} +``` + +If the page resource is a content file, the `Title` methods return the `title` field as defined in front matter. + +```text +content/ +├── lessons/ +│ ├── lesson-1/ +│ │ ├── _objectives.md <-- resource type = page +│ │ └── index.md +│ └── _index.md +└── _index.md +``` + +## Remote resource + +With a [remote resource], the `Title` method returns a hashed file name. + +```go-html-template +{{ with resources.GetRemote "https://example.org/images/a.jpg" }} + {{ .Title }} → a_18432433023265451104.jpg +{{ end }} +``` + +[global resource]: /getting-started/glossary/#global-resource +[page resource]: /getting-started/glossary/#page-resource +[remote resource]: /getting-started/glossary/#remote-resource diff --git a/docs/content/en/methods/resource/Width.md b/docs/content/en/methods/resource/Width.md new file mode 100644 index 000000000..8b96c95e8 --- /dev/null +++ b/docs/content/en/methods/resource/Width.md @@ -0,0 +1,27 @@ +--- +title: Width +description: Applicable to images, returns the width of the given resource. +categories: [] +keywords: [] +action: + related: + - methods/resource/Height + returnType: int + signatures: [RESOURCE.Width] +--- + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Width }} → 600 +{{ end }} +``` + +Use the `Width` and `Height` methods together when rendering an `img` element: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}"> +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} diff --git a/docs/content/en/methods/resource/_common/_index.md b/docs/content/en/methods/resource/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/content/en/methods/resource/_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/docs/content/en/methods/resource/_common/global-page-remote-resources.md b/docs/content/en/methods/resource/_common/global-page-remote-resources.md new file mode 100644 index 000000000..4ea4d1b87 --- /dev/null +++ b/docs/content/en/methods/resource/_common/global-page-remote-resources.md @@ -0,0 +1,13 @@ +--- +# Do not remove front matter. +--- + +{{% note %}} + +Use this method with [global], [page], or [remote] resources. + +[global]: /getting-started/glossary/#global-resource +[page]: /getting-started/glossary/#page-resource +[remote]: /getting-started/glossary/#remote-resource + +{{% /note %}} diff --git a/docs/content/en/methods/resource/_common/processing-spec.md b/docs/content/en/methods/resource/_common/processing-spec.md new file mode 100644 index 000000000..b12a21d3a --- /dev/null +++ b/docs/content/en/methods/resource/_common/processing-spec.md @@ -0,0 +1,36 @@ +--- +# Do not remove front matter. +--- + +## Process specification + +The process specification is a space-delimited, case-insensitive list of one or more of the following in any sequence: + +action +: Applicable to the [`Process`](/methods/resource/process) method only. Specify zero or one of `crop`, `fill`, `fit`, or `resize`. If you specify an action you must also provide dimensions. + +dimensions +: Provide width _or_ height when using the [`Resize`](/methods/resource/resize) method, else provide both width _and_ height. See [details](/content-management/image-processing/#dimensions). + +anchor +: Use with the [`Crop`](/methods/resource/crop) and [`Fill`](/methods/resource/fill) methods. Specify zero or one of `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. Default is `Smart`. See [details](/content-management/image-processing/#anchor). + +rotation +: Typically specify zero or one of `r90`, `r180`, or `r270`. Also supports arbitrary rotation angles. See [details](/content-management/image-processing/#rotation). + +target format +: Specify zero or one of `gif`, `jpeg`, `png`, `tiff`, or `webp`. See [details](/content-management/image-processing/#target-format). + +quality +: Applicable to JPEG and WebP images. Optionally specify `qN` where `N` is an integer in the range [0, 100]. Default is `75`. See [details](/content-management/image-processing/#quality). + +hint +: Applicable to WebP images and equivalent to the `-preset` flag for the [`cwebp`] encoder. Specify zero or one of `drawing`, `icon`, `photo`, `picture`, or `text`. Default is `photo`. See [details](/content-management/image-processing/#hint). + +[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp + +background color +: When converting a PNG or WebP with transparency to a format that does not support transparency, optionally specify a background color using a 3-digit or a 6-digit hexadecimal color code. Default is `#ffffff` (white). See [details](/content-management/image-processing/#background-color). + +resampling filter +: Typically specify zero or one of `Box`, `Lanczos`, `CatmullRom`, `MitchellNetravali`, `Linear`, or `NearestNeighbor`. Other resampling filters are available. See [details](/content-management/image-processing/#resampling-filter). diff --git a/docs/content/en/methods/resource/_index.md b/docs/content/en/methods/resource/_index.md new file mode 100644 index 000000000..e9426e1a5 --- /dev/null +++ b/docs/content/en/methods/resource/_index.md @@ -0,0 +1,12 @@ +--- +title: Resource methods +linkTitle: Resource +description: Use these methods with global, page, and remote Resource objects. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods with global, page, and remote Resource objects. diff --git a/docs/content/en/methods/shortcode/Get.md b/docs/content/en/methods/shortcode/Get.md new file mode 100644 index 000000000..cd674614f --- /dev/null +++ b/docs/content/en/methods/shortcode/Get.md @@ -0,0 +1,51 @@ +--- +title: Get +description: Returns the value of the given parameter. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/IsNamedParams + - methods/shortcode/Params + returnType: any + signatures: [SHORTCODE.Get PARAM] +toc: true +--- + +Specify the parameter by position or by name. When calling a shortcode within markdown, use either positional or named parameters, but not both. + +{{% note %}} +Some shortcodes support positional parameters, some support named parameters, and others support both. Refer to the shortcode's documentation for usage details. +{{% /note %}} + +## Positional parameters + +This shortcode call uses positional parameters: + +{{< code file=content/about.md lang=md >}} +{{</* myshortcode "Hello" "world" */>}} +{{< /code >}} + +To retrieve parameters by position: + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ printf "%s %s." (.Get 0) (.Get 1) }} → Hello world. +{{< /code >}} + +## Named parameters + +This shortcode call uses named parameters: + +{{< code file=content/about.md lang=md >}} +{{</* myshortcode greeting="Hello" firstName="world" */>}} +{{< /code >}} + +To retrieve parameters by name: + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ printf "%s %s." (.Get "greeting") (.Get "firstName") }} → Hello world. +{{< /code >}} + +{{% note %}} +Parameter names are case-sensitive. +{{% /note %}} diff --git a/docs/content/en/methods/shortcode/Inner.md b/docs/content/en/methods/shortcode/Inner.md new file mode 100644 index 000000000..de7c284cb --- /dev/null +++ b/docs/content/en/methods/shortcode/Inner.md @@ -0,0 +1,153 @@ +--- +title: Inner +description: Returns the content between opening and closing shortcode tags, applicable when the shortcode call includes a closing tag. +categories: [] +keywords: [] +action: + related: + - functions/strings/Trim + - methods/page/RenderString + - functions/transform/Markdownify + - methods/shortcode/InnerDeindent + returnType: template.HTML + signatures: [SHORTCODE.Inner] +--- + +This content: + +{{< code file=content/services.md lang=md >}} +{{</* card title="Product Design" */>}} +We design the **best** widgets in the world. +{{</* /card */>}} +{{< /code >}} + +With this shortcode: + +{{< code file=layouts/shortcodes/card.html >}} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + {{ trim .Inner "\r\n" }} + </div> +</div> +{{< /code >}} + +Is rendered to: + +```html +<div class="card"> + <div class="card-title">Product Design</div> + <div class="card-content"> + We design the **best** widgets in the world. + </div> +</div> +``` + +{{% note %}} +Content between opening and closing shortcode tags may include leading and/or trailing newlines, depending on placement within the markdown. Use the [`trim`] function as shown above to remove both carriage returns and newlines. + +[`trim`]: /functions/strings/trim +{{% /note %}} + +{{% note %}} +In the example above, the value returned by `Inner` is markdown, but it was rendered as plain text. Use either of the following approaches to render markdown to HTML. +{{% /note %}} + + +## Use the RenderString method + +Let's modify the example above to pass the value returned by `Inner` through the [`RenderString`] method on the `Page` object: + +[`RenderString`]: /methods/page/renderstring + +{{< code file=layouts/shortcodes/card.html >}} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + {{ trim .Inner "\r\n" | .Page.RenderString }} + </div> +</div> +{{< /code >}} + +Hugo renders this to: + +```html +<div class="card"> + <div class="card-title">Product design</div> + <div class="card-content"> + We produce the <strong>best</strong> widgets in the world. + </div> +</div> +``` + +You can use the [`markdownify`] function instead of the `RenderString` method, but the latter is more flexible. See [details]. + +[details]: /methods/page/renderstring +[`markdownify`]: /functions/transform/markdownify + +## Use alternate notation + +Instead of calling the shortcode with the `{{</* */>}}` notation, use the `{{%/* */%}}` notation: + +{{< code file=content/services.md lang=md >}} +{{%/* card title="Product Design" */%}} +We design the **best** widgets in the world. +{{%/* /card */%}} +{{< /code >}} + +When you use the `{{%/* */%}}` notation, Hugo renders the entire shortcode as markdown, requiring the following changes. + +First, configure the renderer to allow raw HTML within markdown: + +{{< code-toggle file=hugo >}} +[markup.goldmark.renderer] +unsafe = true +{{< /code-toggle >}} + +This configuration is not unsafe if _you_ control the content. Read more about Hugo's [security model]. + +Second, because we are rendering the entire shortcode as markdown, we must adhere to the rules governing [indentation] and inclusion of [raw HTML blocks] as provided in the [CommonMark] specification. + +{{< code file=layouts/shortcodes/card.html >}} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + + {{ trim .Inner "\r\n" }} + </div> +</div> +{{< /code >}} + +The difference between this and the previous example is subtle but required. Note the change in indentation, the addition of a blank line, and removal of the `RenderString` method. + +```diff +--- layouts/shortcodes/a.html ++++ layouts/shortcodes/b.html +@@ -1,8 +1,9 @@ + <div class="card"> + {{ with .Get "title" }} +- <div class="card-title">{{ . }}</div> ++ <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> +- {{ trim .Inner "\r\n" | .Page.RenderString }} ++ ++ {{ trim .Inner "\r\n" }} + </div> + </div> +``` + +{{% note %}} +When using the `{{%/* */%}}` notation, do not pass the value returned by `Inner` through the `RenderString` method or the `markdownify` function. +{{% /note %}} + +[commonmark]: https://commonmark.org/ +[indentation]: https://spec.commonmark.org/0.30/#indented-code-blocks +[raw html blocks]: https://spec.commonmark.org/0.30/#html-blocks +[security model]: /about/security-model/ diff --git a/docs/content/en/methods/shortcode/InnerDeindent.md b/docs/content/en/methods/shortcode/InnerDeindent.md new file mode 100644 index 000000000..136412bc7 --- /dev/null +++ b/docs/content/en/methods/shortcode/InnerDeindent.md @@ -0,0 +1,99 @@ +--- +title: InnerDeindent +description: Returns the content between opening and closing shortcode tags, with indentation removed, applicable when the shortcode call includes a closing tag. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/Inner + returnType: template.HTML + signatures: [SHORTCODE.InnerDeindent] +--- + +Similar to the [`Inner`] method, `InnerDeindent` returns the content between opening and closing shortcode tags. However, with `InnerDeindent`, indentation before the content is removed. + +This allows us to effectively bypass the rules governing [indentation] as provided in the [CommonMark] specification. + +Consider this markdown, an unordered list with a small gallery of thumbnail images within each list item: + +{{< code file=content/about.md lang=md >}} +- Gallery one + + {{</* gallery */>}} + ![kitten a](thumbnails/a.jpg) + ![kitten b](thumbnails/b.jpg) + {{</* /gallery */>}} + +- Gallery two + + {{</* gallery */>}} + ![kitten c](thumbnails/c.jpg) + ![kitten d](thumbnails/d.jpg) + {{</* /gallery */>}} +{{< /code >}} + +In the example above, notice that the content between the opening and closing shortcode tags is indented by four spaces. Per the CommonMark specification, this is treated as an indented code block. + +With this shortcode, calling `Inner` instead of `InnerDeindent`: + +{{< code file=layouts/shortcodes/gallery.html >}} +<div class="gallery"> + {{ trim .Inner "\r\n" | .Page.RenderString }} +</div> +{{< /code >}} + +Hugo renders the markdown to: + +```html +<ul> + <li> + <p>Gallery one</p> + <div class="gallery"> + <pre><code>![kitten a](images/a.jpg) + ![kitten b](images/b.jpg) + </code></pre> + </div> + </li> + <li> + <p>Gallery two</p> + <div class="gallery"> + <pre><code>![kitten c](images/c.jpg) + ![kitten d](images/d.jpg) + </code></pre> + </div> + </li> +</ul> +``` + +Although technically correct per the CommonMark specification, this is not what we want. If we remove the indentation using the `InnerDeindent` method: + +{{< code file=layouts/shortcodes/gallery.html >}} +<div class="gallery"> + {{ trim .InnerDeindent "\r\n" | .Page.RenderString }} +</div> +{{< /code >}} + +Hugo renders the markdown to: + +```html +<ul> + <li> + <p>Gallery one</p> + <div class="gallery"> + <img src="images/a.jpg" alt="kitten a"> + <img src="images/b.jpg" alt="kitten b"> + </div> + </li> + <li> + <p>Gallery two</p> + <div class="gallery"> + <img src="images/c.jpg" alt="kitten c"> + <img src="images/d.jpg" alt="kitten d"> + </div> + </li> +</ul> +``` + +[commonmark]: https://commonmark.org/ +[indentation]: https://spec.commonmark.org/0.30/#indented-code-blocks +[`Inner`]: /methods/shortcode/inner diff --git a/docs/content/en/methods/shortcode/IsNamedParams.md b/docs/content/en/methods/shortcode/IsNamedParams.md new file mode 100644 index 000000000..83eeb2f74 --- /dev/null +++ b/docs/content/en/methods/shortcode/IsNamedParams.md @@ -0,0 +1,30 @@ +--- +title: IsNamedParams +description: Reports whether the shortcode call uses named parameters. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/Get + returnType: bool + signatures: [SHORTCODE.IsNamedParams] +--- + +To support both positional and named parameters when calling a shortcode, use the `IsNamedParams` method to determine how the shortcode was called. + +With this shortcode template: + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ if .IsNamedParams }} + {{ printf "%s %s." (.Get "greeting") (.Get "firstName") }} +{{ else }} + {{ printf "%s %s." (.Get 0) (.Get 1) }} +{{ end }} +{{< /code >}} + +Both of these calls return the same value: + +{{< code file=content/about.md lang=md >}} +{{</* myshortcode greeting="Hello" firstName="world" */>}} +{{</* myshortcode "Hello" "world" */>}} +{{< /code >}} diff --git a/docs/content/en/methods/shortcode/Name.md b/docs/content/en/methods/shortcode/Name.md new file mode 100644 index 000000000..18bddfe1f --- /dev/null +++ b/docs/content/en/methods/shortcode/Name.md @@ -0,0 +1,29 @@ +--- +title: Name +description: Returns the shortcode file name, excluding the file extension. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/Position + - functions/fmt/Errorf + returnType: string + signatures: [SHORTCODE.Name] +--- + +The `Name` method is useful for error reporting. For example, if your shortcode requires a "greeting" parameter: + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ $greeting := "" }} +{{ with .Get "greeting" }} + {{ $greeting = . }} +{{ else }} + {{ errorf "The %q shortcode requires a 'greeting' parameter. See %s" .Name .Position }} +{{ end }} +{{< /code >}} + +In the absence of a "greeting" parameter, Hugo will throw an error message and fail the build: + +```text +ERROR The "myshortcode" shortcode requires a 'greeting' parameter. See "/home/user/project/content/about.md:11:1" +``` diff --git a/docs/content/en/methods/shortcode/Ordinal.md b/docs/content/en/methods/shortcode/Ordinal.md new file mode 100644 index 000000000..954940258 --- /dev/null +++ b/docs/content/en/methods/shortcode/Ordinal.md @@ -0,0 +1,50 @@ +--- +title: Ordinal +description: Returns the zero-based ordinal of the shortcode in relation to its parent. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [SHORTCODE.Ordinal] +--- + +The `Ordinal` method returns the zero-based ordinal of the shortcode in relation to its parent. If the parent is the page itself, the ordinal represents the position of this shortcode in the page content. + +This method is useful for, among other things, assigning unique element IDs when a shortcode is called two or more times from the same page. For example: + +{{< code file=content/about.md lang=md >}} +{{</* img src="images/a.jpg" */>}} + +{{</* img src="images/b.jpg" */>}} +{{< /code >}} + +This shortcode performs error checking, then renders an HTML `img` element with a unique `id` attribute: + +{{< code file=layouts/shortcodes/img.html >}} +{{ $src := "" }} +{{ with .Get "src" }} + {{ $src = . }} + {{ with resources.Get $src }} + {{ $id := printf "img-%03d" $.Ordinal }} + <img id="{{ $id }}" src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ else }} + {{ errorf "The %q shortcode was unable to find %s. See %s" $.Name $src $.Position }} + {{ end }} +{{ else }} + {{ errorf "The %q shortcode requires a 'src' parameter. See %s" .Name .Position }} +{{ end }} +{{< /code >}} + +Hugo renders the page to: + +```html +<img id="img-000" src="/images/a.jpg" width="600" height="400" alt=""> +<img id="img-001" src="/images/b.jpg" width="600" height="400" alt=""> +``` + +{{% note %}} +In the shortcode template above, the [`with`] statement is used to create conditional blocks. Remember that the `with` statement binds context (the dot) to its expression. Inside of a `with` block, preface shortcode method calls with a `$` to access the top level context passed into the template. + +[`with`]: /functions/go-template/with +{{% /note %}} diff --git a/docs/content/en/methods/shortcode/Page.md b/docs/content/en/methods/shortcode/Page.md new file mode 100644 index 000000000..c9262ab48 --- /dev/null +++ b/docs/content/en/methods/shortcode/Page.md @@ -0,0 +1,36 @@ +--- +title: Page +description: Returns the Page object from which the shortcode was called. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.pageForShortcode + signatures: [SHORTCODE.Page] +--- + +With this content: + +{{< code-toggle file=content/books/les-miserables.md fm=true >}} +title = 'Les Misérables' +author = 'Victor Hugo' +published = 1862 +isbn = '978-0451419439' +{{< /code-toggle >}} + +Calling this shortcode: + +```text +{{</* book-details */>}} +``` + +We can access the front matter values using the `Page` method: + +{{< code file=layouts/shortcodes/book-details.html >}} +<ul> + <li>Title: {{ .Page.Title }}</li> + <li>Author: {{ .Page.Params.author }}</li> + <li>Published: {{ .Page.Params.publication_year }}</li> + <li>ISBN: {{ .Page.Params.isbn }}</li> +</ul> +{{< /code >}} diff --git a/docs/content/en/methods/shortcode/Params.md b/docs/content/en/methods/shortcode/Params.md new file mode 100644 index 000000000..63df768a6 --- /dev/null +++ b/docs/content/en/methods/shortcode/Params.md @@ -0,0 +1,33 @@ +--- +title: Params +description: Returns a collection of the shortcode parameters. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/Get + returnType: any + signatures: [SHORTCODE.Params] +--- + +When you call a shortcode using positional parameters, the `Params` method returns a slice. + +{{< code file=content/about.md lang=md >}} +{{</* myshortcode "Hello" "world" */>}} +{{< /code >}} + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ index .Params 0 }} → Hello +{{ index .Params 1 }} → world +{{< /code >}} + +When you call a shortcode using named parameters, the `Params` method returns a map. + +{{< code file=content/about.md lang=md >}} +{{</* myshortcode greeting="Hello" name="world" */>}} +{{< /code >}} + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ .Params.greeting }} → Hello +{{ .Params.name }} → world +{{< /code >}} diff --git a/docs/content/en/methods/shortcode/Parent.md b/docs/content/en/methods/shortcode/Parent.md new file mode 100644 index 000000000..50ae521da --- /dev/null +++ b/docs/content/en/methods/shortcode/Parent.md @@ -0,0 +1,50 @@ +--- +title: Parent +description: Returns the parent shortcode context in nested shortcodes. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.ShortcodeWithPage + signatures: [SHORTCODE.Parent] +--- + +This is useful for inheritance of common shortcode parameters from the root. + +In this contrived example, the "greeting" shortcode is the parent, and the "now" shortcode is child. + +{{< code file=content/welcome.md lang=md >}} +{{</* greeting dateFormat="Jan 2, 2006" */>}} +Welcome. Today is {{</* now */>}}. +{{</* /greeting */>}} +{{< /code >}} + +{{< code file=layouts/shortcodes/greeting.html >}} +<div class="greeting"> + {{ trim .Inner "\r\n" | .Page.RenderString }} +</div> +{{< /code >}} + +{{< code file=layouts/shortcodes/now.html >}} +{{- $dateFormat := "January 2, 2006 15:04:05" }} + +{{- with .Params }} + {{- with .dateFormat }} + {{- $dateFormat = . }} + {{- end }} +{{- else }} + {{- with .Parent.Params }} + {{- with .dateFormat }} + {{- $dateFormat = . }} + {{- end }} + {{- end }} +{{- end }} + +{{- now | time.Format $dateFormat -}} +{{< /code >}} + +The "now" shortcode formats the current time using: + +1. The `dateFormat` parameter passed to the "now" shortcode, if present +2. The `dateFormat` parameter passed to the "greeting" shortcode, if present +3. The default layout string defined at the top of the shortcode diff --git a/docs/content/en/methods/shortcode/Position.md b/docs/content/en/methods/shortcode/Position.md new file mode 100644 index 000000000..565a158bf --- /dev/null +++ b/docs/content/en/methods/shortcode/Position.md @@ -0,0 +1,33 @@ +--- +title: Position +description: Returns the filename and position from which the shortcode was called. +categories: [] +keywords: [] +action: + related: + - methods/shortcode/Name + - functions/fmt/Errorf + returnType: text.Position + signatures: [SHORTCODE.Position] +--- + +The `Position` method is useful for error reporting. For example, if your shortcode requires a "greeting" parameter: + +{{< code file=layouts/shortcodes/myshortcode.html >}} +{{ $greeting := "" }} +{{ with .Get "greeting" }} + {{ $greeting = . }} +{{ else }} + {{ errorf "The %q shortcode requires a 'greeting' parameter. See %s" .Name .Position }} +{{ end }} +{{< /code >}} + +In the absence of a "greeting" parameter, Hugo will throw an error message and fail the build: + +```text +ERROR The "myshortcode" shortcode requires a 'greeting' parameter. See "/home/user/project/content/about.md:11:1" +``` + +{{% note %}} +The position can be expensive to calculate. Limit its use to error reporting. +{{% /note %}} diff --git a/docs/content/en/methods/shortcode/Ref.md b/docs/content/en/methods/shortcode/Ref.md new file mode 100644 index 000000000..293c772d9 --- /dev/null +++ b/docs/content/en/methods/shortcode/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/shortcode/RelRef + - functions/urls/RelRef + - functions/urls/Ref + returnType: string + signatures: [SHORTCODE.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/docs/content/en/methods/shortcode/RelRef.md b/docs/content/en/methods/shortcode/RelRef.md new file mode 100644 index 000000000..07f221a99 --- /dev/null +++ b/docs/content/en/methods/shortcode/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/shortcode/Ref + - functions/urls/Ref + - functions/urls/RelRef + returnType: string + signatures: [SHORTCODE.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/docs/content/en/methods/shortcode/Scratch.md b/docs/content/en/methods/shortcode/Scratch.md new file mode 100644 index 000000000..3ab195a3f --- /dev/null +++ b/docs/content/en/methods/shortcode/Scratch.md @@ -0,0 +1,24 @@ +--- +title: Scratch +description: Creates a "scratch pad" scoped to the shortcode to store and manipulate data. +categories: [] +keywords: [] +action: + related: + - functions/collections/NewScratch + returnType: maps.Scratch + signatures: [SHORTCODE.Scratch] +--- + +The `Scratch` method within a shortcode creates a [scratch pad] to store and manipulate data. The scratch pad is scoped to the shortcode, and is reset on server rebuilds. + +{{% note %}} +With the introduction of the [`newScratch`] function, and the ability to [assign values to template variables] after initialization, the `Scratch` method within a shortcode is obsolete. + +[assign values to template variables]: https://go.dev/doc/go1.11#text/template +[`newScratch`]: functions/collections/newscratch +{{% /note %}} + +[scratch pad]: /getting-started/glossary/#scratch-pad + +{{% include "methods/page/_common/scratch-methods.md" %}} diff --git a/docs/content/en/methods/shortcode/Site.md b/docs/content/en/methods/shortcode/Site.md new file mode 100644 index 000000000..fa2d274de --- /dev/null +++ b/docs/content/en/methods/shortcode/Site.md @@ -0,0 +1,19 @@ +--- +title: Site +description: Returns the Site object. +categories: [] +keywords: [] +action: + related: + - methods/page/Sites + returnType: page.siteWrapper + signatures: [SHORTCODE.Site] +--- + +See [Site methods]. + +[Site methods]: /methods/site + +```go-html-template +{{ .Site.Title }} +``` diff --git a/docs/content/en/methods/shortcode/_index.md b/docs/content/en/methods/shortcode/_index.md new file mode 100644 index 000000000..d26366844 --- /dev/null +++ b/docs/content/en/methods/shortcode/_index.md @@ -0,0 +1,12 @@ +--- +title: Shortcode methods +linkTitle: Shortcode +description: Use these methods in your shortcode templates. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods in your shortcode templates. diff --git a/docs/content/en/methods/site/AllPages.md b/docs/content/en/methods/site/AllPages.md new file mode 100644 index 000000000..8df6348f9 --- /dev/null +++ b/docs/content/en/methods/site/AllPages.md @@ -0,0 +1,26 @@ +--- +title: AllPages +description: Returns a collection of all pages in all languages. +categories: [] +keywords: [] +action: + related: + - methods/site/Pages + - methods/site/RegularPages + - methods/site/Sections + returnType: page.Pages + signatures: [SITE.AllPages] +--- + +This method returns all page [kinds] in all languages. That includes the home page, section pages, taxonomy pages, term pages, and regular pages. + +In most cases you should use the [`RegularPages`] method instead. + +[`RegularPages`]: methods/site/regularpages +[kinds]: /getting-started/glossary/#page-kind + +```go-html-template +{{ range .Site.AllPages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/site/BaseURL.md b/docs/content/en/methods/site/BaseURL.md new file mode 100644 index 000000000..f9c43bca3 --- /dev/null +++ b/docs/content/en/methods/site/BaseURL.md @@ -0,0 +1,37 @@ +--- +title: BaseURL +description: Returns the base URL as defined in the site configuration. +categories: [] +keywords: [] +action: + related: + - functions/urls/AbsURL + - functions/urls/AbsLangURL + - functions/urls/RelURL + - functions/urls/RelLangURL + returnType: string + signatures: [SITE.BaseURL] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.BaseURL }} → https://example.org/docs/ +``` + +{{% note %}} +There is almost never a good reason to use this method in your templates. Its usage tends to be fragile due to misconfiguration. + +Use the [`absURL`], [`absLangURL`], [`relURL`], or [`relLangURL`] functions instead. + +[`absURL`]: /functions/urls/absURL +[`absLangURL`]: /functions/urls/absLangURL +[`relURL`]: /functions/urls/relURL +[`relLangURL`]: /functions/urls/relLangURL +{{% /note %}} diff --git a/docs/content/en/methods/site/BuildDrafts.md b/docs/content/en/methods/site/BuildDrafts.md new file mode 100644 index 000000000..0d85c78fd --- /dev/null +++ b/docs/content/en/methods/site/BuildDrafts.md @@ -0,0 +1,28 @@ +--- +title: BuildDrafts +description: Reports whether the current build includes draft pages. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.BuildDrafts] +--- + +By default, draft pages are not published when building a site. You can change this behavior with a command line flag: + +```sh +hugo --buildDrafts +``` + +Or by setting `buildDrafts` to `true` in your site configuration: + +{{< code-toggle file=hugo >}} +buildDrafts = true +{{< /code-toggle >}} + +Use the `BuildDrafts` method on a `Site` object to determine the current configuration: + +```go-html-template +{{ .Site.BuildDrafts }} → true +``` diff --git a/docs/content/en/methods/site/Config.md b/docs/content/en/methods/site/Config.md new file mode 100644 index 000000000..0ff4cddec --- /dev/null +++ b/docs/content/en/methods/site/Config.md @@ -0,0 +1,57 @@ +--- +title: Config +description: Returns a subset of the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: page.SiteConfig + signatures: [SITE.Config] +toc: true +--- + +The `Config` method on a `Site` object provides access to a subset of the site configuration, specifically the `services` and `privacy` keys. + +## Services + +These are the default service settings, typically used by Hugo's built-in templates and shortcodes. + +{{< code-toggle config=services />}} + +For example, to use Hugo's built-in Google Analytics template you must add a [Google tag ID]: + +[Google tag ID]: https://support.google.com/tagmanager/answer/12326985?hl=en + +{{< code-toggle file=hugo >}} +[services.googleAnalytics] +id = 'G-XXXXXXXXX' +{{< /code-toggle >}} + +To access this value from a template: + +```go-html-template +{{ .Site.Config.Services.GoogleAnalytics.ID }} → G-XXXXXXXXX +``` + +You must capitalize each identifier as shown above. + +## Privacy + +These are the default privacy settings, typically used by Hugo's built-in templates and shortcodes: + +{{< code-toggle config=privacy />}} + +For example, to disable usage of the built-in YouTube shortcode: + +{{< code-toggle file=hugo >}} +[privacy.youtube] +disable = true +{{< /code-toggle >}} + +To access this value from a template: + +```go-html-template +{{ .Site.Config.Privacy.YouTube.Disable }} → true +``` + +You must capitalize each identifier as shown above. diff --git a/docs/content/en/methods/site/Copyright.md b/docs/content/en/methods/site/Copyright.md new file mode 100644 index 000000000..e2ae7d2a5 --- /dev/null +++ b/docs/content/en/methods/site/Copyright.md @@ -0,0 +1,22 @@ +--- +title: Copyright +description: Returns the copyright notice as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.Copyright] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +copyright = '© 2023 ABC Widgets, Inc.' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Copyright }} → © 2023 ABC Widgets, Inc. +``` diff --git a/docs/content/en/methods/site/Data.md b/docs/content/en/methods/site/Data.md new file mode 100644 index 000000000..b78caddec --- /dev/null +++ b/docs/content/en/methods/site/Data.md @@ -0,0 +1,108 @@ +--- +title: Data +description: Returns a data structure composed from the files in the data directory. +categories: [] +keywords: [] +action: + related: + - functions/collections/IndexFunction + - functions/transform/Unmarshal + - functions/collections/Where + - functions/collections/Sort + returnType: map + signatures: [SITE.Data] +--- + +Use the `Data` method on a `Site` object to access data within the data directory, or within any directory [mounted] to the data directory. Supported data formats include JSON, TOML, YAML, and XML. + +[mounted]: /hugo-modules/configuration/#module-configuration-mounts + +{{% note %}} +Although Hugo can unmarshal CSV files with the [`transform.Unmarshal`] function, do not place CSV files in the data directory. You cannot access data within CSV files using this method. + +[`transform.Unmarshal`]: /functions/transform/unmarshal +{{% /note %}} + +Consider this data directory: + +```text +data/ +├── books/ +│ ├── fiction.yaml +│ └── nonfiction.yaml +├── films.json +├── paintings.xml +└── sculptures.toml +``` + +And these data files: + +{{< code file=data/books/fiction.yaml lang=yaml >}} +- title: The Hunchback of Notre Dame + author: Victor Hugo + isbn: 978-0140443530 +- title: Les Misérables + author: Victor Hugo + isbn: 978-0451419439 +{{< /code >}} + +{{< code file=data/books/nonfiction.yaml lang=yaml >}} +- title: The Ancien Régime and the Revolution + author: Alexis de Tocqueville + isbn: 978-0141441641 +- title: Interpreting the French Revolution + author: François Furet + isbn: 978-0521280495 +{{< /code >}} + +Access the data by [chaining] the [identifiers]: + +```go-html-template +{{ range $category, $books := .Site.Data.books }} + <p>{{ $category | title }}</p> + <ul> + {{ range $books }} + <li>{{ .title }} ({{ .isbn }})</li> + {{ end }} + </ul> +{{ end }} +``` + +Hugo renders this to: + +```html +<p>Fiction</p> +<ul> + <li>The Hunchback of Notre Dame (978-0140443530)</li> + <li>Les Misérables (978-0451419439)</li> +</ul> +<p>Nonfiction</p> +<ul> + <li>The Ancien Régime and the Revolution (978-0141441641)</li> + <li>Interpreting the French Revolution (978-0521280495)</li> +</ul> +``` + +To limit the listing to fiction, and sort by title: + +```go-html-template +<ul> + {{ range sort .Site.Data.books.fiction "title" }} + <li>{{ .title }} ({{ .author }})</li> + {{ end }} +</ul> +``` + +To find a fiction book by ISBN: + +```go-html-template +{{ range where .Site.Data.books.fiction "isbn" "978-0140443530" }} + <li>{{ .title }} ({{ .author }})</li> +{{ end }} +``` + +In the template examples above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function: + +[`index`]: /functions/collections/indexfunction +[chaining]: /getting-started/glossary/#chain +[identifiers]: /getting-started/glossary/#identifier diff --git a/docs/content/en/methods/site/DisqusShortname.md b/docs/content/en/methods/site/DisqusShortname.md new file mode 100644 index 000000000..359b836af --- /dev/null +++ b/docs/content/en/methods/site/DisqusShortname.md @@ -0,0 +1,20 @@ +--- +title: DisqusShortname +description: Returns the Disqus shortname as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.DisqusShortname] +# deprecated 2023-10-30 +expiryDate: 2024-10-30 +_build: + list: never +--- + +{{% deprecated-in 0.120.0 %}} +Use [`Site.Config.Services.Disqus.Shortname`] instead. + +[`Site.Config.Services.Disqus.Shortname`]: /methods/site/config +{{% /deprecated-in %}} diff --git a/docs/content/en/methods/site/GetPage.md b/docs/content/en/methods/site/GetPage.md new file mode 100644 index 000000000..1e949f37c --- /dev/null +++ b/docs/content/en/methods/site/GetPage.md @@ -0,0 +1,109 @@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +action: + related: + - methods/page/GetPage + returnType: hugolib.pageState + signatures: [SITE.GetPage PATH] +toc: true +--- + +The `GetPage` method is also available on `Page` objects, allowing you to specify a path relative to the current page. See [details]. + +[details]: /methods/page/getpage + +When using the `GetPage` method on a `Site` object, specify a path relative to the content directory. + +If Hugo cannot resolve the path to a page, the method returns nil. + +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 +``` + +This home page template: + +```go-html-template +{{ with .Site.GetPage "/works/paintings" }} + <ul> + {{ range .Pages }} + <li>{{ .Title }} by {{ .Params.artist }}</li> + {{ end }} + </ul> +{{ end }} +``` + +Is rendered to: + +```html +<ul> + <li>Starry Night by Vincent van Gogh</li> + <li>The Mona Lisa by Leonardo da Vinci</li> +</ul> +``` + +To get a regular page instead of a section page: + +```go-html-template +{{ with .Site.GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Starry Night + {{ .Params.artist }} → Vincent van Gogh +{{ end }} +``` + +## Multilingual projects + +With multilingual projects, the `GetPage` method on a `Site` object resolves the given path to a page in the current language. + +To get a page from a different language, query the `Sites` object: + +```go-html-template +{{ with where .Site.Sites "Language.Lang" "eq" "de" }} + {{ with index . 0 }} + {{ with .GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Sternenklare Nacht + {{ end }} + {{ end }} +{{ end }} +``` + +## Page bundles + +Consider this content structure: + +```text +content/ +├── headless/ +│ ├── a.jpg +│ ├── b.jpg +│ ├── c.jpg +│ └── index.md <-- front matter: headless = true +└── _index.md +``` + +In the home page template, use the `GetPage` method on a `Site` object to render all the images in the headless [page bundle]: + +```go-html-template +{{ with .Site.GetPage "/headless" }} + {{ range .Resources.ByType "image" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +[page bundle]: /getting-started/glossary/#page-bundle diff --git a/docs/content/en/methods/site/GoogleAnalytics.md b/docs/content/en/methods/site/GoogleAnalytics.md new file mode 100644 index 000000000..405cf0de5 --- /dev/null +++ b/docs/content/en/methods/site/GoogleAnalytics.md @@ -0,0 +1,20 @@ +--- +title: GoogleAnalytics +description: Returns the Google Analytics tracking ID as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.GoogleAnalytics] +# deprecated 2023-10-30 +expiryDate: 2024-10-30 +_build: + list: never +--- + +{{% deprecated-in 0.120.0 %}} +Use [`Site.Config.Services.GoogleAnalytics.ID`] instead. + +[`Site.Config.Services.GoogleAnalytics.ID`]: /methods/site/config +{{% /deprecated-in %}} diff --git a/docs/content/en/methods/site/Home.md b/docs/content/en/methods/site/Home.md new file mode 100644 index 000000000..52612dd12 --- /dev/null +++ b/docs/content/en/methods/site/Home.md @@ -0,0 +1,25 @@ +--- +title: Home +description: Returns the home Page object for the given site. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.pageState + signatures: [SITE.Home] +--- + +This method is useful for obtaining a link to the home page. + +Site configuration: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Home.Permalink }} → https://example.org/docs/ +{{ .Site.Home.RelPermalink }} → /docs/ +``` diff --git a/docs/content/en/methods/site/IsDevelopment.md b/docs/content/en/methods/site/IsDevelopment.md new file mode 100644 index 000000000..fdeae15fa --- /dev/null +++ b/docs/content/en/methods/site/IsDevelopment.md @@ -0,0 +1,20 @@ +--- +title: IsDevelopment +description: Reports whether the current running environment is “development”. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.IsDevelopment] +# deprecated 2023-10-30 +expiryDate: 2024-10-30 +_build: + list: never +--- + +{{% deprecated-in 0.120.0 %}} +Use [`hugo.IsDevelopment`] instead. + +[`hugo.IsDevelopment`]: /functions/hugo/isdevelopment +{{% /deprecated-in %}} diff --git a/docs/content/en/methods/site/IsMultiLingual.md b/docs/content/en/methods/site/IsMultiLingual.md new file mode 100644 index 000000000..61cc5e462 --- /dev/null +++ b/docs/content/en/methods/site/IsMultiLingual.md @@ -0,0 +1,34 @@ +--- +title: IsMultiLingual +description: Reports whether the site is multilingual. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.IsMultiLingual] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true +[languages] + [languages.de] + languageCode = 'de-DE' + languageName = 'Deutsch' + title = 'Projekt Dokumentation' + weight = 1 + [languages.en] + languageCode = 'en-US' + languageName = 'English' + title = 'Project Documentation' + weight = 2 +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.IsMultiLingual }} → true +``` diff --git a/docs/content/en/methods/site/IsServer.md b/docs/content/en/methods/site/IsServer.md new file mode 100644 index 000000000..c19a84bc9 --- /dev/null +++ b/docs/content/en/methods/site/IsServer.md @@ -0,0 +1,20 @@ +--- +title: IsServer +description: Reports whether the built-in development server is running. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.IsServer] +# deprecated 2023-10-30 +expiryDate: 2024-10-30 +_build: + list: never +--- + +{{% deprecated-in 0.120.0 %}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver +{{% /deprecated-in %}} diff --git a/docs/content/en/methods/site/Language.md b/docs/content/en/methods/site/Language.md new file mode 100644 index 000000000..1babc099b --- /dev/null +++ b/docs/content/en/methods/site/Language.md @@ -0,0 +1,83 @@ +--- +title: Language +description: Returns the language object for the given site. +categories: [] +keywords: [] +action: + related: + - methods/page/language + returnType: langs.Language + signatures: [SITE.Language] +toc: true +--- + +The `Language` method on a `Site` object returns the language object for the given site. The language object points to the language definition in the site configuration. + +You can also use the `Language` method on a `Page` object. See [details]. + +## Methods + +The examples below assume the following in your site configuration: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +weight = 1 +{{< /code-toggle >}} + +Lang +: (`string`) The language tag as defined by [RFC 5646]. + +```go-html-template +{{ .Site.Language.Lang }} → de +``` + +LanguageCode +: (`string`) The language code from the site configuration. + +```go-html-template +{{ .Site.Language.LanguageCode }} → de-DE +``` + +LanguageDirection +: (`string`) The language direction from the site configuration, either `ltr` or `rtl`. + +```go-html-template +{{ .Site.Language.LanguageDirection }} → ltr +``` + +LanguageName +: (`string`) The language name from the site configuration. + +```go-html-template +{{ .Site.Language.LanguageName }} → Deutsch +``` + +Weight +: (`int`) The language weight from the site configuration which determines its order in the slice of languages returned by the `Languages` method on a `Site` object. + +```go-html-template +{{ .Site.Language.Weight }} → 1 +``` + +## Example + +Some of the methods above are commonly used in a base template as attributes for the `html` element. + +```go-html-template +<html + lang="{{ or site.Language.LanguageCode site.Language.Lang }}" + dir="{{ or site.Language.LanguageDirection `ltr` }} +> +``` + +The example above uses the global [`site`] function instead of accessing the `Site` object via the `.Site` notation. + +Also note that each attribute has a fallback value assigned via the [`or`] operator. + +[details]: /methods/page/language +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 +[`or`]: /functions/go-template/or +[`site`]: /functions/global/site diff --git a/docs/content/en/methods/site/LanguagePrefix.md b/docs/content/en/methods/site/LanguagePrefix.md new file mode 100644 index 000000000..88808eda0 --- /dev/null +++ b/docs/content/en/methods/site/LanguagePrefix.md @@ -0,0 +1,53 @@ +--- +title: LanguagePrefix +description: Returns the URL language prefix, if any, for the given site. +categories: [] +keywords: [] +action: + related: + - functions/urls/AbsLangURL + - functions/urls/RelLangURL + returnType: string + signatures: [SITE.LanguagePrefix] +--- + +Consider 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 >}} + +When visiting the German language site: + +```go-html-template +{{ .Site.LanguagePrefix }} → "" +``` + +When visiting the English language site: + +```go-html-template +{{ .Site.LanguagePrefix }} → /en +``` + +If you change `defaultContentLanguageInSubdir` to `true`, when visiting the German language site: + +```go-html-template +{{ .Site.LanguagePrefix }} → /de +``` + +You may use the `LanguagePrefix` method with both monolingual and multilingual sites. diff --git a/docs/content/en/methods/site/Languages.md b/docs/content/en/methods/site/Languages.md new file mode 100644 index 000000000..26bdefc21 --- /dev/null +++ b/docs/content/en/methods/site/Languages.md @@ -0,0 +1,59 @@ +--- +title: Languages +description: Returns a collection of language objects for all sites, ordered by language weight. +categories: [] +keywords: [] +action: + related: + - methods/site/Language + returnType: langs.Languages + signatures: [SITE.Languages] +--- + +The `Languages` method on a `Site` object returns a collection of language objects for all sites, ordered by language weight. Each language object points to its language definition in the site configuration. + +To view the data structure: + +```go-html-template +<pre>{{ jsonify (dict "indent" " ") .Site.Languages }}</pre> +``` + +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 .Site.Languages }} + <li>{{ .Title }} ({{ .LanguageName }})</li> + {{ end }} +</ul> +``` + +Is rendered to: + +```html +<ul> + <li>Projekt Dokumentation (Deutsch)</li> + <li>Project Documentation (English)</li> +</ul> +``` diff --git a/docs/content/en/methods/site/LastChange.md b/docs/content/en/methods/site/LastChange.md new file mode 100644 index 000000000..aceee691d --- /dev/null +++ b/docs/content/en/methods/site/LastChange.md @@ -0,0 +1,21 @@ +--- +title: LastChange +description: Returns the last modification date of site content. +categories: [] +keywords: [] +action: + related: [] + returnType: time.Time + signatures: [SITE.LastChange] +--- + +The `LastChange` method on a `Site` object returns a [`time.Time`] value. Use this with time [functions] and [methods]. For example: + +```go-html-template +{{ .Site.LastChange | time.Format ":date_long" }} → October 16, 2023 + +``` + +[`time.Time`]: https://pkg.go.dev/time#Time +[functions]: /functions/time +[methods]: /methods/time diff --git a/docs/content/en/methods/site/MainSections.md b/docs/content/en/methods/site/MainSections.md new file mode 100644 index 000000000..251fe1a97 --- /dev/null +++ b/docs/content/en/methods/site/MainSections.md @@ -0,0 +1,55 @@ +--- +title: MainSections +description: Returns a slice of the main section names as defined in the site configuration, falling back to the top level section with the most pages. +categories: [] +keywords: [] +action: + related: [] + returnType: '[]string' + signatures: [SITE.MainSections] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +[params] +mainSections = ['books','films'] +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.MainSections }} → [books films] +``` + +If `params.mainSections` is not defined in the site configuration, this method returns a slice with one element---the top level section with the most pages. + +With this content structure, the "films" section has the most pages: + +```text +content/ +├── books/ +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── film-1.md +│ ├── film-2.md +│ └── film-3.md +└── _index.md +``` + +Template: + +```go-html-template +{{ .Site.MainSections }} → [films] +``` + +When creating a theme, instead of hardcoding section names when listing the most relevant pages on the front page, instruct site authors to set `params.mainSections` in their site configuration. + +Then your home page template can do something like this: + +```go-html-template +{{ range where .Site.RegularPages "Section" "in" .Site.MainSections }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/site/Menus.md b/docs/content/en/methods/site/Menus.md new file mode 100644 index 000000000..1967a9211 --- /dev/null +++ b/docs/content/en/methods/site/Menus.md @@ -0,0 +1,94 @@ +--- +title: Menus +description: Returns a collection of menu objects for the given site. +categories: [] +keywords: [] +action: + related: + - methods/page/IsMenuCurrent + - methods/page/HasMenuCurrent + returnType: navigation.Menus + signatures: [SITE.Menus] +--- + +The `Menus` method on a `Site` object returns a collection of menus, where each menu contains one or more entries, either flat or nested. Each entry points to a page within the site, or to an external resource. + +{{% note %}} +Menus can be defined and localized in several ways. Please see the [menus] section for a complete explanation and examples. + +[menus]: /content-management/menus/ +{{% /note %}} + +A site can have multiple menus. For example, a main menu and a footer menu: + +{{< code-toggle file=hugo >}} +[[menu.main]] +name = 'Home' +pageRef = '/' +weight = 10 + +[[menu.main]] +name = 'Books' +pageRef = '/books' +weight = 20 + +[[menu.main]] +name = 'Films' +pageRef = '/films' +weight = 30 + +[[menu.footer]] +name = 'Legal' +pageRef = '/legal' +weight = 10 + +[[menu.footer]] +name = 'Privacy' +pageRef = '/privacy' +weight = 20 +{{< /code-toggle >}} + +This template renders the main menu: + +```go-html-template +{{ with site.Menus.main }} + <nav class="menu"> + {{ range . }} + {{ if $.IsMenuCurrent .Menu . }} + <a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a> + {{ else }} + <a href="{{ .URL }}">{{ .Name }}</a> + {{ end }} + {{ end }} + </nav> +{{ end }} +``` + +When viewing the home page, the result is: + +```html +<nav class="menu"> + <a class="active" aria-current="page" href="/">Home</a> + <a href="/books/">Books</a> + <a href="/films/">Films</a> +</nav> +``` + +When viewing the "books" page, the result is: + +```html +<nav class="menu"> + <a href="/">Home</a> + <a class="active" aria-current="page" href="/books/">Books</a> + <a href="/films/">Films</a> +</nav> +``` + +You will typically render a menu using a partial template. As the active menu entry will be different on each page, use the [`partial`] function to call the template. Do not use the [`partialCached`] function. + +The example above is simplistic. Please see the [menu templates] section for more information. + +[menu templates]: /templates/menu-templates + +[`partial`]: /functions/partials/include +[`partialCached`]: /functions/partials/includecached diff --git a/docs/content/en/methods/site/Pages.md b/docs/content/en/methods/site/Pages.md new file mode 100644 index 000000000..583e98c11 --- /dev/null +++ b/docs/content/en/methods/site/Pages.md @@ -0,0 +1,26 @@ +--- +title: Pages +description: Returns a collection of all pages. +categories: [] +keywords: [] +action: + related: + - methods/site/AllPages + - methods/site/RegularPages + - methods/site/Sections + returnType: page.Pages + signatures: [SITE.Pages] +--- + +This method returns all page [kinds] in the current language. That includes the home page, section pages, taxonomy pages, term pages, and regular pages. + +In most cases you should use the [`RegularPages`] method instead. + +[`RegularPages`]: methods/site/regularpages +[kinds]: /getting-started/glossary/#page-kind + +```go-html-template +{{ range .Site.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` diff --git a/docs/content/en/methods/site/Param.md b/docs/content/en/methods/site/Param.md new file mode 100644 index 000000000..b699ef2d4 --- /dev/null +++ b/docs/content/en/methods/site/Param.md @@ -0,0 +1,29 @@ +--- +title: Param +description: Returns the site parameter with the given key. +categories: [] +keywords: [] +action: + related: [] + returnType: any + signatures: [SITE.Param KEY] +--- + +The `Param` method on a `Site` object is a convenience method to return the value of a user-defined parameter in the site configuration. + +{{< code-toggle file=hugo >}} +[params] +display_toc = true +{{< /code-toggle >}} + + +```go-html-template +{{ .Site.Param "display_toc" }} → true +``` + +The above is equivalent to either of these: + +```go-html-template +{{ .Site.Params.display_toc }} +{{ index .Site.Params "display_toc" }} +``` diff --git a/docs/content/en/methods/site/Params.md b/docs/content/en/methods/site/Params.md new file mode 100644 index 000000000..518d93bf3 --- /dev/null +++ b/docs/content/en/methods/site/Params.md @@ -0,0 +1,47 @@ +--- +title: Params +description: Returns a map of custom parameters as defined in the site configuration. +categories: [] +keywords: [] +action: + related: + - functions/collections/indexFunction + - methods/page/Params + - methods/page/Param + returnType: maps.Params + signatures: [SITE.Params] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +[params] + subtitle = 'The Best Widgets on Earth' + copyright-year = '2023' + [params.author] + email = '[email protected]' + name = 'John Smith' + [params.layouts] + rfc_1123 = 'Mon, 02 Jan 2006 15:04:05 MST' + rfc_3339 = '2006-01-02T15:04:05-07:00' +{{< /code-toggle >}} + +Access the custom parameters by [chaining] the [identifiers]: + +```go-html-template +{{ .Site.Params.subtitle }} → The Best Widgets on Earth +{{ .Site.Params.author.name }} → John Smith + +{{ $layout := .Site.Params.layouts.rfc_1123 }} +{{ .Site.LastChange.Format $layout }} → Tue, 17 Oct 2023 13:21:02 PDT +``` + +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 .Site.Params "copyright-year" }} → 2023 +``` + +[`index`]: /functions/collections/indexfunction +[chaining]: /getting-started/glossary/#chain +[identifiers]: /getting-started/glossary/#identifier diff --git a/docs/content/en/methods/site/RegularPages.md b/docs/content/en/methods/site/RegularPages.md new file mode 100644 index 000000000..b163ad919 --- /dev/null +++ b/docs/content/en/methods/site/RegularPages.md @@ -0,0 +1,38 @@ +--- +title: RegularPages +description: Returns a collection of all regular pages. +categories: [] +keywords: [] +action: + related: + - methods/site/AllPages + - methods/site/RegularPages + - methods/site/Sections + returnType: page.Pages + signatures: [SITE.RegularPages] +--- + +```go-html-template +{{ range .Site.RegularPages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +By default, Hugo sorts page collections by: + +1. The page `weight` as defined in front matter +1. The page `date` as defined in front matter +1. The page `linkTitle` as defined in front matter +1. The file path + +If the `linkTitle` is not defined, Hugo evaluates the `title` instead. + +To change the sort order, use any of the `Pages` [sorting methods]. For example: + +```go-html-template +{{ range .Site.RegularPages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +[sorting methods]: /methods/pages/ diff --git a/docs/content/en/methods/site/Sections.md b/docs/content/en/methods/site/Sections.md new file mode 100644 index 000000000..a397c5926 --- /dev/null +++ b/docs/content/en/methods/site/Sections.md @@ -0,0 +1,41 @@ +--- +title: Sections +description: Returns a collection of first level section pages. +categories: [] +keywords: [] +action: + related: + - methods/site/AllPages + - methods/site/Pages + - methods/site/RegularPages + returnType: page.Pages + signatures: [SITE.Sections] +--- + +Given this content structure: + +```text +content/ +├── books/ +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── film-1.md +│ └── film-2.md +└── _index.md +``` + +This template: + +```go-html-template +{{ range .Site.Sections }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +Is rendered to: + +```html +<h2><a href="/books/">Books</a></h2> +<h2><a href="/films/">Films</a></h2> +``` diff --git a/docs/content/en/methods/site/Sites.md b/docs/content/en/methods/site/Sites.md new file mode 100644 index 000000000..f7bafd3ed --- /dev/null +++ b/docs/content/en/methods/site/Sites.md @@ -0,0 +1,66 @@ +--- +title: Sites +description: Returns a collection of all Site objects, one for each language, ordered by language weight. +categories: [] +keywords: [] +action: + related: [] + returnType: page.Sites + signatures: [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 .Site.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 .Site.Sites.First }} + <a href="{{ .Home.Permalink }}">{{ .Title }}</a> +{{ end }} +``` + +This is equivalent to: + +```go-html-template +{{ with index .Site.Sites 0 }} + <a href="{{ .Home.Permalink }}">{{ .Title }}</a> +{{ end }} +``` diff --git a/docs/content/en/methods/site/Taxonomies.md b/docs/content/en/methods/site/Taxonomies.md new file mode 100644 index 000000000..72bfc75d5 --- /dev/null +++ b/docs/content/en/methods/site/Taxonomies.md @@ -0,0 +1,99 @@ +--- +title: Taxonomies +description: Returns a data structure containing the site's taxonomy objects, the terms within each taxonomy object, and the pages to which the terms are assigned. +categories: [] +keywords: [] +action: + related: [] + returnType: page.TaxonomyList + signatures: [SITE.Taxonomies] +--- + +Conceptually, the `Taxonomies` method on a `Site` object returns a data structure such as: + +{{< code-toggle >}} +taxonomy a: + - term 1: + - page 1 + - page 2 + - term 2: + - page 1 +taxonomy b: + - term 1: + - page 2 + - term 2: + - page 1 + - page 2 +{{< /code-toggle >}} + +For example, on a book review site you might create two taxonomies; one for genres and another for authors. + +With 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 +``` + +Conceptually, the taxonomies data structure looks like: + +{{< code-toggle >}} +genres: + - suspense: + - And Then There Were None + - Death on the Nile + - Jamaica Inn + - romance: + - Jamaica Inn + - Pride and Prejudice +authors: + - achristie: + - And Then There Were None + - Death on the Nile + - ddmaurier: + - Jamaica Inn + - jausten: + - Pride and Prejudice +{{< /code-toggle >}} + + +To list the "suspense" books: + +```go-html-template +<ul> + {{ range .Site.Taxonomies.genres.suspense }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/books/and-then-there-were-none/">And Then There Were None</a></li> + <li><a href="/books/death-on-the-nile/">Death on the Nile</a></li> + <li><a href="/books/jamaica-inn/">Jamaica Inn</a></li> +</ul> +``` + +{{% note %}} +Hugo's taxonomy system is powerful, allowing you to classify content and create relationships between pages. + +Please see the [taxonomies] section for a complete explanation and examples. + +[taxonomies]: content-management/taxonomies/ +{{% /note %}} diff --git a/docs/content/en/methods/site/Title.md b/docs/content/en/methods/site/Title.md new file mode 100644 index 000000000..a357286c1 --- /dev/null +++ b/docs/content/en/methods/site/Title.md @@ -0,0 +1,22 @@ +--- +title: Title +description: Returns the title as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.Title] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +title = 'My Documentation Site' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Title }} → My Documentation Site +``` diff --git a/docs/content/en/methods/site/_index.md b/docs/content/en/methods/site/_index.md new file mode 100644 index 000000000..39f66f308 --- /dev/null +++ b/docs/content/en/methods/site/_index.md @@ -0,0 +1,12 @@ +--- +title: Site methods +linkTitle: Site +description: Use these methods with Site objects. +categories: [] +keywords: [] +menu: + docs: + parent: methods +--- + +Use these methods with Site objects. A multilingual project will have two or more sites, one for each language. diff --git a/docs/content/en/methods/taxonomy/Alphabetical.md b/docs/content/en/methods/taxonomy/Alphabetical.md new file mode 100644 index 000000000..7845dbf3d --- /dev/null +++ b/docs/content/en/methods/taxonomy/Alphabetical.md @@ -0,0 +1,78 @@ +--- +title: Alphabetical +description: Returns an ordered taxonomy, sorted alphabetically by term. +categories: [] +keywords: [] +action: + related: + - methods/taxonomy/ByCount + returnType: page.OrderedTaxonomy + signatures: [TAXONOMY.Alphabetical] +toc: true +--- + +The `Alphabetical` method on a `Taxonomy` object returns an [ordered taxonomy], sorted alphabetically by [term]. + +While a `Taxonomy` object is a [map], an ordered taxonomy is a [slice], where each element is an object that contains the term and a slice of its [weighted pages]. + +{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}} + +## Get the ordered taxonomy + +Now that we have captured the “genres” Taxonomy object, let’s get the ordered taxonomy sorted alphabetically by term: + +```go-html-template +{{ $taxonomyObject.Alphabetical }} +``` + +To reverse the sort order: + +```go-html-template +{{ $taxonomyObject.Alphabetical.Reverse }} +``` + +To inspect the data structure: + +```go-html-template +<pre>{{ jsonify (dict "indent" " ") $taxonomyObject.Alphabetical }}</pre> +``` + +{{% include "methods/taxonomy/_common/ordered-taxonomy-element-methods.md" %}} + +## Example + +With this template: + +```go-html-template +{{ range $taxonomyObject.Alphabetical }} + <h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a> ({{ .Count }})</h2> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +Hugo renders: + +```html +<h2><a href="/genres/romance/">romance</a> (2)</h2> +<ul> + <li><a href="/books/jamaica-inn/">Jamaica inn</a></li> + <li><a href="/books/pride-and-prejudice/">Pride and prejudice</a></li> +</ul> +<h2><a href="/genres/suspense/">suspense</a> (3)</h2> +<ul> + <li><a href="/books/and-then-there-were-none/">And then there were none</a></li> + <li><a href="/books/death-on-the-nile/">Death on the nile</a></li> + <li><a href="/books/jamaica-inn/">Jamaica inn</a></li> +</ul> +``` + +[ordered taxonomy]: /getting-started/glossary/#ordered-taxonomy +[term]: /getting-started/glossary/#term +[map]: /getting-started/glossary/#map +[slice]: /getting-started/glossary/#slice +[term]: /getting-started/glossary/#term +[weighted pages]: /getting-started/glossary/#weighted-page diff --git a/docs/content/en/methods/taxonomy/ByCount.md b/docs/content/en/methods/taxonomy/ByCount.md new file mode 100644 index 000000000..40f58420a --- /dev/null +++ b/docs/content/en/methods/taxonomy/ByCount.md @@ -0,0 +1,78 @@ +--- +title: ByCount +description: Returns an ordered taxonomy, sorted by the number of pages associated with each term. +categories: [] +keywords: [] +action: + related: + - methods/taxonomy/Alphabetical + returnType: page.OrderedTaxonomy + signatures: [TAXONOMY.ByCount] +toc: true +--- + +The `ByCount` method on a `Taxonomy` object returns an [ordered taxonomy], sorted by the number of pages associated with each [term]. + +While a `Taxonomy` object is a [map], an ordered taxonomy is a [slice], where each element is an object that contains the term and a slice of its [weighted pages]. + +{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}} + +## Get the ordered taxonomy + +Now that we have captured the “genres” Taxonomy object, let’s get the ordered taxonomy sorted by the number of pages associated with each term: + +```go-html-template +{{ $taxonomyObject.ByCount }} +``` + +To reverse the sort order: + +```go-html-template +{{ $taxonomyObject.ByCount.Reverse }} +``` + +To inspect the data structure: + +```go-html-template +<pre>{{ jsonify (dict "indent" " ") $taxonomyObject.ByCount }}</pre> +``` + +{{% include "methods/taxonomy/_common/ordered-taxonomy-element-methods.md" %}} + +## Example + +With this template: + +```go-html-template +{{ range $taxonomyObject.ByCount }} + <h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a> ({{ .Count }})</h2> + <ul> + {{ range .Pages.ByTitle }} + <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +Hugo renders: + +```html +<h2><a href="/genres/suspense/">suspense</a> (3)</h2> +<ul> + <li><a href="/books/and-then-there-were-none/">And then there were none</a></li> + <li><a href="/books/death-on-the-nile/">Death on the nile</a></li> + <li><a href="/books/jamaica-inn/">Jamaica inn</a></li> +</ul> +<h2><a href="/genres/romance/">romance</a> (2)</h2> +<ul> + <li><a href="/books/jamaica-inn/">Jamaica inn</a></li> + <li><a href="/books/pride-and-prejudice/">Pride and prejudice</a></li> +</ul> +``` + +[ordered taxonomy]: /getting-started/glossary/#ordered-taxonomy +[term]: /getting-started/glossary/#term +[map]: /getting-started/glossary/#map +[slice]: /getting-started/glossary/#slice +[term]: /getting-started/glossary/#term +[weighted pages]: /getting-started/glossary/#weighted-page diff --git a/docs/content/en/methods/taxonomy/Count.md b/docs/content/en/methods/taxonomy/Count.md new file mode 100644 index 000000000..50f705ec9 --- /dev/null +++ b/docs/content/en/methods/taxonomy/Count.md @@ -0,0 +1,26 @@ +--- +title: Count +description: Returns the number of number of weighted pages to which the given term has been assigned. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [TAXONOMY.Count TERM] +toc: true +--- + +The `Count` method on a `Taxonomy` object returns the number of number of [weighted pages] to which the given [term] has been assigned. + +{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}} + +## Count the weighted pages + +Now that we have captured the "genres" `Taxonomy` object, let's count the number of weighted pages to which the "suspense" term has been assigned: + +```go-html-template +{{ $taxonomyObject.Count "suspense" }} → 3 +``` + +[weighted pages]: /getting-started/glossary/#weighted-page +[term]: /getting-started/glossary/#term diff --git a/docs/content/en/methods/taxonomy/Get.md b/docs/content/en/methods/taxonomy/Get.md new file mode 100644 index 000000000..3bac86f08 --- /dev/null +++ b/docs/content/en/methods/taxonomy/Get.md @@ -0,0 +1,72 @@ +--- +title: Get +description: Returns a slice of weighted pages to which the given term has been assigned. +categories: [] +keywords: [] +action: + related: [] + returnType: page.WeightedPages + signatures: [TAXONOMY.Get TERM] +toc: true +--- + +The `Get` method on a `Taxonomy` object returns a slice of [weighted pages] to which the given [term] has been assigned. + +{{% include "methods/taxonomy/_common/get-a-taxonomy-object.md" %}} + +## Get the weighted pages + +Now that we have captured the "genres" `Taxonomy` object, let's get the weighted pages to which the "suspense" term has been assigned: + +```go-html-template +{{ $weightedPages := $taxonomyObject.Get "suspense" }} +``` + +The above is equivalent to: + +```go-html-template +{{ $weightedPages := $taxonomyObject.suspense }} +``` + +But, if the term is not a valid [identifier], you cannot use the [chaining] syntax. For example, this will throw an error because the identifier contains a hyphen: + +```go-html-template +{{ $weightedPages := $taxonomyObject.my-genre }} +``` + +You could also use the [`index`] function, but the syntax is more verbose: + +```go-html-template +{{ $weightedPages := index $taxonomyObject "my-genre" }} +``` + +To inspect the data structure: + +```go-html-template +<pre>{{ jsonify (dict "indent" " ") $weightedPages }}</pre> +``` + +## Example + +With this template: + +```go-html-template +{{ $weightedPages := $taxonomyObject.Get "suspense" }} +{{ range $weightedPages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +Hugo renders: + +```html +<h2><a href="/books/jamaica-inn/">Jamaica inn</a></h2> +<h2><a href="/books/death-on-the-nile/">Death on the nile</a></h2> +<h2><a href="/books/and-then-there-were-none/">And then there were none</a></h2> +``` + +[chaining]: /getting-started/glossary/#chain +[`index`]: /functions/collections/indexfunction +[identifier]: /getting-started/glossary/#identifier +[term]: /getting-started/glossary/#term +[weighted pages]: /getting-started/glossary/#weighted-page diff --git a/docs/content/en/methods/taxonomy/_common/_index.md b/docs/content/en/methods/taxonomy/_common/_index.md new file mode 100644 index 000000000..47d5812fb --- /dev/null +++ b/docs/content/en/methods/taxonomy/_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/docs/content/en/methods/taxonomy/_common/get-a-taxonomy-object.md b/docs/content/en/methods/taxonomy/_common/get-a-taxonomy-object.md new file mode 100644 index 000000000..4c4fc42c9 --- /dev/null +++ b/docs/content/en/methods/taxonomy/_common/get-a-taxonomy-object.md @@ -0,0 +1,68 @@ +--- +# Do not remove front matter. +--- + +Before we can use a `Taxonomy` method, we need to capture a `Taxonomy` object. + +## Capture a taxonomy object + +Consider 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 +``` + +To capture the "genres" taxonomy object from within any template, use the [`Taxonomies`] method on a `Site` object. + +```go-html-template +{{ $taxonomyObject := .Site.Taxonomies.genres }} +``` + +To capture the "genres" taxonomy object when rendering its page with a taxonomy template, use the [`Terms`] method on the page's [`Data`] object: + +{{< code file=layouts/_default/taxonomy.html >}} +{{ $taxonomyObject := .Data.Terms }} +{{< /code >}} + +To inspect the data structure: + +```go-html-template +<pre>{{ jsonify (dict "indent" " ") $taxonomyObject }}</pre> +``` + +Although the [`Alphabetical`] and [`ByCount`] methods provide a better data structure for ranging through the taxonomy, you can render the weighted pages by term directly from the `Taxonomy` object: + +```go-html-template +{{ range $term, $weightedPages := $taxonomyObject }} + <h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a></h2> + <ul> + {{ range $weightedPages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> +{{ end }} +``` + +In the example above, the first anchor element is a link to the term page. + + +[`Alphabetical`]: /methods/taxonomy/alphabetical +[`ByCount`]: /methods/taxonomy/bycount + +[`data`]: /methods/page/data +[`terms`]: /methods/page/data/#in-a-taxonomy-template +[`taxonomies`]: /methods/site/taxonomies diff --git a/docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md b/docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md new file mode 100644 index 000000000..57c9e8e29 --- /dev/null +++ b/docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md @@ -0,0 +1,25 @@ +--- +# Do not remove front matter. +--- + +An ordered taxonomy is a slice, where each element is an object that contains the term and a slice of its weighted pages. + +Each element of the slice provides these methods: + +Count +: (`int`) Returns the number of pages to which the term is assigned. + +Page +: (`hugolib.pageState`) Returns the term's `Page` object, useful for linking to the term page. + +Pages +: (`page.Pages`) Returns a `Pages` object containing the `Page` objects to which the term is assigned, sorted by [taxonomic weight]. To sort or group, use any of the [methods] available to the `Pages` object. For example, sort by the last modification date. + +Term +: (`string`) Returns the term name. + +WeightedPages +: (`page.WeightedPages`) Returns a slice of weighted pages to which the term is assigned, sorted by [taxonomic weight]. The `Pages` method above is more flexible, allowing you to sort and group. + +[methods]: /methods/pages +[taxonomic weight]: /getting-started/glossary/#taxonomic-weight diff --git a/docs/content/en/methods/taxonomy/_index.md b/docs/content/en/methods/taxonomy/_index.md new file mode 100644 index 000000000..e7eb57834 --- /dev/null +++ b/docs/content/en/methods/taxonomy/_index.md @@ -0,0 +1,12 @@ +--- +title: Taxonomy methods +linkTitle: Taxonomy +description: Use these methods with Taxonomy objects. +keywords: [] +menu: + docs: + identifier: + parent: methods +--- + +Use these methods with Taxonomy objects. diff --git a/docs/content/en/methods/time/Add.md b/docs/content/en/methods/time/Add.md new file mode 100644 index 000000000..8fd755244 --- /dev/null +++ b/docs/content/en/methods/time/Add.md @@ -0,0 +1,23 @@ +--- +title: Add +description: Returns the given time plus the given duration. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + - functions/time/Duration + - functions/time/ParseDuration + returnType: time.Time + signatures: [TIME.Add DURATION] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} + +{{ $d1 = time.ParseDuration "3h20m10s" }} +{{ $d2 = time.ParseDuration "-3h20m10s" }} + +{{ $t.Add $d1 }} → 2023-01-28 03:05:08 -0800 PST +{{ $t.Add $d2 }} → 2023-01-27 20:24:48 -0800 PST +``` diff --git a/docs/content/en/methods/time/AddDate.md b/docs/content/en/methods/time/AddDate.md new file mode 100644 index 000000000..8537d6e25 --- /dev/null +++ b/docs/content/en/methods/time/AddDate.md @@ -0,0 +1,39 @@ +--- +title: AddDate +description: Returns the time corresponding to adding the given number of years, months, and days to the given time.Time value. +categories: [] +keywords: [] +action: + aliases: [] + related: [] + returnType: time.Time + signatures: [TIME.AddDate YEARS MONTHS DAYS] +aliases: [/functions/adddate] +--- + +```go-html-template +{{ $d := "2022-01-01" | time.AsTime }} + +{{ $d.AddDate 0 0 1 | time.Format "2006-01-02" }} → 2022-01-02 +{{ $d.AddDate 0 1 1 | time.Format "2006-01-02" }} → 2022-02-02 +{{ $d.AddDate 1 1 1 | time.Format "2006-01-02" }} → 2023-02-02 + +{{ $d.AddDate -1 -1 -1 | time.Format "2006-01-02" }} → 2020-11-30 +``` + +{{% note %}} +When adding months or years, Hugo normalizes the final `time.Time` value if the resulting day does not exist. For example, adding one month to 31 January produces 2 March or 3 March, depending on the year. + +See [this explanation](https://github.com/golang/go/issues/31145#issuecomment-479067967) from the Go team. +{{% /note %}} + +```go-html-template +{{ $d := "2023-01-31" | time.AsTime }} +{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} → 2023-03-03 + +{{ $d := "2024-01-31" | time.AsTime }} +{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} → 2024-03-02 + +{{ $d := "2024-02-29" | time.AsTime }} +{{ $d.AddDate 1 0 0 | time.Format "2006-01-02" }} → 2025-03-01 +``` diff --git a/docs/content/en/methods/time/After.md b/docs/content/en/methods/time/After.md new file mode 100644 index 000000000..0aeeb38d8 --- /dev/null +++ b/docs/content/en/methods/time/After.md @@ -0,0 +1,20 @@ +--- +title: After +description: Reports whether TIME1 is after TIME2. +categories: [] +keywords: [] +action: + related: + - methods/time/Before + - methods/time/After + - functions/time/AsTime + returnType: bool + signatures: [TIME1.After TIME2] +--- + +```go-html-template +{{ $t1 := time.AsTime "2023-01-01T17:00:00-08:00" }} +{{ $t2 := time.AsTime "2010-01-01T17:00:00-08:00" }} + +{{ $t1.After $t2 }} → true +``` diff --git a/docs/content/en/methods/time/Before.md b/docs/content/en/methods/time/Before.md new file mode 100644 index 000000000..c3d582860 --- /dev/null +++ b/docs/content/en/methods/time/Before.md @@ -0,0 +1,19 @@ +--- +title: Before +description: Reports whether TIME1 is before TIME2. +categories: [] +keywords: [] +action: + related: + - methods/time/After + - methods/time/Equal + - functions/time/AsTime + returnType: bool + signatures: [TIME1.Before TIME2] +--- + +```go-html-template +{{ $t1 := time.AsTime "2023-01-01T17:00:00-08:00" }} +{{ $t2 := time.AsTime "2030-01-01T17:00:00-08:00" }} + +{{ $t1.Before $t2 }} → true diff --git a/docs/content/en/methods/time/Day.md b/docs/content/en/methods/time/Day.md new file mode 100644 index 000000000..1173b8489 --- /dev/null +++ b/docs/content/en/methods/time/Day.md @@ -0,0 +1,21 @@ +--- +title: Day +description: Returns the day of the month of the given time.Time value. +categories: [] +keywords: [] +action: + related: + - methods/time/Year + - methods/time/Month + - methods/time/Hour + - methods/time/Minute + - methods/time/Second + - functions/time/AsTime + returnType: int + signatures: [TIME.Day] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Day }} → 27 +``` diff --git a/docs/content/en/methods/time/Equal.md b/docs/content/en/methods/time/Equal.md new file mode 100644 index 000000000..4d45a3ada --- /dev/null +++ b/docs/content/en/methods/time/Equal.md @@ -0,0 +1,20 @@ +--- +title: Equal +description: Reports whether TIME1 is equal to TIME2. +categories: [] +keywords: [] +action: + related: + - methods/time/After + - methods/time/Before + - functions/time/AsTime + returnType: bool + signatures: [TIME1.Equal TIME2] +--- + +```go-html-template +{{ $t1 := time.AsTime "2023-01-01T17:00:00-08:00" }} +{{ $t2 := time.AsTime "2023-01-01T20:00:00-05:00" }} + +{{ $t1.Equal $t2 }} → true +``` diff --git a/docs/content/en/methods/time/Format.md b/docs/content/en/methods/time/Format.md new file mode 100644 index 000000000..fc3e2635c --- /dev/null +++ b/docs/content/en/methods/time/Format.md @@ -0,0 +1,98 @@ +--- +title: Format +description: Returns a textual representation of the time.Time value formatted according to the layout string. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/time/AsTime + - methods/time/UTC + - methods/time/Local + returnType: string + signatures: [TIME.Format LAYOUT] +toc: true +aliases: [/methods/time/format] +--- + +```go-template +{{ $t := "2023-01-27T23:44:58-08:00" }} +{{ $t = time.AsTime $t }} +{{ $format := "2 Jan 2006" }} + +{{ $t.Format $format }} → 27 Jan 2023 +``` + +{{% note %}} +To [localize] the return value, use the [`time.Format`] function instead. + +[localize]: /getting-started/glossary/#localization +[`time.Format`]: /functions/time/format +{{% /note %}} + +Use the `Format` method with any `time.Time` value, including the four predefined front matter dates: + +```go-html-template +{{ $format := "2 Jan 2006" }} + +{{ .Date.Format $format }} +{{ .PublishDate.Format $format }} +{{ .ExpiryDate.Format $format }} +{{ .Lastmod.Format $format }} +``` + +{{% note %}} +Use the [`time.Format`] function to format string representations of dates, and to format raw TOML dates that exclude time and time zone offset. + +[`time.Format`]: /functions/time/format +{{% /note %}} + +## Layout string + +{{% include "functions/_common/time-layout-string.md" %}} + +## Examples + +Given this front matter: + +{{< code-toggle fm=true >}} +title = "About time" +date = 2023-01-27T23:44:58-08:00 +{{< /code-toggle >}} + +The examples below were rendered in the `America/Los_Angeles` time zone: + +Format string|Result +:--|:-- +`Monday, January 2, 2006`|`Friday, January 27, 2023` +`Mon Jan 2 2006`|`Fri Jan 27 2023` +`January 2006`|`January 2023` +`2006-01-02`|`2023-01-27` +`Monday`|`Friday` +`02 Jan 06 15:04 MST`|`27 Jan 23 23:44 PST` +`Mon, 02 Jan 2006 15:04:05 MST`|`Fri, 27 Jan 2023 23:44:58 PST` +`Mon, 02 Jan 2006 15:04:05 -0700`|`Fri, 27 Jan 2023 23:44:58 -0800` + +## UTC and local time + +Convert and format any `time.Time` value to either Coordinated Universal Time (UTC) or local time. + +```go-html-template +{{ $t := "2023-01-27T23:44:58-08:00" }} +{{ $t = time.AsTime $t }} +{{ $format := "2 Jan 2006 3:04:05 PM MST" }} + +{{ $t.UTC.Format $format }} → 28 Jan 2023 7:44:58 AM UTC +{{ $t.Local.Format $format }} → 27 Jan 2023 11:44:58 PM PST +``` + +## Ordinal representation + +Use the [`humanize`](/functions/inflect/humanize) function to render the day of the month as an ordinal number: + +```go-html-template +{{ $t := "2023-01-27T23:44:58-08:00" }} +{{ $t = time.AsTime $t }} + +{{ humanize $t.Day }} of {{ $t.Format "January 2006" }} → 27th of January 2023 +``` diff --git a/docs/content/en/methods/time/Hour.md b/docs/content/en/methods/time/Hour.md new file mode 100644 index 000000000..58ed00260 --- /dev/null +++ b/docs/content/en/methods/time/Hour.md @@ -0,0 +1,21 @@ +--- +title: Hour +description: Returns the hour within the day of the given time.Time value, in the range [0, 23]. +categories: [] +keywords: [] +action: + related: + - methods/time/Year + - methods/time/Month + - methods/time/Day + - methods/time/Minute + - methods/time/Second + - functions/time/AsTime + returnType: int + signatures: [TIME.Hour] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Hour }} → 23 +``` diff --git a/docs/content/en/methods/time/IsDST.md b/docs/content/en/methods/time/IsDST.md new file mode 100644 index 000000000..df2b84cae --- /dev/null +++ b/docs/content/en/methods/time/IsDST.md @@ -0,0 +1,19 @@ +--- +title: IsDST +description: Reports whether the given time.Time value is in Daylight Savings Time. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + returnType: bool + signatures: [TIME.IsDST] +--- + +```go-html-template +{{ $t1 := time.AsTime "2023-01-01T00:00:00-08:00" }} +{{ $t2 := time.AsTime "2023-07-01T00:00:00-07:00" }} + +{{ $t1.IsDST }} → false +{{ $t2.IsDST }} → true +``` diff --git a/docs/content/en/methods/time/IsZero.md b/docs/content/en/methods/time/IsZero.md new file mode 100644 index 000000000..2026f3b2e --- /dev/null +++ b/docs/content/en/methods/time/IsZero.md @@ -0,0 +1,19 @@ +--- +title: IsZero +description: Reports whether the given time.Time value represents the zero time instant, January 1, year 1, 00:00:00 UTC. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + returnType: bool + signatures: [TIME.IsZero] +--- + +````go-html-template +{{ $t1 := time.AsTime "2023-01-01T00:00:00-08:00" }} +{{ $t2 := time.AsTime "0001-01-01T00:00:00-00:00" }} + +{{ $t1.IsZero }} → false +{{ $t2.IsZero }} → true +``` diff --git a/docs/content/en/methods/time/Local.md b/docs/content/en/methods/time/Local.md new file mode 100644 index 000000000..bd40e3a44 --- /dev/null +++ b/docs/content/en/methods/time/Local.md @@ -0,0 +1,17 @@ +--- +title: Local +description: Returns the given time.Time value with the location set to local time. +categories: [] +keywords: [] +action: + related: + - methods/time/UTC + - functions/time/AsTime + returnType: time.Time + signatures: [TIME.Local] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-28T07:44:58+00:00" }} +{{ $t.Local }} → 2023-01-27 23:44:58 -0800 PST +``` diff --git a/docs/content/en/methods/time/Minute.md b/docs/content/en/methods/time/Minute.md new file mode 100644 index 000000000..d482fab5d --- /dev/null +++ b/docs/content/en/methods/time/Minute.md @@ -0,0 +1,21 @@ +--- +title: Minute +description: Returns the minute offset within the hour of the given time.Time value, in the range [0, 59]. +categories: [] +keywords: [] +action: + related: + - methods/time/Year + - methods/time/Month + - methods/time/Day + - methods/time/Hour + - methods/time/Second + - functions/time/AsTime + returnType: int + signatures: [TIME.Minute] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Minute }} → 44 +``` diff --git a/docs/content/en/methods/time/Month.md b/docs/content/en/methods/time/Month.md new file mode 100644 index 000000000..0a01d1a70 --- /dev/null +++ b/docs/content/en/methods/time/Month.md @@ -0,0 +1,30 @@ +--- +title: Month +description: Returns the month of the year of the given time.Time value. +categories: [] +keywords: [] +action: + related: + - methods/time/Year + - methods/time/Day + - methods/time/Hour + - methods/time/Minute + - methods/time/Second + - functions/time/AsTime + returnType: time.Month + signatures: [TIME.Month] +--- + +To convert the `time.Month` value to a string: + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Month.String }} → January +``` + +To convert the `time.Month` value to an integer. + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Month | int }} → 1 +``` diff --git a/docs/content/en/methods/time/Nanosecond.md b/docs/content/en/methods/time/Nanosecond.md new file mode 100644 index 000000000..606143139 --- /dev/null +++ b/docs/content/en/methods/time/Nanosecond.md @@ -0,0 +1,16 @@ +--- +title: Nanosecond +description: Returns the nanosecond offset within the second of the given time.Time value, in the range [0, 999999999]. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + returnType: int + signatures: [TIME.Nanosecond] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Nanosecond }} → 0 +``` diff --git a/docs/content/en/methods/time/Second.md b/docs/content/en/methods/time/Second.md new file mode 100644 index 000000000..e326c64bc --- /dev/null +++ b/docs/content/en/methods/time/Second.md @@ -0,0 +1,21 @@ +--- +title: Second +description: Returns the second offset within the minute of the given time.Time value, in the range [0, 59]. +categories: [] +keywords: [] +action: + related: + - methods/time/Year + - methods/time/Month + - methods/time/Day + - methods/time/Hour + - methods/time/Minute + - functions/time/AsTime + returnType: int + signatures: [TIME.Second] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Second }} → 58 +``` diff --git a/docs/content/en/methods/time/Sub.md b/docs/content/en/methods/time/Sub.md new file mode 100644 index 000000000..9678365eb --- /dev/null +++ b/docs/content/en/methods/time/Sub.md @@ -0,0 +1,18 @@ +--- +title: Sub +description: Returns the duration computed by subtracting TIME2 from TIME1. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + returnType: time.Duration + signatures: [TIME1.Sub TIME2] +--- + +```go-html-template +{{ $t1 := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t2 := time.AsTime "2023-01-26T22:34:38-08:00" }} + +{{ $t1.Sub $t2 }} → 25h10m20s +``` diff --git a/docs/content/en/methods/time/UTC.md b/docs/content/en/methods/time/UTC.md new file mode 100644 index 000000000..6fd7b526d --- /dev/null +++ b/docs/content/en/methods/time/UTC.md @@ -0,0 +1,16 @@ +--- +title: UTC +description: Returns the given time.Time value with the location set to UTC. +categories: [] +keywords: [] +action: + related: + - methods/time/Local + - functions/time/AsTime + returnType: time.Time + signatures: [TIME.UTC] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.UTC }} → 2023-01-28 07:44:58 +0000 UTC diff --git a/docs/content/en/methods/time/Unix.md b/docs/content/en/methods/time/Unix.md new file mode 100644 index 000000000..fcfc661fe --- /dev/null +++ b/docs/content/en/methods/time/Unix.md @@ -0,0 +1,21 @@ +--- +title: Unix +description: Returns the given time.Time value expressed as the number of seconds elapsed since January 1, 1970 UTC. +categories: [] +action: + related: + - methods/time/UnixMilli + - methods/time/UnixMicro + - methods/time/UnixNano + - functions/time/AsTime + returnType: int64 + signatures: [TIME.Unix] +aliases: [/functions/unix] +--- + +See [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Unix }} → 1674891898 +``` diff --git a/docs/content/en/methods/time/UnixMicro.md b/docs/content/en/methods/time/UnixMicro.md new file mode 100644 index 000000000..150497cd3 --- /dev/null +++ b/docs/content/en/methods/time/UnixMicro.md @@ -0,0 +1,21 @@ +--- +title: UnixMicro +description: Returns the given time.Time value expressed as the number of microseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +action: + related: + - methods/time/Unix + - methods/time/UnixMilli + - methods/time/UnixNano + - functions/time/AsTime + returnType: int64 + signatures: [TIME.UnixMicro] +--- + +See [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.UnixMicro }} → 1674891898000000 +``` diff --git a/docs/content/en/methods/time/UnixMilli.md b/docs/content/en/methods/time/UnixMilli.md new file mode 100644 index 000000000..e5e90ba25 --- /dev/null +++ b/docs/content/en/methods/time/UnixMilli.md @@ -0,0 +1,21 @@ +--- +title: UnixMilli +description: Returns the given time.Time value expressed as the number of milliseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +action: + related: + - methods/time/Unix + - methods/time/UnixMicro + - methods/time/UnixNano + - functions/time/AsTime + returnType: int64 + signatures: [TIME.UnixMilli] +--- + +See [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.UnixMilli }} → 1674891898000 +``` diff --git a/docs/content/en/methods/time/UnixNano.md b/docs/content/en/methods/time/UnixNano.md new file mode 100644 index 000000000..63db320a3 --- /dev/null +++ b/docs/content/en/methods/time/UnixNano.md @@ -0,0 +1,21 @@ +--- +title: UnixNano +description: Returns the given time.Time value expressed as the number of nanoseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +action: + related: + - methods/time/Unix + - methods/time/UnixMilli + - methods/time/UnixMicro + - functions/time/AsTime + returnType: int64 + signatures: [TIME.UnixNano] +--- + +See [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.UnixNano }} → 1674891898000000000 +``` diff --git a/docs/content/en/methods/time/Weekday.md b/docs/content/en/methods/time/Weekday.md new file mode 100644 index 000000000..b2a95fe9c --- /dev/null +++ b/docs/content/en/methods/time/Weekday.md @@ -0,0 +1,24 @@ +--- +title: Weekday +description: Returns the day of the week of the given time.Time value. +categories: [] +keywords: [] +action: + related: + - functions/time/AsTime + returnType: time.Weekday + signatures: [TIME.Weekday] +--- + +To convert the `time.Weekday` value to a string: + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Weekday.String }} → Friday +``` + +To convert the `time.Weekday` value to an integer. + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Weekday | int }} → 5 diff --git a/docs/content/en/methods/time/Year.md b/docs/content/en/methods/time/Year.md new file mode 100644 index 000000000..b046896f4 --- /dev/null +++ b/docs/content/en/methods/time/Year.md @@ -0,0 +1,21 @@ +--- +title: Year +description: Returns the year of the given time.Time value. +categories: [] +keywords: [] +action: + related: + - methods/time/Month + - methods/time/Day + - methods/time/Hour + - methods/time/Minute + - methods/time/Second + - functions/time/AsTime + returnType: int + signatures: [TIME.Year] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.Year }} → 2023 +``` diff --git a/docs/content/en/methods/time/YearDay.md b/docs/content/en/methods/time/YearDay.md new file mode 100644 index 000000000..40d7d6aab --- /dev/null +++ b/docs/content/en/methods/time/YearDay.md @@ -0,0 +1,15 @@ +--- +title: YearDay +description: Returns the day of the year of the given time.Time value, in the range [1, 365] for non-leap years, and [1,366] in leap years. +categories: [] +keywords: [] +action: + related: [] + returnType: int + signatures: [TIME.YearDay] +--- + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $t.YearDay }} → 27 +``` diff --git a/docs/content/en/methods/time/_index.md b/docs/content/en/methods/time/_index.md new file mode 100644 index 000000000..81d4690e0 --- /dev/null +++ b/docs/content/en/methods/time/_index.md @@ -0,0 +1,13 @@ +--- +title: Time methods +linkTitle: Time +description: Use these methods with time.Time values. +categories: [] +keywords: [] +menu: + docs: + identifier: time-methods + parent: methods +--- + +Use these methods with time.Time values. |