diff options
Diffstat (limited to 'docs/content/en/methods')
261 files changed, 10712 insertions, 0 deletions
diff --git a/docs/content/en/methods/_index.md b/docs/content/en/methods/_index.md new file mode 100644 index 000000000..39f2b6146 --- /dev/null +++ b/docs/content/en/methods/_index.md @@ -0,0 +1,8 @@ +--- +title: Methods +description: Use these methods within your templates. +categories: [] +keywords: [] +weight: 10 +aliases: ['/variables/'] +--- diff --git a/docs/content/en/methods/duration/Abs.md b/docs/content/en/methods/duration/Abs.md new file mode 100644 index 000000000..2e85797ea --- /dev/null +++ b/docs/content/en/methods/duration/Abs.md @@ -0,0 +1,15 @@ +--- +title: Abs +description: Returns the absolute value of the given time.Duration value. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..23655510e --- /dev/null +++ b/docs/content/en/methods/duration/Hours.md @@ -0,0 +1,15 @@ +--- +title: Hours +description: Returns the time.Duration value as a floating point number of hours. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..c090316d0 --- /dev/null +++ b/docs/content/en/methods/duration/Microseconds.md @@ -0,0 +1,15 @@ +--- +title: Microseconds +description: Returns the time.Duration value as an integer microsecond count. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..288f3695a --- /dev/null +++ b/docs/content/en/methods/duration/Milliseconds.md @@ -0,0 +1,15 @@ +--- +title: Milliseconds +description: Returns the time.Duration value as an integer millisecond count. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..aec904fa7 --- /dev/null +++ b/docs/content/en/methods/duration/Minutes.md @@ -0,0 +1,15 @@ +--- +title: Minutes +description: Returns the time.Duration value as a floating point number of minutes. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..fd1b9e496 --- /dev/null +++ b/docs/content/en/methods/duration/Nanoseconds.md @@ -0,0 +1,15 @@ +--- +title: Nanoseconds +description: Returns the time.Duration value as an integer nanosecond count. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..dfd06253f --- /dev/null +++ b/docs/content/en/methods/duration/Round.md @@ -0,0 +1,18 @@ +--- +title: Round +description: Returns the result of rounding DURATION1 to the nearest multiple of DURATION2. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..8b6d060b9 --- /dev/null +++ b/docs/content/en/methods/duration/Seconds.md @@ -0,0 +1,15 @@ +--- +title: Seconds +description: Returns the time.Duration value as a floating point number of seconds. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..5a785a77a --- /dev/null +++ b/docs/content/en/methods/duration/Truncate.md @@ -0,0 +1,18 @@ +--- +title: Truncate +description: Returns the result of rounding DURATION1 toward zero to a multiple of DURATION2. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..aeb113820 --- /dev/null +++ b/docs/content/en/methods/duration/_index.md @@ -0,0 +1,7 @@ +--- +title: Duration methods +linkTitle: Duration +description: Use these methods with time.Duration values. +categories: [] +keywords: [] +--- 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..ecad415fa --- /dev/null +++ b/docs/content/en/methods/menu-entry/Children.md @@ -0,0 +1,66 @@ +--- +title: Children +description: Returns a collection of child menu entries, if any, under the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: navigation.Menu + signatures: [MENUENTRY.Children] +--- + +Use the `Children` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menus.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..03e6cb672 --- /dev/null +++ b/docs/content/en/methods/menu-entry/HasChildren.md @@ -0,0 +1,66 @@ +--- +title: HasChildren +description: Reports whether the given menu entry has child menu entries. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [MENUENTRY.HasChildren] +--- + +Use the `HasChildren` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menus.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..809624459 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Identifier.md @@ -0,0 +1,41 @@ +--- +title: Identifier +description: Returns the `identifier` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. + +{{< code-toggle file=hugo >}} +[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + +[[menus.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. + +[automatically]: /content-management/menus/#define-automatically 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..d614a5a87 --- /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: [] +params: + functions_and_methods: + 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 >}} +[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + +[[menus.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..074911eeb --- /dev/null +++ b/docs/content/en/methods/menu-entry/Menu.md @@ -0,0 +1,22 @@ +--- +title: Menu +description: Returns the identifier of the menu that contains the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/#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..706d0f8c8 --- /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: [] +params: + functions_and_methods: + 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 of the given menu entry. If the `name` is not defined, and the menu entry resolves to a page, the `Name` returns the page [`LinkTitle`], falling back 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..489ee7acc --- /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: [] +params: + functions_and_methods: + returnType: page.Page + 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 >}} +[[menus.main]] +pageRef = '/about' +weight = 10 + +[[menus.main]] +pageRef = '/contact' +weight = 20 + +[[menus.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/#page-references +[methods]: /methods/page/ diff --git a/docs/content/en/methods/menu-entry/PageRef.md b/docs/content/en/methods/menu-entry/PageRef.md new file mode 100644 index 000000000..979879b03 --- /dev/null +++ b/docs/content/en/methods/menu-entry/PageRef.md @@ -0,0 +1,109 @@ +--- +title: PageRef +description: Returns the `pageRef` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [MENUENTRY.PageRef] +--- + +The use case for this method is rare. + +In almost also scenarios you should use the [`URL`] method instead. + +## Explanation + +If you specify a `pageRef` property when [defining a menu entry] in your site configuration, Hugo looks for a matching page when rendering the entry. + +If a matching page is found: + +- The [`URL`] method returns the page's relative permalink +- The [`Page`] method returns the corresponding `Page` object +- The [`HasMenuCurrent`] and [`IsMenuCurrent`] methods on a `Page` object return the expected values + +If a matching page is not found: + +- The [`URL`] method returns the entry's `url` property if set, else an empty string +- The [`Page`] method returns nil +- The [`HasMenuCurrent`] and [`IsMenuCurrent`] methods on a `Page` object return `false` + +> [!note] +> In almost also scenarios you should use the [`URL`] method instead. + +## Example + +This example is contrived. + +> [!note] +> In almost also scenarios you should use the [`URL`] method instead. + +Consider this content structure: + +```text +content/ +├── products.md +└── _index.md +``` + +And this menu definition: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Products' +pageRef = '/products' +weight = 10 +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +With this template code: + +```go-html-template {file="layouts/partials/menu.html"} +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo render this HTML: + +```html +<ul> + <li><a href="/products/">Products</a></li> + <li><a href="">Services</a></li> +</ul> +``` + +In the above note that the `href` attribute of the second `anchor` element is blank because Hugo was unable to find the "services" page. + +With this template code: + +```go-html-template {file="layouts/partials/menu.html"} +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ or .URL .PageRef }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this HTML: + +```html +<ul> + <li><a href="/products/">Products</a></li> + <li><a href="/services">Services</a></li> +</ul> +``` + +In the above note that Hugo populates the `href` attribute of the second `anchor` element with the `pageRef` property as defined in the site configuration because the template code falls back to the `PageRef` method. + +[`HasMenuCurrent`]: /methods/page/hasmenucurrent/ +[`IsMenuCurrent`]: /methods/page/ismenucurrent/ +[`Page`]: /methods/menu-entry/page/ +[`URL`]: /methods/menu-entry/url/ +[defining a menu entry]: /content-management/menus/#define-in-site-configuration 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..20c4f7fc7 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Params.md @@ -0,0 +1,61 @@ +--- +title: Params +description: Returns the `params` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 >}} +[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 10 + +[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 20 + +[[menus.main]] +name = 'Hugo' +url = 'https://gohugo.io' +weight = 30 +[menus.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/#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..7c617527b --- /dev/null +++ b/docs/content/en/methods/menu-entry/Parent.md @@ -0,0 +1,50 @@ +--- +title: Parent +description: Returns the `parent` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [MENUENTRY.Parent] +--- + +With this menu definition: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + +[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + +[[menus.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..2da8c38d8 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Post.md @@ -0,0 +1,12 @@ +--- +title: Post +description: Returns the `post` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [MENUENTRY.Post] +--- + +{{% include "/_common/menu-entries/pre-and-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..19af243e7 --- /dev/null +++ b/docs/content/en/methods/menu-entry/Pre.md @@ -0,0 +1,12 @@ +--- +title: Pre +description: Returns the `pre` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [MENUENTRY.Pre] +--- + +{{% include "/_common/menu-entries/pre-and-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..526132d7c --- /dev/null +++ b/docs/content/en/methods/menu-entry/Title.md @@ -0,0 +1,22 @@ +--- +title: Title +description: Returns the `title` property of the given menu entry. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [MENUENTRY.Title] +--- + +The `Title` method returns the `title` property of the given menu entry. If the `title` is not defined, and the menu entry resolves to a page, the `Title` returns the page [`Title`]. + +[`Title`]: /methods/page/title/ + +```go-html-template +<ul> + {{ range .Site.Menus.main }} + <li><a href="{{ .URL }}" title="{{ .Title }}>{{ .Name }}</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..e29a6f058 --- /dev/null +++ b/docs/content/en/methods/menu-entry/URL.md @@ -0,0 +1,22 @@ +--- +title: URL +description: Returns the relative permalink of the page associated with the given menu entry, else its `url` property. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..b96e2cc87 --- /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: [] +params: + functions_and_methods: + 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/_index.md b/docs/content/en/methods/menu-entry/_index.md new file mode 100644 index 000000000..129e9bcdc --- /dev/null +++ b/docs/content/en/methods/menu-entry/_index.md @@ -0,0 +1,7 @@ +--- +title: Menu entry methods +linkTitle: Menu entry +description: Use these methods in your menu templates. +categories: [] +keywords: [] +--- diff --git a/docs/content/en/methods/menu/ByName.md b/docs/content/en/methods/menu/ByName.md new file mode 100644 index 000000000..d98a4aced --- /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: [] +params: + functions_and_methods: + 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 >}} +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menus.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..013d37e13 --- /dev/null +++ b/docs/content/en/methods/menu/ByWeight.md @@ -0,0 +1,71 @@ +--- +title: ByWeight +description: Returns the given menu with its entries sorted by weight, then by name, then by identifier. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: navigation.Menu + signatures: [MENU.ByWeight] +--- + +The `ByWeight` method returns the given menu with its entries sorted by [`weight`](g), then by `name`, then by `identifier`. This is the default sort order. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} +[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 20 + +[[menus.main]] +identifier = 'services' +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menus.main]] +identifier = 'contact' +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by `weight`, then by `name`, then by `identifier`: + +```go-html-template +<ul> + {{ range .Site.Menus.main.ByWeight }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +Hugo renders this to: + +```html +<ul> + <li><a href="/services/">Services</a></li> + <li><a href="/about/">About</a></li> + <li><a href="/contact">Contact</a></li> +</ul> +``` + +> [!note] +> In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables. + +You can also sort menu entries using the [`sort`] function. For example, to sort by `weight` in descending order: + +```go-html-template +<ul> + {{ range sort .Site.Menus.main "Weight" "desc" }} + <li><a href="{{ .URL }}">{{ .Name }}</a></li> + {{ end }} +</ul> +``` + +When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. + +[`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..005fef144 --- /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: [] +params: + functions_and_methods: + 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 >}} +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menus.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..1ee31aa51 --- /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: [] +params: + functions_and_methods: + 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 >}} +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + +[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + +[[menus.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..41084fdba --- /dev/null +++ b/docs/content/en/methods/menu/_index.md @@ -0,0 +1,7 @@ +--- +title: Menu methods +linkTitle: Menu +description: Use these methods when ranging through menu entries. +categories: [] +keywords: [] +--- diff --git a/docs/content/en/methods/page/Aliases.md b/docs/content/en/methods/page/Aliases.md new file mode 100644 index 000000000..775404bd3 --- /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: [] +params: + functions_and_methods: + 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..62117b429 --- /dev/null +++ b/docs/content/en/methods/page/AllTranslations.md @@ -0,0 +1,88 @@ +--- +title: AllTranslations +description: Returns all translations of the given page, including the current language. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 . }} + <li> + <a href="{{ .RelPermalink }}" hreflang="{{ .Language.LanguageCode }}">{{ .LinkTitle }} ({{ or .Language.LanguageName .Language.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/" hreflang="en-US">Book 1 (English)</a></li> + <li><a href="/de/books/book-1/" hreflang="de-DE">Book 1 (Deutsch)</a></li> + <li><a href="/fr/books/book-1/" hreflang="fr-FR">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/" hreflang="en-US">Book 1 (English)</a></li> + <li><a href="/de/books/book-1/" hreflang="de-DE">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..c4075d010 --- /dev/null +++ b/docs/content/en/methods/page/AlternativeOutputFormats.md @@ -0,0 +1,42 @@ +--- +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: [] +params: + functions_and_methods: + returnType: page.OutputFormats + signatures: [PAGE.AlternativeOutputFormats] +--- + +{{% glossary-term "output format" %}} + +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](/configuration/output-formats/). + +## Methods + +{{% include "/_common/methods/page/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..d8275cf76 --- /dev/null +++ b/docs/content/en/methods/page/Ancestors.md @@ -0,0 +1,76 @@ +--- +title: Ancestors +description: Returns a collection of Page objects, one for each ancestor section of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.Ancestors] +--- + +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..e919511da --- /dev/null +++ b/docs/content/en/methods/page/BundleType.md @@ -0,0 +1,33 @@ +--- +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: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.BundleType] +--- + +A page bundle is a directory that encapsulates both content and associated [resources](g). There are two types of page bundles: [leaf bundles](g) and [branch bundles](g). 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 }} +``` diff --git a/docs/content/en/methods/page/CodeOwners.md b/docs/content/en/methods/page/CodeOwners.md new file mode 100644 index 000000000..00afa7549 --- /dev/null +++ b/docs/content/en/methods/page/CodeOwners.md @@ -0,0 +1,65 @@ +--- +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: [] +params: + functions_and_methods: + 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 +my-project/ +├── 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..21348ebe6 --- /dev/null +++ b/docs/content/en/methods/page/Content.md @@ -0,0 +1,16 @@ +--- +title: Content +description: Returns the rendered content of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.Content] +--- + +The `Content` method on a `Page` object renders Markdown and shortcodes to HTML. + +```go-html-template +{{ .Content }} +``` diff --git a/docs/content/en/methods/page/ContentWithoutSummary.md b/docs/content/en/methods/page/ContentWithoutSummary.md new file mode 100644 index 000000000..4923b1197 --- /dev/null +++ b/docs/content/en/methods/page/ContentWithoutSummary.md @@ -0,0 +1,22 @@ +--- +title: ContentWithoutSummary +description: Returns the rendered content of the given page, excluding the content summary. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.ContentWithoutSummary] +--- + +{{< new-in 0.134.0 />}} + +Applicable when using manual or automatic [content summaries], the `ContentWithoutSummary` method on a `Page` object renders Markdown and shortcodes to HTML, excluding the content summary from the result. + +[content summaries]: /content-management/summaries/#manual-summary + +```go-html-template +{{ .ContentWithoutSummary }} +``` + +The `ContentWithoutSummary` method returns the same as `Content` if you define the content summary in front matter. diff --git a/docs/content/en/methods/page/CurrentSection.md b/docs/content/en/methods/page/CurrentSection.md new file mode 100644 index 000000000..93457f13f --- /dev/null +++ b/docs/content/en/methods/page/CurrentSection.md @@ -0,0 +1,48 @@ +--- +title: CurrentSection +description: Returns the Page object of the section in which the given page resides. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.CurrentSection] +--- + +{{% glossary-term section %}} + +> [!note] +> The current section of a [section page](g), [taxonomy page](g), [term page](g), or the home page, is itself. + +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..ae0bdc57f --- /dev/null +++ b/docs/content/en/methods/page/Data.md @@ -0,0 +1,101 @@ +--- +title: Data +description: Returns a unique data object for each page kind. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Data + signatures: [PAGE.Data] +--- + +The `Data` method on a `Page` object returns a unique data object for each [page kind](g). + +> [!note] +> The `Data` method is only useful within [taxonomy](g) and [term](g) templates. +> +> Themes that are not actively maintained may still use `.Data.Pages` in list templates. Although that syntax remains functional, use one of these methods instead: [`Pages`], [`RegularPages`], or [`RegularPagesRecursive`] + +The 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](g) 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. + +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]. + +[`Pages`]: /methods/page/pages/ +[`RegularPages`]: /methods/page/regularpages/ +[`RegularPagesRecursive`]: /methods/page/regularpagesrecursive/ +[taxonomy methods]: /methods/taxonomy/ +[taxonomy templates]: /templates/types/#taxonomy +[term templates]: /templates/types/#term diff --git a/docs/content/en/methods/page/Date.md b/docs/content/en/methods/page/Date.md new file mode 100644 index 000000000..b6c2042c2 --- /dev/null +++ b/docs/content/en/methods/page/Date.md @@ -0,0 +1,34 @@ +--- +title: Date +description: Returns the date of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]. + +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]: /configuration/front-matter/#dates +[details]: /configuration/front-matter/#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..5287aa699 --- /dev/null +++ b/docs/content/en/methods/page/Description.md @@ -0,0 +1,27 @@ +--- +title: Description +description: Returns the description of the given page as defined in front matter. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Description] +--- + +Conceptually different from 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 >}} + +```go-html-template {file="layouts/_default/baseof.html"} +<head> + ... + <meta name="description" content="{{ .Description }}"> + ... +</head> +``` + +[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..482a370bf --- /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: [] +params: + functions_and_methods: + 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..4947a4bfa --- /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: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE1.Eq PAGE2] +--- + +In this contrived example from a single 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..a72155c33 --- /dev/null +++ b/docs/content/en/methods/page/ExpiryDate.md @@ -0,0 +1,32 @@ +--- +title: ExpiryDate +description: Returns the expiry date of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..2af60a719 --- /dev/null +++ b/docs/content/en/methods/page/File.md @@ -0,0 +1,194 @@ +--- +title: File +description: For pages backed by a file, returns file information for the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: hugolib.fileInfo + signatures: [PAGE.File] +--- + +By default, not all pages are backed by a file, including top-level [section pages](g), [taxonomy pages](g), and [term pages](g). 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-slevel section page + ├── book-1.md + └── book-2.md +``` + +> [!note] +> Code defensively by verifying file existence as shown in the examples below. + +## Methods + +> [!note] +> The path separators (slash or backslash) in `Path`, `Dir`, and `Filename` depend on the operating system. + +### 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 }} +``` + +### IsContentAdapter + +{{< new-in 0.126.0 />}} + +(`bool`) Reports whether the file is a [content adapter]. + +```go-html-template +{{ with .File }} + {{ .IsContentAdapter }} +{{ 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 }} +``` + +### Section + +(`string`) The name of the top-level section in which the file resides. + +```go-html-template +{{ with .File }} + {{ .Section }} +{{ 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/... +IsContentAdapter|false|false|false +LogicalName|a.en.md|index.en.md|_index.en.md +Path|news/a.en.md|news/b/index.en.md|news/_index.en.md +Section|news|news|news +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 an error if you attempt to access a `.File` property. To code defensively, first check for file existence: + +```go-html-template +{{ with .File }} + {{ .ContentBaseName }} +{{ end }} +``` + +[content adapter]: /content-management/content-adapters/ diff --git a/docs/content/en/methods/page/FirstSection.md b/docs/content/en/methods/page/FirstSection.md new file mode 100644 index 000000000..73ddd2d7b --- /dev/null +++ b/docs/content/en/methods/page/FirstSection.md @@ -0,0 +1,48 @@ +--- +title: FirstSection +description: Returns the Page object of the top-level section of which the given page is a descendant. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.FirstSection] +--- + +{{% glossary-term section %}} + +> [!note] +> When called on the home page, the `FirstSection` method returns the `Page` object of the home page itself. + +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..2c0460def --- /dev/null +++ b/docs/content/en/methods/page/Fragments.md @@ -0,0 +1,109 @@ +--- +title: Fragments +description: Returns a data structure of the fragments in the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: tableofcontents.Fragments + signatures: [PAGE.Fragments] +--- + +In a URL, whether absolute or relative, the [fragment](g) 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](g) 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](g) the `Fragments.Map` data structure. + +## Methods + +### Headings + +(`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`, `Level`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +<pre>{{ debug.Dump .Fragments.Headings }}</pre> +``` + +### HeadingsMap + +(`map`) A nested map of all headings on the page. Each map contains the following keys: `ID`, `Level`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +<pre>{{ debug.Dump .Fragments.HeadingsMap }}</pre> +``` + +### Identifiers + +(`slice`) A slice containing the `id` attribute of each heading on the page. If so configured, will also contain the `id` attribute of each description term (i.e., `dt` element) on the page. + +See [configure Markup](/configuration/markup/#parserautodefinitiontermid). + +To inspect the data structure: + +```go-html-template +<pre>{{ debug.Dump .Fragments.Identifiers }}</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](g). + +```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 [standard notation]. If you use [Markdown notation] the rendered shortcode is included in the creation of the fragments map, resulting in a circular loop. + +[`TableOfContents`]: /methods/page/tableofcontents/ +[ATX]: https://spec.commonmark.org/0.30/#atx-headings +[Markdown notation]: /content-management/shortcodes/#notation +[setext]: https://spec.commonmark.org/0.30/#setext-headings +[standard notation]: /content-management/shortcodes/#notation +[table of contents]: /methods/page/tableofcontents/ diff --git a/docs/content/en/methods/page/FuzzyWordCount.md b/docs/content/en/methods/page/FuzzyWordCount.md new file mode 100644 index 000000000..815a07402 --- /dev/null +++ b/docs/content/en/methods/page/FuzzyWordCount.md @@ -0,0 +1,18 @@ +--- +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: [] +params: + functions_and_methods: + 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..02f6888e0 --- /dev/null +++ b/docs/content/en/methods/page/GetPage.md @@ -0,0 +1,64 @@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + 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-lisa.md: + +```go-html-template {file="layouts/works/single.html"} +{{ 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..53b996fc5 --- /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: [] +params: + functions_and_methods: + 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..5fde05b07 --- /dev/null +++ b/docs/content/en/methods/page/GitInfo.md @@ -0,0 +1,151 @@ +--- +title: GitInfo +description: Returns Git information related to the last commit of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: source.GitInfo + signatures: [PAGE.GitInfo] +--- + +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. + +## 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 `enableGitInfo` 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]. + +## 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 }} → jsmith@example.org +{{ end }} +``` + +### AuthorName + +(`string`) The author's name, respecting [gitmailmap]. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorName }} → John Smith +{{ end }} +``` + +### CommitDate + +(`time.Time`) The commit date. + +```go-html-template +{{ with .GitInfo }} + {{ .CommitDate.Format "2006-01-02" }} → 2023-10-09 +{{ 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 }} +``` + +### Body + +(`string`) The commit message body. + +```go-html-template +{{ with .GitInfo }} + {{ .Body }} → - Two new pages added. +{{ 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]. + +## Hosting considerations + +When hosting your site in a [CI/CD](g) 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 only perform shallow clones. + +Hosting service | Default clone depth | Configurable +:-- | :-- | :-- +AWS Amplify | Deep | N/A +Cloudflare Pages | Shallow | Yes [^1] +DigitalOcean App Platform | Deep | N/A +GitHub Pages | Shallow | Yes [^2] +GitLab Pages | Shallow | Yes [^3] +Netlify | Deep | N/A +Render | Shallow | No +Vercel | Shallow | No + +[^1]: To configure a Cloudflare Pages site for deep cloning, run `git fetch --unshallow` before building the site. + +[^2]: 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](/host-and-deploy/host-on-github-pages/#procedure). + +[^3]: 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](/host-and-deploy/host-on-gitlab-pages/#configure-gitlab-cicd). + +[details]: /configuration/front-matter/#dates +[gitmailmap]: https://git-scm.com/docs/gitmailmap +[site configuration]: /configuration/front-matter/ diff --git a/docs/content/en/methods/page/HasMenuCurrent.md b/docs/content/en/methods/page/HasMenuCurrent.md new file mode 100644 index 000000000..207882167 --- /dev/null +++ b/docs/content/en/methods/page/HasMenuCurrent.md @@ -0,0 +1,33 @@ +--- +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: [] +params: + functions_and_methods: + 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. + +> [!note] +> When using this method you must either define the menu entry in front matter, or specify a `pageRef` property when defining the menu entry in your site configuration. + +[menu templates]: /templates/menu/#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..616b6de09 --- /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: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.HasShortcode NAME] +--- + +By example, let's use [Plotly] to render a chart: + +[Plotly]: https://plotly.com/javascript/ + +```text {file="content/example.md"} +{{</* plotly */>}} +{ + "data": [ + { + "x": ["giraffes", "orangutans", "monkeys"], + "y": [20, 14, 23], + "type": "bar" + } + ], +} +{{</* /plotly */>}} +``` + +The shortcode is simple: + +```go-html-template {file="layouts/shortcodes/plotly.html"} +{{ $id := printf "plotly-%02d" .Ordinal }} +<div id="{{ $id }}"></div> +<script> + Plotly.newPlot(document.getElementById({{ $id }}), {{ .Inner | safeJS }}); +</script> +``` + +Now we can selectively load the required JavaScript on pages that call the "plotly" shortcode: + +```go-html-template {file="layouts/_default/baseof.html"} +<head> + ... + {{ if .HasShortcode "plotly" }} + <script src="https://cdn.plot.ly/plotly-2.28.0.min.js"></script> + {{ end }} + ... +</head> +``` diff --git a/docs/content/en/methods/page/HeadingsFiltered.md b/docs/content/en/methods/page/HeadingsFiltered.md new file mode 100644 index 000000000..86c989d43 --- /dev/null +++ b/docs/content/en/methods/page/HeadingsFiltered.md @@ -0,0 +1,16 @@ +--- +title: HeadingsFiltered +description: Returns a slice of headings for each page related to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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-content/#index-content-headings diff --git a/docs/content/en/methods/page/InSection.md b/docs/content/en/methods/page/InSection.md new file mode 100644 index 000000000..adca82d86 --- /dev/null +++ b/docs/content/en/methods/page/InSection.md @@ -0,0 +1,91 @@ +--- +title: InSection +description: Reports whether the given page is in the given section. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.InSection SECTION] +--- + +{{% glossary-term section %}} + +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. + +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](g) (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. + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.InSection . }} → true +{{ end }} +``` + +> [!note] +> Gaining a thorough understanding of context is critical for anyone writing template code. + +[`else`]: /functions/go-template/else/ +[`with`]: /functions/go-template/with/ diff --git a/docs/content/en/methods/page/IsAncestor.md b/docs/content/en/methods/page/IsAncestor.md new file mode 100644 index 000000000..fe1b78454 --- /dev/null +++ b/docs/content/en/methods/page/IsAncestor.md @@ -0,0 +1,87 @@ +--- +title: IsAncestor +description: Reports whether PAGE1 is an ancestor of PAGE2. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE1.IsAncestor PAGE2] +--- + +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](g) (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. + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.IsAncestor . }} → true +{{ end }} +``` + +> [!note] +> Gaining a thorough understanding of context is critical for anyone writing template code. + +[`else`]: /functions/go-template/else/ +[`with`]: /functions/go-template/with/ diff --git a/docs/content/en/methods/page/IsDescendant.md b/docs/content/en/methods/page/IsDescendant.md new file mode 100644 index 000000000..6ee8d3c4f --- /dev/null +++ b/docs/content/en/methods/page/IsDescendant.md @@ -0,0 +1,87 @@ +--- +title: IsDescendant +description: Reports whether PAGE1 is a descendant of PAGE2. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE1.IsDescendant PAGE2] +--- + +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](g) (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. + +```go-html-template +{{ with .Site.GetPage "/auctions" }} + {{ $.IsDescendant . }} → true +{{ end }} +``` + +> [!note] +> Gaining a thorough understanding of context is critical for anyone writing template code. + +[`else`]: /functions/go-template/else/ +[`with`]: /functions/go-template/with/ diff --git a/docs/content/en/methods/page/IsHome.md b/docs/content/en/methods/page/IsHome.md new file mode 100644 index 000000000..66d8180b0 --- /dev/null +++ b/docs/content/en/methods/page/IsHome.md @@ -0,0 +1,26 @@ +--- +title: IsHome +description: Reports whether the given page is the home page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.IsHome] +--- + +The `IsHome` method on a `Page` object returns `true` if the [page kind](g) 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 }} +``` diff --git a/docs/content/en/methods/page/IsMenuCurrent.md b/docs/content/en/methods/page/IsMenuCurrent.md new file mode 100644 index 000000000..9bbacd018 --- /dev/null +++ b/docs/content/en/methods/page/IsMenuCurrent.md @@ -0,0 +1,31 @@ +--- +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: [] +params: + functions_and_methods: + 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. + +> [!note] +> When using this method you must either define the menu entry in front matter, or specify a `pageRef` property when defining the menu entry in your site configuration. + +[menu templates]: /templates/menu/#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..194a2cac8 --- /dev/null +++ b/docs/content/en/methods/page/IsNode.md @@ -0,0 +1,32 @@ +--- +title: IsNode +description: Reports whether the given page is a node. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.IsNode] +--- + +The `IsNode` method on a `Page` object returns `true` if the [page kind](g) 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 }} +``` diff --git a/docs/content/en/methods/page/IsPage.md b/docs/content/en/methods/page/IsPage.md new file mode 100644 index 000000000..910a3a7e1 --- /dev/null +++ b/docs/content/en/methods/page/IsPage.md @@ -0,0 +1,26 @@ +--- +title: IsPage +description: Reports whether the given page is a regular page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.IsPage] +--- + +The `IsPage` method on a `Page` object returns `true` if the [page kind](g) 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 }} +``` diff --git a/docs/content/en/methods/page/IsSection.md b/docs/content/en/methods/page/IsSection.md new file mode 100644 index 000000000..7a04fbd8f --- /dev/null +++ b/docs/content/en/methods/page/IsSection.md @@ -0,0 +1,26 @@ +--- +title: IsSection +description: Reports whether the given page is a section page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.IsSection] +--- + +The `IsSection` method on a `Page` object returns `true` if the [page kind](g) 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 }} +``` diff --git a/docs/content/en/methods/page/IsTranslated.md b/docs/content/en/methods/page/IsTranslated.md new file mode 100644 index 000000000..2cdf911ac --- /dev/null +++ b/docs/content/en/methods/page/IsTranslated.md @@ -0,0 +1,56 @@ +--- +title: IsTranslated +description: Reports whether the given page has one or more translations. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..7c940984e --- /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: [] +params: + functions_and_methods: + returnType: '[]string' + signatures: [PAGE.Keywords] +--- + +By default, Hugo evaluates the keywords when creating collections of [related content]. + +[related content]: /content-management/related-content/ + +{{< 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..a01877e8c --- /dev/null +++ b/docs/content/en/methods/page/Kind.md @@ -0,0 +1,32 @@ +--- +title: Kind +description: Returns the kind of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Kind] +--- + +The [page kind](g) 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 }} +``` diff --git a/docs/content/en/methods/page/Language.md b/docs/content/en/methods/page/Language.md new file mode 100644 index 000000000..9fd604df3 --- /dev/null +++ b/docs/content/en/methods/page/Language.md @@ -0,0 +1,69 @@ +--- +title: Language +description: Returns the language object for the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. Falls back to `Lang` if not defined. + +```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..643eddc5e --- /dev/null +++ b/docs/content/en/methods/page/Lastmod.md @@ -0,0 +1,36 @@ +--- +title: Lastmod +description: Returns the last modification date of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..f9aa5b6ab --- /dev/null +++ b/docs/content/en/methods/page/Layout.md @@ -0,0 +1,39 @@ +--- +title: Layout +description: Returns the layout for the given page as defined in front matter. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 fm=true >}} +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..010da88d1 --- /dev/null +++ b/docs/content/en/methods/page/Len.md @@ -0,0 +1,14 @@ +--- +title: Len +description: Returns the length, in bytes, of the rendered content of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..fcfd5318d --- /dev/null +++ b/docs/content/en/methods/page/LinkTitle.md @@ -0,0 +1,29 @@ +--- +title: LinkTitle +description: Returns the link title of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..996603083 --- /dev/null +++ b/docs/content/en/methods/page/Next.md @@ -0,0 +1,12 @@ +--- +title: Next +description: Returns the next page in a site's collection of regular pages, relative to the current page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.Next] +--- + +{{% include "/_common/methods/page/next-and-prev.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..eb02c9492 --- /dev/null +++ b/docs/content/en/methods/page/NextInSection.md @@ -0,0 +1,12 @@ +--- +title: NextInSection +description: Returns the next regular page in a section, relative to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.NextInSection] +--- + +{{% include "/_common/methods/page/nextinsection-and-previnsection.md" %}} diff --git a/docs/content/en/methods/page/OutputFormats.md b/docs/content/en/methods/page/OutputFormats.md new file mode 100644 index 000000000..0e648efaa --- /dev/null +++ b/docs/content/en/methods/page/OutputFormats.md @@ -0,0 +1,38 @@ +--- +title: OutputFormats +description: Returns a slice of OutputFormat objects, each representing one of the output formats enabled for the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: '[]OutputFormat' + signatures: [PAGE.OutputFormats] +--- + +{{% glossary-term "output format" %}} + +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](/configuration/output-formats/). + +## Methods + +{{% include "/_common/methods/page/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]: /configuration/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..7c7728b2f --- /dev/null +++ b/docs/content/en/methods/page/Page.md @@ -0,0 +1,35 @@ +--- +title: Page +description: Returns the Page object of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.Page] +--- + +This is a convenience method, useful within partial templates that are called from both [shortcodes](g) and page templates. + +```go-html-template {file="layouts/shortcodes/foo.html"} +{{ partial "my-partial.html" . }} +``` + +When the shortcode calls the partial, it passes the current [context](g) (the dot). The context includes identifiers such as `Page`, `Params`, `Inner`, and `Name`. + +```go-html-template {file="layouts/_default/single.html"} +{{ partial "my-partial.html" . }} +``` + +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. + +```go-html-template {file="layouts/partials/my-partial.html"} +The page title is: {{ .Page.Title }} +``` + +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. diff --git a/docs/content/en/methods/page/Pages.md b/docs/content/en/methods/page/Pages.md new file mode 100644 index 000000000..ba43c36a8 --- /dev/null +++ b/docs/content/en/methods/page/Pages.md @@ -0,0 +1,82 @@ +--- +title: Pages +description: Returns a collection of regular pages within the current section, and section pages of immediate descendant sections. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.Pages] +--- + +The `Pages` method on a `Page` object is available to these [page kinds](g): `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection](g) in [context](g), in the [default sort order](g). + +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](g)---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]. + +```go-html-template +{{ range .Site.Pages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +[details]: /methods/site/pages/ diff --git a/docs/content/en/methods/page/Paginate.md b/docs/content/en/methods/page/Paginate.md new file mode 100644 index 000000000..0b699d6b2 --- /dev/null +++ b/docs/content/en/methods/page/Paginate.md @@ -0,0 +1,47 @@ +--- +title: Paginate +description: Paginates a collection of pages. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 your [site configuration]. The default is `10`. Override that value 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. + +You can invoke pagination on the [home template], [section templates], [taxonomy templates], and [term templates]. + +```go-html-template {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" . }} +``` + +In the example above, we: + +1. Build a page collection +1. Sort the collection by title +1. Paginate the collection, with 7 elements per pager +1. Range over the paginated page collection, rendering a link to each page +1. Call the embedded pagination template to create 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. + +[home template]: /templates/types/#home +[section templates]: /templates/types/#section +[site configuration]: /configuration/pagination/ +[taxonomy templates]: /templates/types/#taxonomy +[term templates]: /templates/types/#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..bff7ea90c --- /dev/null +++ b/docs/content/en/methods/page/Paginator.md @@ -0,0 +1,40 @@ +--- +title: Paginator +description: Paginates the collection of regular pages received in context. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 your [site configuration]. The default is `10`. + +You can invoke pagination on the [home template], [section templates], [taxonomy templates], and [term templates]. Each of these receives a collection of regular pages in [context](g). When you invoke the `Paginator` method, it paginates the page collection received in context. + +```go-html-template {file="layouts/_default/list.html"} +{{ range .Paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +{{ template "_internal/pagination.html" . }} +``` + +In the example above, the embedded pagination template creates 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. + +> [!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. + +[home template]: /templates/types/#home +[section templates]: /templates/types/#section +[site configuration]: /configuration/pagination/ +[taxonomy templates]: /templates/types/#taxonomy +[term templates]: /templates/types/#term +[`Paginate`]: /methods/page/paginate/ diff --git a/docs/content/en/methods/page/Param.md b/docs/content/en/methods/page/Param.md new file mode 100644 index 000000000..b07c1cd92 --- /dev/null +++ b/docs/content/en/methods/page/Param.md @@ -0,0 +1,48 @@ +--- +title: Param +description: Returns a page parameter with the given key, falling back to a site parameter if present. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 +[params] +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..eeb253437 --- /dev/null +++ b/docs/content/en/methods/page/Params.md @@ -0,0 +1,42 @@ +--- +title: Params +description: Returns a map of custom parameters as defined in the front matter of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Params + signatures: [PAGE.Params] +--- + +By way of example, consider this front matter: + +{{< code-toggle file=content/annual-conference.md fm=true >}} +title = 'Annual conference' +date = 2023-10-17T15:11:37-07:00 +[params] +display_related = true +key-with-hyphens = 'must use index function' +[params.author] + email = 'jsmith@example.org' + name = 'John Smith' +{{< /code-toggle >}} + +The `title` and `date` fields are standard [front matter fields], while the other fields are user-defined. + +Access the custom fields by [chaining](g) the [identifiers](g) when needed: + +```go-html-template +{{ .Params.display_related }} → true +{{ .Params.author.email }} → jsmith@example.org +{{ .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 "key-with-hyphens" }} → must use index function +``` + +[`index`]: /functions/collections/indexfunction/ +[front matter fields]: /content-management/front-matter/#fields diff --git a/docs/content/en/methods/page/Parent.md b/docs/content/en/methods/page/Parent.md new file mode 100644 index 000000000..0946a7993 --- /dev/null +++ b/docs/content/en/methods/page/Parent.md @@ -0,0 +1,52 @@ +--- +title: Parent +description: Returns the Page object of the parent section of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.Parent] +--- + +{{% glossary-term section %}} + +> [!note] +> The parent section of a regular page is the [current section]. + +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 }} +``` + +[current section]: /methods/page/currentsection/ diff --git a/docs/content/en/methods/page/Path.md b/docs/content/en/methods/page/Path.md new file mode 100644 index 000000000..db4e7d629 --- /dev/null +++ b/docs/content/en/methods/page/Path.md @@ -0,0 +1,140 @@ +--- +title: Path +description: Returns the logical path of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Path] +--- + +{{< new-in 0.123.0 />}} + +The `Path` method on a `Page` object returns the logical path of the given page, regardless of whether the page is backed by a file. + +{{% glossary-term "logical path" %}} + +```go-html-template +{{ .Path }} → /posts/post-1 +``` + +> [!note] +> Beginning with the release of [v0.92.0] in January 2022, Hugo emitted a warning whenever calling the `Path` method. The warning indicated that this method would change in a future release. +> +> The meaning of, and value returned by, the `Path` method on a `Page` object changed with the release of [v0.123.0] in February 2024. + +The value returned by the `Path` method on a `Page` object is independent of content format, language, and URL modifiers such as the `slug` and `url` front matter fields. + +## Examples + +### Monolingual site + +Note that the logical path is independent of content format and URL modifiers. + +File path|Front matter slug|Logical path +:--|:--|:-- +`content/_index.md`||`/` +`content/posts/_index.md`||`/posts` +`content/posts/post-1.md`|`foo`|`/posts/post-1` +`content/posts/post-2.html`|`bar`|`/posts/post-2` + +### Multilingual site + +Note that the logical path is independent of content format, language identifiers, and URL modifiers. + +File path|Front matter slug|Logical path +:--|:--|:-- +`content/_index.en.md`||`/` +`content/_index.de.md`||`/` +`content/posts/_index.en.md`||`/posts` +`content/posts/_index.de.md`||`/posts` +`content/posts/posts-1.en.md`|`foo`|`/posts/post-1` +`content/posts/posts-1.de.md`|`foo`|`/posts/post-1` +`content/posts/posts-2.en.html`|`bar`|`/posts/post-2` +`content/posts/posts-2.de.html`|`bar`|`/posts/post-2` + +### Pages not backed by a file + +The `Path` method on a `Page` object returns a value regardless of whether the page is backed by a file. + +```text +content/ +└── posts/ + └── post-1.md <-- front matter: tags = ['hugo'] +``` + +When you build the site: + +```text +public/ +├── posts/ +│ ├── post-1/ +│ │ └── index.html .Page.Path = /posts/post-1 +│ └── index.html .Page.Path = /posts +├── tags/ +│ ├── hugo/ +│ │ └── index.html .Page.Path = /tags/hugo +│ └── index.html .Page.Path = /tags +└── index.html .Page.Path = / +``` + +## Finding pages + +These methods, functions, and shortcodes use the logical path to find the given page: + +Methods|Functions|Shortcodes +:--|:--|:-- +[`Site.GetPage`]|[`urls.Ref`]|[`ref`] +[`Page.GetPage`]|[`urls.RelRef`]|[`relref`] +[`Page.Ref`]||| +[`Page.RelRef`]||| +[`Shortcode.Ref`]||| +[`Shortcode.RelRef`]||| + +> [!note] +> Specify the logical path when using any of these methods, functions, or shortcodes. If you include a file extension or language identifier, Hugo will strip these values before finding the page in the logical tree. + +## Logical tree + +Just as file paths form a file tree, logical paths form a logical tree. + +A file tree: + +```text +content/ +└── s1/ + ├── p1/ + │ └── index.md + └── p2.md +``` + +The same content represented as a logical tree: + +```text +content/ +└── s1/ + ├── p1 + └── p2 +``` + +A key difference between these trees is the relative path from p1 to p2: + +- In the file tree, the relative path from p1 to p2 is `../p2.md` +- In the logical tree, the relative path is `p2` + +> [!note] +> Remember to use the logical path when using any of the methods, functions, or shortcodes listed in the previous section. If you include a file extension or language identifier, Hugo will strip these values before finding the page in the logical tree. + +[`Page.GetPage`]: /methods/page/getpage/ +[`Page.Ref`]: /methods/page/ref/ +[`Page.RelRef`]: /methods/page/relref/ +[`ref`]: /shortcodes/ref/ +[`relref`]: /shortcodes/relref/ +[`Shortcode.Ref`]: /methods/shortcode/ref +[`Shortcode.RelRef`]: /methods/shortcode/relref +[`Site.GetPage`]: /methods/site/getpage/ +[`urls.Ref`]: /functions/urls/ref/ +[`urls.RelRef`]: /functions/urls/relref/ +[v0.123.0]: https://github.com/gohugoio/hugo/releases/tag/v0.123.0 +[v0.92.0]: https://github.com/gohugoio/hugo/releases/tag/v0.92.0 diff --git a/docs/content/en/methods/page/Permalink.md b/docs/content/en/methods/page/Permalink.md new file mode 100644 index 000000000..cc74f3342 --- /dev/null +++ b/docs/content/en/methods/page/Permalink.md @@ -0,0 +1,24 @@ +--- +title: Permalink +description: Returns the permalink of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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.Permalink }} → 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..65d11166e --- /dev/null +++ b/docs/content/en/methods/page/Plain.md @@ -0,0 +1,23 @@ +--- +title: Plain +description: Returns the rendered content of the given page, removing all HTML tags. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Plain] +--- + +The `Plain` method on a `Page` object renders Markdown and [shortcodes](g) to HTML, then strips the HTML [tags]. It does not strip HTML [entities]. + +To prevent Go's [html/template] package from escaping HTML entities, pass the result through the [`htmlUnescape`] function. + +```go-html-template +{{ .Plain | htmlUnescape }} +``` + +[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/transform/htmlunescape/ diff --git a/docs/content/en/methods/page/PlainWords.md b/docs/content/en/methods/page/PlainWords.md new file mode 100644 index 000000000..5749a21f9 --- /dev/null +++ b/docs/content/en/methods/page/PlainWords.md @@ -0,0 +1,31 @@ +--- +title: PlainWords +description: Calls the Plain method, splits the result into a slice of words, and returns the slice. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 whitespace characters, as defined by [`unicode.IsSpace`], returning a slice of substrings of `s` or an empty slice if `s` contains only whitespace. + +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 +[`unicode.IsSpace`]: https://pkg.go.dev/unicode#IsSpace diff --git a/docs/content/en/methods/page/Prev.md b/docs/content/en/methods/page/Prev.md new file mode 100644 index 000000000..5a6e2162d --- /dev/null +++ b/docs/content/en/methods/page/Prev.md @@ -0,0 +1,12 @@ +--- +title: Prev +description: Returns the previous page in a site's collection of regular pages, relative to the current page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.Prev] +--- + +{{% include "/_common/methods/page/next-and-prev.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..14d3ca082 --- /dev/null +++ b/docs/content/en/methods/page/PrevInSection.md @@ -0,0 +1,12 @@ +--- +title: PrevInSection +description: Returns the previous regular page in a section, relative to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGE.PrevInSection] +--- + +{{% include "/_common/methods/page/nextinsection-and-previnsection.md" %}} diff --git a/docs/content/en/methods/page/PublishDate.md b/docs/content/en/methods/page/PublishDate.md new file mode 100644 index 000000000..7500a08aa --- /dev/null +++ b/docs/content/en/methods/page/PublishDate.md @@ -0,0 +1,32 @@ +--- +title: PublishDate +description: Returns the publish date of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..41215ef53 --- /dev/null +++ b/docs/content/en/methods/page/RawContent.md @@ -0,0 +1,23 @@ +--- +title: RawContent +description: Returns the raw content of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g). + +> [!note] +> [Shortcodes](g) within the content are not rendered. To get the raw content with shortcodes rendered, use the [`RenderShortcodes`] method on a `Page` object. + +[`RenderShortcodes`]: /methods/page/rendershortcodes/ diff --git a/docs/content/en/methods/page/ReadingTime.md b/docs/content/en/methods/page/ReadingTime.md new file mode 100644 index 000000000..1bd7dea31 --- /dev/null +++ b/docs/content/en/methods/page/ReadingTime.md @@ -0,0 +1,47 @@ +--- +title: ReadingTime +description: Returns the estimated reading time, in minutes, for the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..35f9460ba --- /dev/null +++ b/docs/content/en/methods/page/Ref.md @@ -0,0 +1,37 @@ +--- +title: Ref +description: Returns the absolute URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Ref OPTIONS] +--- + +## Usage + +The `Ref` method accepts a single argument: an options map. + +## Options + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The following examples show the rendered output for a page on the English 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 +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} diff --git a/docs/content/en/methods/page/RegularPages.md b/docs/content/en/methods/page/RegularPages.md new file mode 100644 index 000000000..761de3af5 --- /dev/null +++ b/docs/content/en/methods/page/RegularPages.md @@ -0,0 +1,79 @@ +--- +title: RegularPages +description: Returns a collection of regular pages within the current section. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.RegularPages] +--- + +The `RegularPages` method on a `Page` object is available to these [page kinds](g): `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection](g) in [context](g), in the [default sort order](g). + +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](g)---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]. + +```go-html-template +{{ range .Site.RegularPages.ByTitle }} + <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> +{{ end }} +``` + +[details]: /methods/site/regularpages/ diff --git a/docs/content/en/methods/page/RegularPagesRecursive.md b/docs/content/en/methods/page/RegularPagesRecursive.md new file mode 100644 index 000000000..d85cd0b48 --- /dev/null +++ b/docs/content/en/methods/page/RegularPagesRecursive.md @@ -0,0 +1,83 @@ +--- +title: RegularPagesRecursive +description: Returns a collection of regular pages within the current section, and regular pages within all descendant sections. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.RegularPagesRecursive] +--- + +The `RegularPagesRecursive` method on a `Page` object is available to these [page kinds](g): `home`, `section`, `taxonomy`, and `term`. The templates for these page kinds receive a page [collection](g) in [context](g), in the [default sort order](g). + +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 is not available on a `Site` object. diff --git a/docs/content/en/methods/page/RelPermalink.md b/docs/content/en/methods/page/RelPermalink.md new file mode 100644 index 000000000..a3c610d50 --- /dev/null +++ b/docs/content/en/methods/page/RelPermalink.md @@ -0,0 +1,24 @@ +--- +title: RelPermalink +description: Returns the relative permalink of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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.RelPermalink }} → /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..7edab5740 --- /dev/null +++ b/docs/content/en/methods/page/RelRef.md @@ -0,0 +1,37 @@ +--- +title: RelRef +description: Returns the relative URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.RelRef OPTIONS] +--- + +## Usage + +The `RelRef` method accepts a single argument: an options map. + +## Options + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The following examples show the rendered output for a page on the English 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 +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} diff --git a/docs/content/en/methods/page/Render.md b/docs/content/en/methods/page/Render.md new file mode 100644 index 000000000..10f7f9ca5 --- /dev/null +++ b/docs/content/en/methods/page/Render.md @@ -0,0 +1,72 @@ +--- +title: Render +description: Renders the given template with the given page as context. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g).|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/content-view/ +[`partial`]: /functions/partials/include/ diff --git a/docs/content/en/methods/page/RenderShortcodes.md b/docs/content/en/methods/page/RenderShortcodes.md new file mode 100644 index 000000000..d124606f0 --- /dev/null +++ b/docs/content/en/methods/page/RenderShortcodes.md @@ -0,0 +1,89 @@ +--- +title: RenderShortcodes +description: Renders all shortcodes in the content of the given page, preserving the surrounding markup. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.RenderShortcodes] +--- + +{{< 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: + +```go-html-template {file="layouts/shortcodes/include.html" copy=true} +{{ with .Get 0 }} + {{ with $.Page.GetPage . }} + {{- .RenderShortcodes }} + {{ else }} + {{ errorf "The %q shortcode was unable to find %q. See %s" $.Name . $.Position }} + {{ end }} +{{ else }} + {{ errorf "The %q shortcode requires a positional parameter indicating the logical path of the file to include. See %s" .Name .Position }} +{{ end }} +``` + +Then call the shortcode in your Markdown: + +```text {file="content/about.md"} +{{%/* include "/snippets/services" */%}} +{{%/* include "/snippets/values" */%}} +{{%/* include "/snippets/leadership" */%}} +``` + +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 + +```text {file="content/about.md"} ++++ +title = 'About' +date = 2023-10-07T12:28:33-07:00 ++++ + +{{</* ref "privacy" */>}} + +An *emphasized* word. +``` + +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. + +## Limitations + +The primary use case for `.RenderShortcodes` is inclusion of Markdown content. If you try to use `.RenderShortcodes` inside `HTML` blocks when inside Markdown, you will get a warning similar to this: + +```text +WARN .RenderShortcodes detected inside HTML block in "/content/mypost.md"; this may not be what you intended ... +``` + +The above warning can be turned off is this is what you really want. diff --git a/docs/content/en/methods/page/RenderString.md b/docs/content/en/methods/page/RenderString.md new file mode 100644 index 000000000..c7774774c --- /dev/null +++ b/docs/content/en/methods/page/RenderString.md @@ -0,0 +1,49 @@ +--- +title: RenderString +description: Renders markup to HTML. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/#classification +[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..dd472de88 --- /dev/null +++ b/docs/content/en/methods/page/Resources.md @@ -0,0 +1,90 @@ +--- +title: Resources +description: Returns a collection of page resources. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: resource.Resources + signatures: [PAGE.Resources] +--- + +The `Resources` method on a `Page` object returns a collection of page resources. A page resource is a file within a [page bundle](g). + +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](g) 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](g) 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. + +### Mount + +{{< new-in 0.140.0 />}} + +(`ResourceGetter`) Mounts the given resources from the two arguments base (`string`) to the given target path (`string`) and returns an object that implements [Get](#get). Note that leading slashes in target marks an absolute path. Relative target paths allows you to mount resources relative to another set, e.g. a [Page bundle](/content-management/page-bundles/): + +```go-html-template +{{ $common := resources.Match "/js/headlessui/*.*" }} +{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }} +``` + +This method is currently only useful in [js.Batch](/functions/js/batch/#import-context). + +## Pattern matching + +With the `GetMatch` and `Match` methods, Hugo determines a match using a case-insensitive [glob](g) pattern. + +{{% include "/_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/ +[media type]: https://en.wikipedia.org/wiki/Media_type diff --git a/docs/content/en/methods/page/Scratch.md b/docs/content/en/methods/page/Scratch.md new file mode 100644 index 000000000..61c5dc19e --- /dev/null +++ b/docs/content/en/methods/page/Scratch.md @@ -0,0 +1,21 @@ +--- +title: Scratch +description: Returns a "scratch pad" to store and manipulate data, scoped to the current page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Scratch + signatures: [PAGE.Scratch] +expiryDate: 2026-11-18 # deprecated 2024-11-18 (soft) +--- + +{{< deprecated-in 0.138.0 >}} +Use the [`PAGE.Store`] method instead. + +This is a soft deprecation. This method will be removed in a future release, but the removal date has not been established. Although Hugo will not emit a warning if you continue to use this method, you should begin using `PAGE.Store` as soon as possible. + +Beginning with v0.138.0 the `PAGE.Scratch` method is aliased to `PAGE.Store`. + +[`PAGE.Store`]: /methods/page/store/ +{{< /deprecated-in >}} diff --git a/docs/content/en/methods/page/Section.md b/docs/content/en/methods/page/Section.md new file mode 100644 index 000000000..04c6a8a24 --- /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: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Section] +--- + +{{% glossary-term 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..12f0a8c24 --- /dev/null +++ b/docs/content/en/methods/page/Sections.md @@ -0,0 +1,62 @@ +--- +title: Sections +description: Returns a collection of section pages, one for each immediate descendant section of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.Sections] +--- + +The `Sections` method on a `Page` object is available to these [page kinds](g): `home`, `section`, and `taxonomy`. The templates for these page kinds receive a page [collection](g) in [context](g), in the [default sort order](g). + +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 = 20 +│ ├── book-1.md +│ └── book-2.md +├── films/ +│ ├── _index.md <-- front matter: weight = 10 +│ ├── 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..4649e5e00 --- /dev/null +++ b/docs/content/en/methods/page/Site.md @@ -0,0 +1,18 @@ +--- +title: Site +description: Returns the Site object. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..bb1360493 --- /dev/null +++ b/docs/content/en/methods/page/Sitemap.md @@ -0,0 +1,81 @@ +--- +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: [] +params: + functions_and_methods: + returnType: config.SitemapConfig + signatures: [PAGE.Sitemap] +--- + +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`. With the default value of `""` Hugo will omit this field from the sitemap. See [details](https://www.sitemaps.org/protocol.html#changefreqdef). + +```go-html-template +{{ .Sitemap.ChangeFreq }} +``` + +### Disable + +{{< new-in 0.125.0 />}} + +(`bool`) Whether to disable page inclusion. Default is `false`. Set to `true` in front matter to exclude the page. + +```go-html-template +{{ .Sitemap.Disable }} +``` + +### Priority + +(`float`) The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. With the default value of `-1` Hugo will omit this field from the sitemap. See [details](https://www.sitemaps.org/protocol.html#prioritydef). + +```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: + +```xml {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> +``` + +The change frequency will be `hourly` for the news page, and `monthly` for other pages. + +[sitemap templates]: /templates/sitemap/ diff --git a/docs/content/en/methods/page/Sites.md b/docs/content/en/methods/page/Sites.md new file mode 100644 index 000000000..8677226d7 --- /dev/null +++ b/docs/content/en/methods/page/Sites.md @@ -0,0 +1,68 @@ +--- +title: Sites +description: Returns a collection of all Site objects, one for each language, ordered by language weight. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 the home page of the site corresponding to the default content language: + +```go-html-template +{{ with .Sites.Default }} + <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..34000b660 --- /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: [] +params: + functions_and_methods: + 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..0b1049b0a --- /dev/null +++ b/docs/content/en/methods/page/Store.md @@ -0,0 +1,35 @@ +--- +title: Store +description: Returns a "scratch pad" to store and manipulate data, scoped to the current page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Scratch + signatures: [PAGE.Store] +aliases: [/functions/store/,/extras/scratch/,/doc/scratch/,/functions/scratch] +--- + +Use the `Store` method on a `Page` object to create a [scratch pad](g) to store and manipulate data, scoped to the current page. To create a scratch pad with a different [scope](g), refer to the [scope](#scope) section below. + +{{% include "_common/store-methods.md" %}} + +{{% include "_common/scratch-pad-scope.md" %}} + +## Determinate values + +The `Store` method is often used to set scratch pad values within a shortcode, a partial template called by a shortcode, or by a Markdown render hook. In all three cases, the scratch pad values are indeterminate until Hugo renders the page content. + +If you need to access a scratch pad value from a parent template, and the parent template has not yet rendered the page content, you can trigger content rendering by assigning the returned value to a [noop](g) variable: + +```go-html-template +{{ $noop := .Content }} +{{ .Store.Get "mykey" }} +``` + +You can also trigger content rendering with the `ContentWithoutSummary`, `FuzzyWordCount`, `Len`, `Plain`, `PlainWords`, `ReadingTime`, `Summary`, `Truncated`, and `WordCount` methods. For example: + +```go-html-template +{{ $noop := .WordCount }} +{{ .Store.Get "mykey" }} +``` diff --git a/docs/content/en/methods/page/Summary.md b/docs/content/en/methods/page/Summary.md new file mode 100644 index 000000000..9158e571d --- /dev/null +++ b/docs/content/en/methods/page/Summary.md @@ -0,0 +1,44 @@ +--- +title: Summary +description: Returns the summary of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.Summary] +--- + +<!-- Do not remove the manual summary divider below. --> +<!-- If you do, you will break its first literal usage on this page. --> + +<!--more--> + +You can define a [summary] manually, in front matter, or automatically. A manual summary takes precedence over a front matter summary, and a front matter summary takes precedence over an automatic summary. + +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 }} +``` + +Depending on content length and how you define the summary, the summary may be equivalent to the content itself. To determine whether the content length exceeds the summary length, use the [`Truncated`] method on a `Page` object. This is useful for conditionally 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 }} +``` + +> [!note] +> The `Truncated` method returns `false` if you define the summary in front matter. + +[`Truncated`]: /methods/page/truncated +[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..7ec9fe614 --- /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: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.TableOfContents] +aliases: [/content-management/toc/] +--- + +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..dae4ba6dd --- /dev/null +++ b/docs/content/en/methods/page/Title.md @@ -0,0 +1,39 @@ +--- +title: Title +description: Returns the title of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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, taxonomy, and term pages not backed by a file, the `Title` method returns the section name, capitalized and pluralized. You can disable these transformations by setting [`capitalizeListTitles`] and [`pluralizeListTitles`] in your site configuration. For example: + +{{< code-toggle file=hugo >}} +capitalizeListTitles = false +pluralizeListTitles = false +{{< /code-toggle >}} + +You can change the capitalization style in your site configuration to one of `ap`, `chicago`, `go`, `firstupper`, or `none`. For example: + +{{< code-toggle file=hugo >}} +titleCaseStyle = "firstupper" +{{< /code-toggle >}} + + See [details]. + +[`capitalizeListTitles`]: /configuration/all/#capitalizelisttitles +[`pluralizeListTitles`]: /configuration/all/#pluralizelisttitles +[details]: /configuration/all/#title-case-style diff --git a/docs/content/en/methods/page/TranslationKey.md b/docs/content/en/methods/page/TranslationKey.md new file mode 100644 index 000000000..1e930687e --- /dev/null +++ b/docs/content/en/methods/page/TranslationKey.md @@ -0,0 +1,71 @@ +--- +title: TranslationKey +description: Returns the translation key of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..4bab9fe11 --- /dev/null +++ b/docs/content/en/methods/page/Translations.md @@ -0,0 +1,86 @@ +--- +title: Translations +description: Returns all translations of the given page, excluding the current language. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 . }} + <li> + <a href="{{ .RelPermalink }}" hreflang="{{ .Language.LanguageCode }}">{{ .LinkTitle }} ({{ or .Language.LanguageName .Language.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/" hreflang="de-DE">Book 1 (Deutsch)</a></li> + <li><a href="/fr/books/book-1/" hreflang="fr-FR">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/" hreflang="de-DE">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..8c2573069 --- /dev/null +++ b/docs/content/en/methods/page/Truncated.md @@ -0,0 +1,29 @@ +--- +title: Truncated +description: Reports whether the content length exceeds the summary length. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.Truncated] +--- + +You can define a [summary] manually, in front matter, or automatically. A manual summary takes precedence over a front matter summary, and a front matter summary takes precedence over an automatic summary. + +[summary]: /content-management/summaries/ + +The `Truncated` method returns `true` if the content length exceeds the summary length. This is useful for conditionally 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 }} +``` + +> [!note] +> The `Truncated` method returns `false` if you define the summary in front matter. diff --git a/docs/content/en/methods/page/Type.md b/docs/content/en/methods/page/Type.md new file mode 100644 index 000000000..6f855fbe3 --- /dev/null +++ b/docs/content/en/methods/page/Type.md @@ -0,0 +1,51 @@ +--- +title: Type +description: Returns the content type of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGE.Type] +--- + +The `Type` method on a `Page` object returns the [content type](g) 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](g): + +```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]. + +[details]: /templates/lookup-order/#target-a-template diff --git a/docs/content/en/methods/page/Weight.md b/docs/content/en/methods/page/Weight.md new file mode 100644 index 000000000..c14af0257 --- /dev/null +++ b/docs/content/en/methods/page/Weight.md @@ -0,0 +1,25 @@ +--- +title: Weight +description: Returns the weight of the given page as defined in front matter. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGE.Weight] +--- + +The `Weight` method on a `Page` object returns the [weight](g) of the given page as defined in front matter. + +{{< 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..3950244ca --- /dev/null +++ b/docs/content/en/methods/page/WordCount.md @@ -0,0 +1,18 @@ +--- +title: WordCount +description: Returns the number of words in the content of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/_index.md b/docs/content/en/methods/page/_index.md new file mode 100644 index 000000000..c7ae7ad5d --- /dev/null +++ b/docs/content/en/methods/page/_index.md @@ -0,0 +1,8 @@ +--- +title: Page methods +linkTitle: Page +description: Use these methods with a Page object. +categories: [] +keywords: [] +aliases: [/variables/page/] +--- diff --git a/docs/content/en/methods/pager/First.md b/docs/content/en/methods/pager/First.md new file mode 100644 index 000000000..9cd58989b --- /dev/null +++ b/docs/content/en/methods/pager/First.md @@ -0,0 +1,38 @@ +--- +title: First +description: Returns the first pager in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pager + signatures: [PAGER.First] +--- + +Use the `First` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/HasNext.md b/docs/content/en/methods/pager/HasNext.md new file mode 100644 index 000000000..cf3688efd --- /dev/null +++ b/docs/content/en/methods/pager/HasNext.md @@ -0,0 +1,66 @@ +--- +title: HasNext +description: Reports whether there is a pager after the current pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGER.HasNext] +--- + +Use the `HasNext` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ if .HasPrev }} + <li><a href="{{ .Prev.URL }}">Previous</a></li> + {{ end }} + {{ if .HasNext }} + <li><a href="{{ .Next.URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` + +You can also write the above without using the `HasNext` method: + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/HasPrev.md b/docs/content/en/methods/pager/HasPrev.md new file mode 100644 index 000000000..4b486b7c5 --- /dev/null +++ b/docs/content/en/methods/pager/HasPrev.md @@ -0,0 +1,66 @@ +--- +title: HasPrev +description: Reports whether there is a pager before the current pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGER.HasPrev] +--- + +Use the `HasPrev` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ if .HasPrev }} + <li><a href="{{ .Prev.URL }}">Previous</a></li> + {{ end }} + {{ if .HasNext }} + <li><a href="{{ .Next.URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` + +You can also write the above without using the `HasPrev` method: + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/Last.md b/docs/content/en/methods/pager/Last.md new file mode 100644 index 000000000..71dea183d --- /dev/null +++ b/docs/content/en/methods/pager/Last.md @@ -0,0 +1,38 @@ +--- +title: Last +description: Returns the last pager in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pager + signatures: [PAGER.Last] +--- + +Use the `Last` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/Next.md b/docs/content/en/methods/pager/Next.md new file mode 100644 index 000000000..d7ea9caa4 --- /dev/null +++ b/docs/content/en/methods/pager/Next.md @@ -0,0 +1,38 @@ +--- +title: Next +description: Returns the next pager in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pager + signatures: [PAGER.Next] +--- + +Use the `Next` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/NumberOfElements.md b/docs/content/en/methods/pager/NumberOfElements.md new file mode 100644 index 000000000..9f88126fc --- /dev/null +++ b/docs/content/en/methods/pager/NumberOfElements.md @@ -0,0 +1,23 @@ +--- +title: NumberOfElements +description: Returns the number of pages in the current pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.NumberOfElements] +--- + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + {{ .NumberOfElements }} +{{ end }} +``` diff --git a/docs/content/en/methods/pager/PageGroups.md b/docs/content/en/methods/pager/PageGroups.md new file mode 100644 index 000000000..46f6d81cb --- /dev/null +++ b/docs/content/en/methods/pager/PageGroups.md @@ -0,0 +1,28 @@ +--- +title: PageGroups +description: Returns the page groups in the current pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.PagesGroup + signatures: [PAGER.PageGroups] +--- + +Use the `PageGroups` method with any of the [grouping methods]. + +[grouping methods]: /quick-reference/page-collections/#group + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate ($pages.GroupByDate "Jan 2006") }} + +{{ range $paginator.PageGroups }} + <h2>{{ .Key }}</h2> + {{ range .Pages }} + <h3><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h3> + {{ end }} +{{ end }} + +{{ template "_internal/pagination.html" . }} +``` diff --git a/docs/content/en/methods/pager/PageNumber.md b/docs/content/en/methods/pager/PageNumber.md new file mode 100644 index 000000000..6d0b8e35d --- /dev/null +++ b/docs/content/en/methods/pager/PageNumber.md @@ -0,0 +1,29 @@ +--- +title: PageNumber +description: Returns the current pager's number within the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.PageNumber] +--- + +Use the `PageNumber` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ range .Pagers }} + <li><a href="{{ .URL }}">{{ .PageNumber }}</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/PageSize.md b/docs/content/en/methods/pager/PageSize.md new file mode 100644 index 000000000..5aad88682 --- /dev/null +++ b/docs/content/en/methods/pager/PageSize.md @@ -0,0 +1,17 @@ +--- +title: PageSize +description: Returns the number of pages per pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.PageSize] +expiryDate: 2026-06-09 # deprecated 2024-06-09 in v0.128.0 +--- + +{{< deprecated-in 0.128.0 >}} +Use [`PAGER.PagerSize`] instead. + +[`PAGER.PagerSize`]: /methods/pager/pagersize/ +{{< /deprecated-in >}} diff --git a/docs/content/en/methods/pager/PagerSize.md b/docs/content/en/methods/pager/PagerSize.md new file mode 100644 index 000000000..b2397a3e8 --- /dev/null +++ b/docs/content/en/methods/pager/PagerSize.md @@ -0,0 +1,30 @@ +--- +title: PagerSize +description: Returns the number of pages per pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.PagerSize] +--- + +{{< new-in 0.128.0 />}} + +The number of pages per pager is determined by the optional second argument passed to the [`Paginate`] method, falling back to the `pagerSize` as defined in your [site configuration]. + +[`Paginate`]: /methods/page/paginate/ +[site configuration]: /templates/pagination/#configuration + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + {{ .PagerSize }} +{{ end }} +``` diff --git a/docs/content/en/methods/pager/Pagers.md b/docs/content/en/methods/pager/Pagers.md new file mode 100644 index 000000000..e431069f4 --- /dev/null +++ b/docs/content/en/methods/pager/Pagers.md @@ -0,0 +1,29 @@ +--- +title: Pagers +description: Returns the pagers collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.pagers + signatures: [PAGER.Pagers] +--- + +Use the `Pagers` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ range .Pagers }} + <li><a href="{{ .URL }}">{{ .PageNumber }}</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/Pages.md b/docs/content/en/methods/pager/Pages.md new file mode 100644 index 000000000..6e5772a48 --- /dev/null +++ b/docs/content/en/methods/pager/Pages.md @@ -0,0 +1,21 @@ +--- +title: Pages +description: Returns the pages in the current pager. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGER.Pages] +--- + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ template "_internal/pagination.html" . }} +``` diff --git a/docs/content/en/methods/pager/Prev.md b/docs/content/en/methods/pager/Prev.md new file mode 100644 index 000000000..eb79f96e9 --- /dev/null +++ b/docs/content/en/methods/pager/Prev.md @@ -0,0 +1,38 @@ +--- +title: Prev +description: Returns the previous pager in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pager + signatures: [PAGER.Prev] +--- + +Use the `Prev` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/TotalNumberOfElements.md b/docs/content/en/methods/pager/TotalNumberOfElements.md new file mode 100644 index 000000000..ad29a01f3 --- /dev/null +++ b/docs/content/en/methods/pager/TotalNumberOfElements.md @@ -0,0 +1,23 @@ +--- +title: TotalNumberOfElements +description: Returns the number of pages in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.TotalNumberOfElements] +--- + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + {{ .TotalNumberOfElements }} +{{ end }} +``` diff --git a/docs/content/en/methods/pager/TotalPages.md b/docs/content/en/methods/pager/TotalPages.md new file mode 100644 index 000000000..63da5d786 --- /dev/null +++ b/docs/content/en/methods/pager/TotalPages.md @@ -0,0 +1,39 @@ +--- +title: TotalPages +description: Returns the number of pagers in the pager collection. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [PAGER.TotalPages] +--- + +Use the `TotalPages` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <p>Pager {{ .PageNumber }} of {{ .TotalPages }}</p> + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/URL.md b/docs/content/en/methods/pager/URL.md new file mode 100644 index 000000000..a3558ba7c --- /dev/null +++ b/docs/content/en/methods/pager/URL.md @@ -0,0 +1,38 @@ +--- +title: URL +description: Returns the URL of the current pager relative to the site root. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [PAGER.URL] +--- + +Use the `URL` method to build navigation between pagers. + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} + +{{ with $paginator }} + <ul> + {{ with .First }} + <li><a href="{{ .URL }}">First</a></li> + {{ end }} + {{ with .Prev }} + <li><a href="{{ .URL }}">Previous</a></li> + {{ end }} + {{ with .Next }} + <li><a href="{{ .URL }}">Next</a></li> + {{ end }} + {{ with .Last }} + <li><a href="{{ .URL }}">Last</a></li> + {{ end }} + </ul> +{{ end }} +``` diff --git a/docs/content/en/methods/pager/_index.md b/docs/content/en/methods/pager/_index.md new file mode 100644 index 000000000..7a79bf42f --- /dev/null +++ b/docs/content/en/methods/pager/_index.md @@ -0,0 +1,6 @@ +--- +title: Pager methods +linkTitle: Pager +description: Use these methods with Pager objects when building navigation for a paginated list page. +keywords: [] +--- diff --git a/docs/content/en/methods/pages/ByDate.md b/docs/content/en/methods/pages/ByDate.md new file mode 100644 index 000000000..18f1b985e --- /dev/null +++ b/docs/content/en/methods/pages/ByDate.md @@ -0,0 +1,28 @@ +--- +title: ByDate +description: Returns the given page collection sorted by date in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..703988c4e --- /dev/null +++ b/docs/content/en/methods/pages/ByExpiryDate.md @@ -0,0 +1,28 @@ +--- +title: ByExpiryDate +description: Returns the given page collection sorted by expiration date in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..36244eb4d --- /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: [] +params: + functions_and_methods: + 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..3c03d2a6e --- /dev/null +++ b/docs/content/en/methods/pages/ByLastmod.md @@ -0,0 +1,28 @@ +--- +title: ByLastmod +description: Returns the given page collection sorted by last modification date in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..c47bf98ba --- /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: [] +params: + functions_and_methods: + 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..4a024d25a --- /dev/null +++ b/docs/content/en/methods/pages/ByLinkTitle.md @@ -0,0 +1,24 @@ +--- +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: [] +params: + functions_and_methods: + 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..9544122a6 --- /dev/null +++ b/docs/content/en/methods/pages/ByParam.md @@ -0,0 +1,34 @@ +--- +title: ByParam +description: Returns the given page collection sorted by the given parameter in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..3dde6fd95 --- /dev/null +++ b/docs/content/en/methods/pages/ByPublishDate.md @@ -0,0 +1,28 @@ +--- +title: ByPublishDate +description: Returns the given page collection sorted by publish date in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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]: /configuration/front-matter/#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..e10c41714 --- /dev/null +++ b/docs/content/en/methods/pages/ByTitle.md @@ -0,0 +1,24 @@ +--- +title: ByTitle +description: Returns the given page collection sorted by title in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..ba255d3c3 --- /dev/null +++ b/docs/content/en/methods/pages/ByWeight.md @@ -0,0 +1,26 @@ +--- +title: ByWeight +description: Returns the given page collection sorted by weight in ascending order. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGES.ByWeight] +--- + +Assign a [weight](g) 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. + +```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..aff0800e9 --- /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: [] +params: + functions_and_methods: + returnType: page.PagesGroup + signatures: ['PAGES.GroupBy FIELD [SORT]'] +--- + +{{% include "/_common/methods/pages/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..7ef4843a4 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByDate.md @@ -0,0 +1,63 @@ +--- +title: GroupByDate +description: Returns the given page collection grouped by date in descending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g) for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[site configuration]: /configuration/front-matter/#dates + +{{% include "/_common/methods/pages/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 "/_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..d209e6c2b --- /dev/null +++ b/docs/content/en/methods/pages/GroupByExpiryDate.md @@ -0,0 +1,63 @@ +--- +title: GroupByExpiryDate +description: Returns the given page collection grouped by expiration date in descending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g) for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[site configuration]: /configuration/front-matter/#dates + +{{% include "/_common/methods/pages/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 "/_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..8729cd3c9 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByLastmod.md @@ -0,0 +1,63 @@ +--- +title: GroupByLastmod +description: Returns the given page collection grouped by last modification date in descending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g) for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[site configuration]: /configuration/front-matter/#dates + +{{% include "/_common/methods/pages/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 "/_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..6764144d6 --- /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: [] +params: + functions_and_methods: + returnType: page.PagesGroup + signatures: ['PAGES.GroupByParam PARAM [SORT]'] +--- + +{{% include "/_common/methods/pages/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..b05a096d2 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByParamDate.md @@ -0,0 +1,60 @@ +--- +title: GroupByParamDate +description: Returns the given page collection grouped by the given date parameter in descending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g) for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string + +{{% include "/_common/methods/pages/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 "/_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..50e12f085 --- /dev/null +++ b/docs/content/en/methods/pages/GroupByPublishDate.md @@ -0,0 +1,63 @@ +--- +title: GroupByPublishDate +description: Returns the given page collection grouped by publish date in descending order. +categories: [] +keywords: [] +params: + functions_and_methods: + 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](g) for language and region. + +[`time.Format`]: /functions/time/format/ +[layout string]: #layout-string +[site configuration]: /configuration/front-matter/#dates + +{{% include "/_common/methods/pages/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 "/_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..85b3267cd --- /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: [] +params: + functions_and_methods: + 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..6ee3de24d --- /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: [] +params: + functions_and_methods: + 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..ce091c1ab --- /dev/null +++ b/docs/content/en/methods/pages/Next.md @@ -0,0 +1,12 @@ +--- +title: Next +description: Returns the next page in a page collection, relative to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [PAGES.Next PAGE] +--- + +{{% include "/_common/methods/pages/next-and-prev.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..004b9496d --- /dev/null +++ b/docs/content/en/methods/pages/Prev.md @@ -0,0 +1,12 @@ +--- +title: Prev +description: Returns the previous page in a page collection, relative to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGES.Prev PAGE] +--- + +{{% include "/_common/methods/pages/next-and-prev.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..22eeb4dfa --- /dev/null +++ b/docs/content/en/methods/pages/Related.md @@ -0,0 +1,75 @@ +--- +title: Related +description: Returns a collection of pages related to the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + 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: + +```go-html-template {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 }} +``` + +To pass an options map: + +```go-html-template {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 }} +``` + +## 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](g) 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-content/ +[related content configuration]: /configuration/related-content/ diff --git a/docs/content/en/methods/pages/Reverse.md b/docs/content/en/methods/pages/Reverse.md new file mode 100644 index 000000000..23c4b0324 --- /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: [] +params: + functions_and_methods: + 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/_index.md b/docs/content/en/methods/pages/_index.md new file mode 100644 index 000000000..f2495ae49 --- /dev/null +++ b/docs/content/en/methods/pages/_index.md @@ -0,0 +1,8 @@ +--- +title: Pages methods +linkTitle: Pages +description: Use these methods with a collection of Page objects. +categories: [] +keywords: [] +aliases: [/variables/pages] +--- diff --git a/docs/content/en/methods/resource/Colors.md b/docs/content/en/methods/resource/Colors.md new file mode 100644 index 000000000..14d0a40d8 --- /dev/null +++ b/docs/content/en/methods/resource/Colors.md @@ -0,0 +1,174 @@ +--- +title: Colors +description: Applicable to images, returns a slice of the most dominant colors using a simple histogram method. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: '[]images.Color' + signatures: [RESOURCE.Colors] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +The `Resources.Colors` method returns a slice of the most dominant colors in an image, ordered from most dominant to least dominant. This method is fast, but if you also downsize your image you can improve performance by extracting the colors from the scaled image. + +## Methods + +Each color is an object with the following methods: + +### ColorHex + +{{< new-in 0.125.0 />}} + +(`string`) Returns the [hexadecimal color] value, prefixed with a hash sign. + +### Luminance + +{{< new-in 0.125.0 />}} + +(`float64`) Returns the [relative luminance] of the color in the sRGB colorspace in the range [0, 1]. A value of `0` represents the darkest black, while a value of `1` represents the lightest white. + +> [!note] +> Image filters such as [`images.Dither`], [`images.Padding`], and [`images.Text`] accept either hexadecimal color values or `images.Color` objects as arguments. +> +> Hugo renders an `images.Color` object as a hexadecimal color value. + +## Sorting + +As a contrived example, create a table of an image's dominant colors with the most dominant color first, and display the relative luminance of each dominant color: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + <table> + <thead> + <tr> + <th>Color</th> + <th>Relative luminance</th> + </tr> + </thead> + <tbody> + {{ range .Colors }} + <tr> + <td>{{ .ColorHex }}</td> + <td>{{ .Luminance | lang.FormatNumber 4 }}</td> + </tr> + {{ end }} + </tbody> + </table> +{{ end }} +``` + +Hugo renders this to: + +ColorHex|Relative luminance +:--|:-- +`#bebebd`|`0.5145` +`#514947`|`0.0697` +`#768a9a`|`0.2436` +`#647789`|`0.1771` +`#90725e`|`0.1877` +`#a48974`|`0.2704` + +To sort by dominance with the least dominant color first: + +```go-html-template +{{ range .Colors | collections.Reverse }} +``` + +To sort by relative luminance with the darkest color first: + +```go-html-template +{{ range sort .Colors "Luminance" }} +``` + +To sort by relative luminance with the lightest color first, use either of these constructs: + +```go-html-template +{{ range sort .Colors "Luminance" | collections.Reverse }} +{{ range sort .Colors "Luminance" "desc" }} +``` + +## Examples + +### Image borders + +To add a 5 pixel border to an image using the most dominant color: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ $mostDominant := index .Colors 0 }} + {{ $filter := images.Padding 5 $mostDominant }} + {{ with .Filter $filter }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +To add a 5 pixel border to an image using the darkest dominant color: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ $darkest := index (sort .Colors "Luminance") 0 }} + {{ $filter := images.Padding 5 $darkest }} + {{ with .Filter $filter }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` + +### Light text on dark background + +To create a text box where the foreground and background colors are derived from an image's lightest and darkest dominant colors: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ $darkest := index (sort .Colors "Luminance") 0 }} + {{ $lightest := index (sort .Colors "Luminance" "desc") 0 }} + <div style="background: {{ $darkest }};"> + <div style="color: {{ $lightest }};"> + <p>This is light text on a dark background.</p> + </div> + </div> +{{ end }} +``` + +### WCAG contrast ratio + +In the previous example we placed light text on a dark background, but does this color combination conform to [WCAG] guidelines for either the [minimum] or the [enhanced] contrast ratio? + +The WCAG defines the [contrast ratio] as: + +$$contrast\ ratio = { L_1 + 0.05 \over L_2 + 0.05 }$$ + +where $L_1$ is the relative luminance of the lightest color and $L_2$ is the relative luminance of the darkest color. + +Calculate the contrast ratio to determine WCAG conformance: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ $lightest := index (sort .Colors "Luminance" "desc") 0 }} + {{ $darkest := index (sort .Colors "Luminance") 0 }} + {{ $cr := div + (add $lightest.Luminance 0.05) + (add $darkest.Luminance 0.05) + }} + {{ if ge $cr 7.5 }} + {{ printf "The %.2f contrast ratio conforms to WCAG Level AAA." $cr }} + {{ else if ge $cr 4.5 }} + {{ printf "The %.2f contrast ratio conforms to WCAG Level AA." $cr }} + {{ else }} + {{ printf "The %.2f contrast ratio does not conform to WCAG guidelines." $cr }} + {{ end }} +{{ end }} +``` + +[`images.Dither`]: /functions/images/dither/ +[`images.Padding`]: /functions/images/padding/ +[`images.Text`]: /functions/images/text/ +[contrast ratio]: https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio +[enhanced]: https://www.w3.org/WAI/WCAG22/quickref/?showtechniques=145#contrast-enhanced +[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color +[minimum]: https://www.w3.org/WAI/WCAG22/quickref/?showtechniques=145#contrast-minimum +[relative luminance]: https://www.w3.org/TR/WCAG21/#dfn-relative-luminance +[WCAG]: https://en.wikipedia.org/wiki/Web_Content_Accessibility_Guidelines diff --git a/docs/content/en/methods/resource/Content.md b/docs/content/en/methods/resource/Content.md new file mode 100644 index 000000000..2c2c12d3a --- /dev/null +++ b/docs/content/en/methods/resource/Content.md @@ -0,0 +1,60 @@ +--- +title: Content +description: Returns the content of the given resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: any + signatures: [RESOURCE.Content] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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/ + +```text {file="assets/quotations/kipling.txt"} +He travels the fastest who travels alone. +``` + +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 }} +``` diff --git a/docs/content/en/methods/resource/Crop.md b/docs/content/en/methods/resource/Crop.md new file mode 100644 index 000000000..97b3b95d3 --- /dev/null +++ b/docs/content/en/methods/resource/Crop.md @@ -0,0 +1,42 @@ +--- +title: Crop +description: Applicable to images, returns an image resource cropped to the given dimensions without resizing. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Crop SPEC] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 "/_common/methods/resource/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..0709ca50a --- /dev/null +++ b/docs/content/en/methods/resource/Data.md @@ -0,0 +1,66 @@ +--- +title: Data +description: Applicable to resources returned by the resources.GetRemote function, returns information from the HTTP response. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/ + +## Example + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ $opts := dict "responseHeaders" (slice "Server") }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else with .Value }} + {{ with .Data }} + {{ .ContentLength }} → 42764 + {{ .ContentType }} → image/jpeg + {{ .Headers }} → map[Server:[Netlify]] + {{ .Status }} → 200 OK + {{ .StatusCode }} → 200 + {{ .TransferEncoding }} → [] + {{ end }} + {{ else }} + {{ errorf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +## Methods + +### ContentLength + +(`int`) The content length in bytes. + +### ContentType + +(`string`) The content type. + +### Headers + +(`map[string][]string`) A map of response headers matching those requested in the [`responseHeaders`] option passed to the `resources.GetRemote` function. The header name matching is case-insensitive. In most cases there will be one value per header key. + +### Status + +(`string`) The HTTP status text. + +### StatusCode + +(`int`) The HTTP status code. + +### TransferEncoding + +(`string`) The transfer encoding. + +[`resources.GetRemote`]: /functions/resources/getremote/ +[`responseHeaders`]: /functions/resources/getremote/#responseheaders diff --git a/docs/content/en/methods/resource/Err.md b/docs/content/en/methods/resource/Err.md new file mode 100644 index 000000000..591af8266 --- /dev/null +++ b/docs/content/en/methods/resource/Err.md @@ -0,0 +1,60 @@ +--- +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: [] +params: + functions_and_methods: + returnType: resource.resourceError + signatures: [RESOURCE.Err] +expiryDate: 2027-01-16 # deprecated 2025-01-16 in v0.141.0 +--- + +{{< deprecated-in 0.141.0 >}} +Use the `try` statement instead. See [example]. + +[example]: /functions/go-template/try/#example +{{< /deprecated-in >}} + +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. diff --git a/docs/content/en/methods/resource/Exif.md b/docs/content/en/methods/resource/Exif.md new file mode 100644 index 000000000..443a0ee1a --- /dev/null +++ b/docs/content/en/methods/resource/Exif.md @@ -0,0 +1,82 @@ +--- +title: Exif +description: Applicable to JPEG, PNG, TIFF, and WebP images, returns an EXIF object containing image metadata. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: exif.ExifInfo + signatures: [RESOURCE.Exif] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +Applicable to JPEG, PNG, TIFF, and WebP 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. See [configure imaging]. + +[configure imaging]: /configuration/imaging/#exif-data + +## 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 }} +``` + +[exif]: https://en.wikipedia.org/wiki/Exif +[`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..82c696c91 --- /dev/null +++ b/docs/content/en/methods/resource/Fill.md @@ -0,0 +1,42 @@ +--- +title: Fill +description: Applicable to images, returns an image resource cropped and resized to the given dimensions. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Fill SPEC] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 "/_common/methods/resource/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..b83c3d8cb --- /dev/null +++ b/docs/content/en/methods/resource/Filter.md @@ -0,0 +1,66 @@ +--- +title: Filter +description: Applicable to images, applies one or more image filters to the given image resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Filter FILTER...] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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/ + +## 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..7b416c4a1 --- /dev/null +++ b/docs/content/en/methods/resource/Fit.md @@ -0,0 +1,42 @@ +--- +title: Fit +description: Applicable to images, returns an image resource downscaled to fit the given dimensions while maintaining aspect ratio. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Fit SPEC] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 "/_common/methods/resource/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..cc131378a --- /dev/null +++ b/docs/content/en/methods/resource/Height.md @@ -0,0 +1,26 @@ +--- +title: Height +description: Applicable to images, returns the height of the given resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [RESOURCE.Height] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +```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 }} +``` diff --git a/docs/content/en/methods/resource/MediaType.md b/docs/content/en/methods/resource/MediaType.md new file mode 100644 index 000000000..7721f69ba --- /dev/null +++ b/docs/content/en/methods/resource/MediaType.md @@ -0,0 +1,66 @@ +--- +title: MediaType +description: Returns a media type object for the given resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: media.Type + signatures: [RESOURCE.MediaType] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 }} +``` + +### FirstSuffix.Suffix + +(`string`) The first of the possible file suffixes for the resource's media type. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .MediaType.FirstSuffix.Suffix }} → jpg +{{ end }} +``` diff --git a/docs/content/en/methods/resource/Name.md b/docs/content/en/methods/resource/Name.md new file mode 100644 index 000000000..c678c96c9 --- /dev/null +++ b/docs/content/en/methods/resource/Name.md @@ -0,0 +1,88 @@ +--- +title: Name +description: Returns the name of the given resource as optionally defined in front matter, falling back to its file path. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [RESOURCE.Name] +--- + +The value returned by the `Name` method on a `Resource` object depends on the resource type. + +## Global resource + +With a [global resource](g), the `Name` method returns the path to the resource, relative to the `assets` directory. + +```text +assets/ +└── images/ + └── Sunrise in Bryce Canyon.jpg +``` + +```go-html-template +{{ with resources.Get "images/Sunrise in Bryce Canyon.jpg" }} + {{ .Name }} → /images/Sunrise in Bryce Canyon.jpg +{{ end }} +``` + +## Page resource + +With a [page resource](g), if you create an element in the `resources` array in front matter, the `Name` method returns the value of the `name` parameter. + +```text +content/ +├── example/ +│ ├── images/ +│ │ └── a.jpg +│ └── index.md +└── _index.md +``` + +{{< code-toggle file=content/example/index.md fm=true >}} +title = 'Example' +[[resources]] +src = 'images/a.jpg' +name = 'Sunrise in Bryce Canyon' +{{< /code-toggle >}} + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + {{ .Name }} → Sunrise in Bryce Canyon +{{ end }} +``` + +You can also capture the image by specifying its `name` instead of its path: + +```go-html-template +{{ with .Resources.Get "Sunrise in Bryce Canyon" }} + {{ .Name }} → Sunrise in Bryce Canyon +{{ end }} +``` + +If you do not create an element in the `resources` array in front matter, the `Name` method returns the file path, relative to the page bundle. + +```text +content/ +├── example/ +│ ├── images/ +│ │ └── Sunrise in Bryce Canyon.jpg +│ └── index.md +└── _index.md +``` + +```go-html-template +{{ with .Resources.Get "images/Sunrise in Bryce Canyon.jpg" }} + {{ .Name }} → images/Sunrise in Bryce Canyon.jpg +{{ end }} +``` +## Remote resource + +With a [remote resource](g), 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 }} +``` diff --git a/docs/content/en/methods/resource/Params.md b/docs/content/en/methods/resource/Params.md new file mode 100644 index 000000000..38f2ef6c2 --- /dev/null +++ b/docs/content/en/methods/resource/Params.md @@ -0,0 +1,61 @@ +--- +title: Params +description: Returns a map of resource parameters as defined in front matter. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: map + signatures: [RESOURCE.Params] +--- + +Use the `Params` method with [page resources](g). It is not applicable to either [global resources](g) or [remote resources](g). + +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..a8ec2d323 --- /dev/null +++ b/docs/content/en/methods/resource/Permalink.md @@ -0,0 +1,20 @@ +--- +title: Permalink +description: Publishes the given resource and returns its permalink. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [RESOURCE.Permalink] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +The `Permalink` method on a `Resource` object writes the resource to the publish directory, typically `public`, and returns its [permalink](g). + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Permalink }} → https://example.org/images/a.jpg +{{ end }} +``` diff --git a/docs/content/en/methods/resource/Process.md b/docs/content/en/methods/resource/Process.md new file mode 100644 index 000000000..fb27da54e --- /dev/null +++ b/docs/content/en/methods/resource/Process.md @@ -0,0 +1,60 @@ +--- +title: Process +description: Applicable to images, returns an image resource processed with the given specification. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Process SPEC] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 "/_common/methods/resource/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..0ecdf7e74 --- /dev/null +++ b/docs/content/en/methods/resource/Publish.md @@ -0,0 +1,32 @@ +--- +title: Publish +description: Publishes the given resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: nil + signatures: [RESOURCE.Publish] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +The `Publish` method on a `Resource` object writes the resource to the publish directory, typically `public`. + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .Publish }} +{{ end }} +``` + +The `Permalink` and `RelPermalink` methods also publish a resource. `Publish` is a convenience method for publishing without a return value. For example, this: + +```go-html-template +{{ $resource.Publish }} +``` + +Instead of this: + +```go-html-template +{{ $noop := $resource.Permalink }} +``` diff --git a/docs/content/en/methods/resource/RelPermalink.md b/docs/content/en/methods/resource/RelPermalink.md new file mode 100644 index 000000000..d4c907bff --- /dev/null +++ b/docs/content/en/methods/resource/RelPermalink.md @@ -0,0 +1,20 @@ +--- +title: RelPermalink +description: Publishes the given resource and returns its relative permalink. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [RESOURCE.RelPermalink] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +The `Permalink` method on a `Resource` object writes the resource to the publish directory, typically `public`, and returns its [relative permalink](g). + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ .RelPermalink }} → /images/a.jpg +{{ end }} +``` diff --git a/docs/content/en/methods/resource/Resize.md b/docs/content/en/methods/resource/Resize.md new file mode 100644 index 000000000..93c029ba6 --- /dev/null +++ b/docs/content/en/methods/resource/Resize.md @@ -0,0 +1,44 @@ +--- +title: Resize +description: Applicable to images, returns an image resource resized to the given width and/or height. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: images.ImageResource + signatures: [RESOURCE.Resize SPEC] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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 "/_common/methods/resource/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..0ea9c0cf9 --- /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: [] +params: + functions_and_methods: + returnType: string + signatures: [RESOURCE.ResourceType] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +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: + +```go-html-template {file="layouts/lessons/single.html"} +{{ range .Resources.ByType "page" }} + {{ .Content }} +{{ end }} +``` diff --git a/docs/content/en/methods/resource/Title.md b/docs/content/en/methods/resource/Title.md new file mode 100644 index 000000000..c02d29ff8 --- /dev/null +++ b/docs/content/en/methods/resource/Title.md @@ -0,0 +1,81 @@ +--- +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: [] +params: + functions_and_methods: + returnType: string + signatures: [RESOURCE.Title] +--- + +The value returned by the `Title` method on a `Resource` object depends on the resource type. + +## Global resource + +With a [global resource](g), the `Title` method returns the path to the resource, relative to the `assets` directory. + +```text +assets/ +└── images/ + └── Sunrise in Bryce Canyon.jpg +``` + +```go-html-template +{{ with resources.Get "images/Sunrise in Bryce Canyon.jpg" }} + {{ .Title }} → /images/Sunrise in Bryce Canyon.jpg +{{ end }} +``` + +## Page resource + +With a [page resource](g), if you create an element in the `resources` array in front matter, the `Title` method returns the value of the `title` parameter. + +```text +content/ +├── example/ +│ ├── images/ +│ │ └── a.jpg +│ └── index.md +└── _index.md +``` + +{{< code-toggle file=content/example/index.md fm=true >}} +title = 'Example' +[[resources]] +src = 'images/a.jpg' +title = 'A beautiful sunrise in Bryce Canyon' +{{< /code-toggle >}} + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + {{ .Title }} → A beautiful sunrise in Bryce Canyon +{{ end }} +``` + +If you do not create an element in the `resources` array in front matter, the `Title` method returns the file path, relative to the page bundle. + +```text +content/ +├── example/ +│ ├── images/ +│ │ └── Sunrise in Bryce Canyon.jpg +│ └── index.md +└── _index.md +``` + +```go-html-template +{{ with .Resources.Get "Sunrise in Bryce Canyon.jpg" }} + {{ .Title }} → images/Sunrise in Bryce Canyon.jpg +{{ end }} +``` + +## Remote resource + +With a [remote resource](g), 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 }} +``` diff --git a/docs/content/en/methods/resource/Width.md b/docs/content/en/methods/resource/Width.md new file mode 100644 index 000000000..e1b43f44c --- /dev/null +++ b/docs/content/en/methods/resource/Width.md @@ -0,0 +1,26 @@ +--- +title: Width +description: Applicable to images, returns the width of the given resource. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [RESOURCE.Width] +--- + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +```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 }} +``` diff --git a/docs/content/en/methods/resource/_index.md b/docs/content/en/methods/resource/_index.md new file mode 100644 index 000000000..edfbc5b14 --- /dev/null +++ b/docs/content/en/methods/resource/_index.md @@ -0,0 +1,7 @@ +--- +title: Resource methods +linkTitle: Resource +description: Use these methods with global, page, and remote Resource objects. +categories: [] +keywords: [] +--- diff --git a/docs/content/en/methods/shortcode/Get.md b/docs/content/en/methods/shortcode/Get.md new file mode 100644 index 000000000..b9c01cfc4 --- /dev/null +++ b/docs/content/en/methods/shortcode/Get.md @@ -0,0 +1,46 @@ +--- +title: Get +description: Returns the value of the given argument. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: any + signatures: [SHORTCODE.Get ARG] +--- + +Specify the argument by position or by name. When calling a shortcode within Markdown, use either positional or named argument, but not both. + +> [!note] +> Some shortcodes support positional arguments, some support named arguments, and others support both. Refer to the shortcode's documentation for usage details. + +## Positional arguments + +This shortcode call uses positional arguments: + +```text {file="content/about.md"} +{{</* myshortcode "Hello" "world" */>}} +``` + +To retrieve arguments by position: + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ printf "%s %s." (.Get 0) (.Get 1) }} → Hello world. +``` + +## Named arguments + +This shortcode call uses named arguments: + +```text {file="content/about.md"} +{{</* myshortcode greeting="Hello" firstName="world" */>}} +``` + +To retrieve arguments by name: + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ printf "%s %s." (.Get "greeting") (.Get "firstName") }} → Hello world. +``` + +> [!note] +> Argument names are case-sensitive. diff --git a/docs/content/en/methods/shortcode/Inner.md b/docs/content/en/methods/shortcode/Inner.md new file mode 100644 index 000000000..cdce4c1c3 --- /dev/null +++ b/docs/content/en/methods/shortcode/Inner.md @@ -0,0 +1,143 @@ +--- +title: Inner +description: Returns the content between opening and closing shortcode tags, applicable when the shortcode call includes a closing tag. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [SHORTCODE.Inner] +--- + +This content: + +```text {file="content/services.md"} +{{</* card title="Product Design" */>}} +We design the **best** widgets in the world. +{{</* /card */>}} +``` + +With this shortcode: + +```go-html-template {file="layouts/shortcodes/card.html"} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + {{ .Inner | strings.TrimSpace }} + </div> +</div> +``` + +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 [`strings.TrimSpace`] function as shown above to remove carriage returns and newlines. + +> [!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. + +## Use RenderString + +Let's modify the example above to pass the value returned by `Inner` through the [`RenderString`] method on the `Page` object: + +```go-html-template {file="layouts/shortcodes/card.html"} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + {{ .Inner | strings.TrimSpace | .Page.RenderString }} + </div> +</div> +``` + +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]. + +## Alternative notation + +Instead of calling the shortcode with the `{{</* */>}}` notation, use the `{{%/* */%}}` notation: + +```text {file="content/services.md"} +{{%/* card title="Product Design" */%}} +We design the **best** widgets in the world. +{{%/* /card */%}} +``` + +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. + +```go-html-template {file="layouts/shortcodes/card.html"} +<div class="card"> + {{ with .Get "title" }} + <div class="card-title">{{ . }}</div> + {{ end }} + <div class="card-content"> + + {{ .Inner | strings.TrimSpace }} + </div> +</div> +``` + +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"> +- {{ .Inner | strings.TrimSpace | .Page.RenderString }} ++ ++ {{ .Inner | strings.TrimSpace }} + </div> + </div> +``` + +> [!note] +> Don't process the `Inner` value with `RenderString` or `markdownify` when using [Markdown notation] to call the shortcode. + +[`markdownify`]: /functions/transform/markdownify/ +[`RenderString`]: /methods/page/renderstring/ +[`strings.TrimSpace`]: /functions/strings/trimspace/ +[CommonMark]: https://spec.commonmark.org/current/ +[details]: /methods/page/renderstring/ +[indentation]: https://spec.commonmark.org/0.30/#indented-code-blocks +[Markdown notation]: /content-management/shortcodes/#notation +[raw HTML blocks]: https://spec.commonmark.org/0.31.2/#html-blocks +[security model]: /about/security/ diff --git a/docs/content/en/methods/shortcode/InnerDeindent.md b/docs/content/en/methods/shortcode/InnerDeindent.md new file mode 100644 index 000000000..0b8c8e2d8 --- /dev/null +++ b/docs/content/en/methods/shortcode/InnerDeindent.md @@ -0,0 +1,98 @@ +--- +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: [] +params: + functions_and_methods: + 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: + +```text {file="content/about.md"} +- Gallery one + + {{</* gallery */>}} +  +  + {{</* /gallery */>}} + +- Gallery two + + {{</* gallery */>}} +  +  + {{</* /gallery */>}} +``` + +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`: + +```go-html-template {file="layouts/shortcodes/gallery.html"} +<div class="gallery"> + {{ .Inner | strings.TrimSpace | .Page.RenderString }} +</div> +``` + +Hugo renders the Markdown to: + +```html +<ul> + <li> + <p>Gallery one</p> + <div class="gallery"> + <pre><code> +  + </code></pre> + </div> + </li> + <li> + <p>Gallery two</p> + <div class="gallery"> + <pre><code> +  + </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: + +```go-html-template {file="layouts/shortcodes/gallery.html"} +<div class="gallery"> + {{ .InnerDeindent | strings.TrimSpace | .Page.RenderString }} +</div> +``` + +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..1e0a7f00e --- /dev/null +++ b/docs/content/en/methods/shortcode/IsNamedParams.md @@ -0,0 +1,29 @@ +--- +title: IsNamedParams +description: Reports whether the shortcode call uses named arguments. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [SHORTCODE.IsNamedParams] +--- + +To support both positional and named arguments when calling a shortcode, use the `IsNamedParams` method to determine how the shortcode was called. + +With this shortcode template: + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ if .IsNamedParams }} + {{ printf "%s %s." (.Get "greeting") (.Get "firstName") }} +{{ else }} + {{ printf "%s %s." (.Get 0) (.Get 1) }} +{{ end }} +``` + +Both of these calls return the same value: + +```text {file="content/about.md"} +{{</* myshortcode greeting="Hello" firstName="world" */>}} +{{</* myshortcode "Hello" "world" */>}} +``` diff --git a/docs/content/en/methods/shortcode/Name.md b/docs/content/en/methods/shortcode/Name.md new file mode 100644 index 000000000..b5f9b6c17 --- /dev/null +++ b/docs/content/en/methods/shortcode/Name.md @@ -0,0 +1,27 @@ +--- +title: Name +description: Returns the shortcode file name, excluding the file extension. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SHORTCODE.Name] +--- + +The `Name` method is useful for error reporting. For example, if your shortcode requires a "greeting" argument: + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ $greeting := "" }} +{{ with .Get "greeting" }} + {{ $greeting = . }} +{{ else }} + {{ errorf "The %q shortcode requires a 'greeting' argument. See %s" .Name .Position }} +{{ end }} +``` + +In the absence of a "greeting" argument, Hugo will throw an error message and fail the build: + +```text +ERROR The "myshortcode" shortcode requires a 'greeting' argument. 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..def0c016f --- /dev/null +++ b/docs/content/en/methods/shortcode/Ordinal.md @@ -0,0 +1,52 @@ +--- +title: Ordinal +description: Returns the zero-based ordinal of the shortcode in relation to its parent. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. + +> [!note] +> Hugo increments the ordinal with each shortcode call, regardless of the specific shortcode type. This means that the ordinal value is tracked sequentially across all shortcodes within a given page. + +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: + +```text {file="content/about.md"} +{{</* img src="images/a.jpg" */>}} + +{{</* img src="images/b.jpg" */>}} +``` + +This shortcode performs error checking, then renders an HTML `img` element with a unique `id` attribute: + +```go-html-template {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' argument. See %s" .Name .Position }} +{{ end }} +``` + +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/ diff --git a/docs/content/en/methods/shortcode/Page.md b/docs/content/en/methods/shortcode/Page.md new file mode 100644 index 000000000..774caf9fc --- /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: [] +params: + functions_and_methods: + 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' +publication_year = 1862 +isbn = '978-0451419439' +{{< /code-toggle >}} + +Calling this shortcode: + +```text +{{</* book-details */>}} +``` + +We can access the front matter values using the `Page` method: + +```go-html-template {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> +``` diff --git a/docs/content/en/methods/shortcode/Params.md b/docs/content/en/methods/shortcode/Params.md new file mode 100644 index 000000000..f001e737f --- /dev/null +++ b/docs/content/en/methods/shortcode/Params.md @@ -0,0 +1,32 @@ +--- +title: Params +description: Returns a collection of the shortcode arguments. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: any + signatures: [SHORTCODE.Params] +--- + +When you call a shortcode using positional arguments, the `Params` method returns a slice. + +```text {file="content/about.md"} +{{</* myshortcode "Hello" "world" */>}} +``` + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ index .Params 0 }} → Hello +{{ index .Params 1 }} → world +``` + +When you call a shortcode using named arguments, the `Params` method returns a map. + +```text {file="content/about.md"} +{{</* myshortcode greeting="Hello" name="world" */>}} +``` + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ .Params.greeting }} → Hello +{{ .Params.name }} → world +``` diff --git a/docs/content/en/methods/shortcode/Parent.md b/docs/content/en/methods/shortcode/Parent.md new file mode 100644 index 000000000..91c445d2a --- /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: [] +params: + functions_and_methods: + returnType: hugolib.ShortcodeWithPage + signatures: [SHORTCODE.Parent] +--- + +This is useful for inheritance of common shortcode arguments from the root. + +In this contrived example, the "greeting" shortcode is the parent, and the "now" shortcode is child. + +```text {file="content/welcome.md"} +{{</* greeting dateFormat="Jan 2, 2006" */>}} +Welcome. Today is {{</* now */>}}. +{{</* /greeting */>}} +``` + +```go-html-template {file="layouts/shortcodes/greeting.html"} +<div class="greeting"> + {{ .Inner | strings.TrimSpace | .Page.RenderString }} +</div> +``` + +```go-html-template {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 -}} +``` + +The "now" shortcode formats the current time using: + +1. The `dateFormat` argument passed to the "now" shortcode, if present +1. The `dateFormat` argument passed to the "greeting" shortcode, if present +1. 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..24810e825 --- /dev/null +++ b/docs/content/en/methods/shortcode/Position.md @@ -0,0 +1,30 @@ +--- +title: Position +description: Returns the file name and position from which the shortcode was called. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: text.Position + signatures: [SHORTCODE.Position] +--- + +The `Position` method is useful for error reporting. For example, if your shortcode requires a "greeting" argument: + +```go-html-template {file="layouts/shortcodes/myshortcode.html"} +{{ $greeting := "" }} +{{ with .Get "greeting" }} + {{ $greeting = . }} +{{ else }} + {{ errorf "The %q shortcode requires a 'greeting' argument. See %s" .Name .Position }} +{{ end }} +``` + +In the absence of a "greeting" argument, Hugo will throw an error message and fail the build: + +```text +ERROR The "myshortcode" shortcode requires a 'greeting' argument. See "/home/user/project/content/about.md:11:1" +``` + +> [!note] +> The position can be expensive to calculate. Limit its use to error reporting. diff --git a/docs/content/en/methods/shortcode/Ref.md b/docs/content/en/methods/shortcode/Ref.md new file mode 100644 index 000000000..3a877d568 --- /dev/null +++ b/docs/content/en/methods/shortcode/Ref.md @@ -0,0 +1,37 @@ +--- +title: Ref +description: Returns the absolute URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SHORTCODE.Ref OPTIONS] +--- + +## Usage + +The `Ref` method accepts a single argument: an options map. + +## Options + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The following examples show the rendered output for a page on the English 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 +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} diff --git a/docs/content/en/methods/shortcode/RelRef.md b/docs/content/en/methods/shortcode/RelRef.md new file mode 100644 index 000000000..273705a95 --- /dev/null +++ b/docs/content/en/methods/shortcode/RelRef.md @@ -0,0 +1,37 @@ +--- +title: RelRef +description: Returns the relative URL of the page with the given path, language, and output format. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SHORTCODE.RelRef OPTIONS] +--- + +## Usage + +The `RelRef` method accepts a single argument: an options map. + +## Options + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The following examples show the rendered output for a page on the English 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 +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} diff --git a/docs/content/en/methods/shortcode/Scratch.md b/docs/content/en/methods/shortcode/Scratch.md new file mode 100644 index 000000000..6efec2097 --- /dev/null +++ b/docs/content/en/methods/shortcode/Scratch.md @@ -0,0 +1,21 @@ +--- +title: Scratch +description: Returns a "scratch pad" to store and manipulate data, scoped to the current shortcode. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Scratch + signatures: [SHORTCODE.Scratch] +expiryDate: 2026-11-18 # deprecated 2024-11-18 (soft) +--- + +{{< deprecated-in 0.139.0 >}} +Use the [`SHORTCODE.Store`] method instead. + +This is a soft deprecation. This method will be removed in a future release, but the removal date has not been established. Although Hugo will not emit a warning if you continue to use this method, you should begin using `SHORTCODE.Store` as soon as possible. + +Beginning with v0.139.0 the `SHORTCODE.Scratch` method is aliased to `SHORTCODE.Store`. + +[`SHORTCODE.Store`]: /methods/shortcode/store/ +{{< /deprecated-in >}} diff --git a/docs/content/en/methods/shortcode/Site.md b/docs/content/en/methods/shortcode/Site.md new file mode 100644 index 000000000..4c5a9a9b5 --- /dev/null +++ b/docs/content/en/methods/shortcode/Site.md @@ -0,0 +1,18 @@ +--- +title: Site +description: Returns the Site object. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/Store.md b/docs/content/en/methods/shortcode/Store.md new file mode 100644 index 000000000..76cb9237d --- /dev/null +++ b/docs/content/en/methods/shortcode/Store.md @@ -0,0 +1,24 @@ +--- +title: Store +description: Returns a "scratch pad" to store and manipulate data, scoped to the current shortcode. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Scratch + signatures: [SHORTCODE.Store] +--- + +{{< new-in 0.139.0 />}} + +Use the `Store` method to create a [scratch pad](g) to store and manipulate data, scoped to the current shortcode. To create a scratch pad with a different [scope](g), refer to the [scope](#scope) section below. + +> [!note] +> With the introduction of the [`newScratch`] function, and the ability to [assign values to template variables] after initialization, the `Store` method within a shortcode is mostly obsolete. + +{{% include "_common/store-methods.md" %}} + +{{% include "_common/scratch-pad-scope.md" %}} + +[`newScratch`]: /functions/collections/newScratch/ +[assign values to template variables]: https://go.dev/doc/go1.11#texttemplatepkgtexttemplate diff --git a/docs/content/en/methods/shortcode/_index.md b/docs/content/en/methods/shortcode/_index.md new file mode 100644 index 000000000..0064f42aa --- /dev/null +++ b/docs/content/en/methods/shortcode/_index.md @@ -0,0 +1,8 @@ +--- +title: Shortcode methods +linkTitle: Shortcode +description: Use these methods in your shortcode templates. +categories: [] +keywords: [] +aliases: [/variables/shortcodes] +--- diff --git a/docs/content/en/methods/site/AllPages.md b/docs/content/en/methods/site/AllPages.md new file mode 100644 index 000000000..90cceee8c --- /dev/null +++ b/docs/content/en/methods/site/AllPages.md @@ -0,0 +1,22 @@ +--- +title: AllPages +description: Returns a collection of all pages in all languages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [SITE.AllPages] +--- + +This method returns all page [kinds](g) in all languages, in the [default sort order](g). 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/ + +```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..3644443cb --- /dev/null +++ b/docs/content/en/methods/site/BaseURL.md @@ -0,0 +1,32 @@ +--- +title: BaseURL +description: Returns the base URL as defined in the site configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. + +[`absLangURL`]: /functions/urls/absLangURL/ +[`absURL`]: /functions/urls/absURL/ +[`relLangURL`]: /functions/urls/relLangURL/ +[`relURL`]: /functions/urls/relURL/ diff --git a/docs/content/en/methods/site/BuildDrafts.md b/docs/content/en/methods/site/BuildDrafts.md new file mode 100644 index 000000000..4beceeb6b --- /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: [] +params: + functions_and_methods: + 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..d1b4d1f42 --- /dev/null +++ b/docs/content/en/methods/site/Config.md @@ -0,0 +1,52 @@ +--- +title: Config +description: Returns a subset of the site configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.SiteConfig + signatures: [SITE.Config] +--- + +The `Config` method on a `Site` object provides access to a subset of the site configuration, specifically the `services` and `privacy` keys. + +## Services + +See [configure services](/configuration/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 + +See [configure privacy](/configuration/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..dd8bdb4a3 --- /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: [] +params: + functions_and_methods: + 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..296851874 --- /dev/null +++ b/docs/content/en/methods/site/Data.md @@ -0,0 +1,103 @@ +--- +title: Data +description: Returns a data structure composed from the files in the data directory. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. + +> [!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. + +Consider this `data` directory: + +```text +data/ +├── books/ +│ ├── fiction.yaml +│ └── nonfiction.yaml +├── films.json +├── paintings.xml +└── sculptures.toml +``` + +And these data files: + +```yaml {file="data/books/fiction.yaml"} +- title: The Hunchback of Notre Dame + author: Victor Hugo + isbn: 978-0140443530 +- title: Les Misérables + author: Victor Hugo + isbn: 978-0451419439 +``` + +```yaml {file="data/books/nonfiction.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 +``` + +Access the data by [chaining](g) the [identifiers](g): + +```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. For example: + +```go-html-template +{{ index .Site.Data.books "historical-fiction" }} +``` + +[`index`]: /functions/collections/indexfunction/ +[`transform.Unmarshal`]: /functions/transform/unmarshal/ +[mounted]: /configuration/module/#mounts diff --git a/docs/content/en/methods/site/DisqusShortname.md b/docs/content/en/methods/site/DisqusShortname.md new file mode 100644 index 000000000..de679fd7e --- /dev/null +++ b/docs/content/en/methods/site/DisqusShortname.md @@ -0,0 +1,17 @@ +--- +title: DisqusShortname +description: Returns the Disqus shortname as defined in the site configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SITE.DisqusShortname] +expiryDate: 2025-10-30 # deprecated 2023-10-30 in v0.120.0 +--- + +{{< 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..2a3bd7d59 --- /dev/null +++ b/docs/content/en/methods/site/GetPage.md @@ -0,0 +1,105 @@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [SITE.GetPage PATH] +--- + +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 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 template, use the `GetPage` method on a `Site` object to render all the images in the headless [page bundle](g): + +```go-html-template +{{ with .Site.GetPage "/headless" }} + {{ range .Resources.ByType "image" }} + <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> + {{ end }} +{{ end }} +``` diff --git a/docs/content/en/methods/site/GoogleAnalytics.md b/docs/content/en/methods/site/GoogleAnalytics.md new file mode 100644 index 000000000..e4d28bcce --- /dev/null +++ b/docs/content/en/methods/site/GoogleAnalytics.md @@ -0,0 +1,17 @@ +--- +title: GoogleAnalytics +description: Returns the Google Analytics tracking ID as defined in the site configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SITE.GoogleAnalytics] +expiryDate: 2025-10-30 # deprecated 2023-10-30 in v0.120.0 +--- + +{{< 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..19ab61747 --- /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: [] +params: + functions_and_methods: + returnType: page.Page + 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..cddd18818 --- /dev/null +++ b/docs/content/en/methods/site/IsDevelopment.md @@ -0,0 +1,17 @@ +--- +title: IsDevelopment +description: Reports whether the current running environment is “development”. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [SITE.IsDevelopment] +expiryDate: 2025-10-30 # deprecated 2023-10-30 in v0.120.0 +--- + +{{< 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..3f9723f1c --- /dev/null +++ b/docs/content/en/methods/site/IsMultiLingual.md @@ -0,0 +1,17 @@ +--- +title: IsMultiLingual +description: Reports whether there are two or more configured languages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [SITE.IsMultiLingual] +expiryDate: 2026-03-16 # deprecated 2024-03-16 in 0.124.0 +--- + +{{< deprecated-in 0.124.0 >}} +Use [`hugo.IsMultilingual`] instead. + +[`hugo.IsMultilingual`]: /functions/hugo/ismultilingual/ +{{< /deprecated-in >}} diff --git a/docs/content/en/methods/site/IsServer.md b/docs/content/en/methods/site/IsServer.md new file mode 100644 index 000000000..8b09c8492 --- /dev/null +++ b/docs/content/en/methods/site/IsServer.md @@ -0,0 +1,17 @@ +--- +title: IsServer +description: Reports whether the built-in development server is running. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [SITE.IsServer] +expiryDate: 2025-10-30 # deprecated 2023-10-30 in v0.120.0 +--- + +{{< 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..31f15b8cb --- /dev/null +++ b/docs/content/en/methods/site/Language.md @@ -0,0 +1,80 @@ +--- +title: Language +description: Returns the language object for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: langs.Language + signatures: [SITE.Language] +--- + +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. Falls back to `Lang` if not defined. + +```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="{{ .Site.Language.LanguageCode }}" + dir="{{ or .Site.Language.LanguageDirection `ltr` }} +> +``` + +[details]: /methods/page/language/ +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 diff --git a/docs/content/en/methods/site/LanguagePrefix.md b/docs/content/en/methods/site/LanguagePrefix.md new file mode 100644 index 000000000..81a5e8607 --- /dev/null +++ b/docs/content/en/methods/site/LanguagePrefix.md @@ -0,0 +1,51 @@ +--- +title: LanguagePrefix +description: Returns the URL language prefix, if any, for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..056d6193a --- /dev/null +++ b/docs/content/en/methods/site/Languages.md @@ -0,0 +1,58 @@ +--- +title: Languages +description: Returns a collection of language objects for all sites, ordered by language weight. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 inspect the data structure: + +```go-html-template +<pre>{{ debug.Dump .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..e02937bf1 --- /dev/null +++ b/docs/content/en/methods/site/LastChange.md @@ -0,0 +1,17 @@ +--- +title: LastChange +description: Returns the last modification date of site content. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: time.Time + signatures: [SITE.LastChange] +expiryDate: 2026-02-19 # deprecated 2024-02-19 in v0.123.0 +--- + +{{< deprecated-in 0.123.0 >}} +Use [`.Site.Lastmod`] instead. + +[`.Site.Lastmod`]: /methods/site/lastmod/ +{{< /deprecated-in >}} diff --git a/docs/content/en/methods/site/Lastmod.md b/docs/content/en/methods/site/Lastmod.md new file mode 100644 index 000000000..38f6da2fa --- /dev/null +++ b/docs/content/en/methods/site/Lastmod.md @@ -0,0 +1,23 @@ +--- +title: Lastmod +description: Returns the last modification date of site content. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: time.Time + signatures: [SITE.Lastmod] +--- + +{{< new-in 0.123.0 />}} + +The `Lastmod` method on a `Site` object returns a [`time.Time`] value. Use this with time [functions] and [methods]. For example: + +```go-html-template +{{ .Site.Lastmod | time.Format ":date_long" }} → January 31, 2024 + +``` + +[`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..bee4f2d57 --- /dev/null +++ b/docs/content/en/methods/site/MainSections.md @@ -0,0 +1,54 @@ +--- +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: [] +params: + functions_and_methods: + returnType: '[]string' + signatures: [SITE.MainSections] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +mainSections = ['books','films'] +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.MainSections }} → [books films] +``` + +If `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 `mainSections` in their site configuration. + +Then your home 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..398a9b022 --- /dev/null +++ b/docs/content/en/methods/site/Menus.md @@ -0,0 +1,89 @@ +--- +title: Menus +description: Returns a collection of menu objects for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + 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. + +A site can have multiple menus. For example, a main menu and a footer menu: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Home' +pageRef = '/' +weight = 10 + +[[menus.main]] +name = 'Books' +pageRef = '/books' +weight = 20 + +[[menus.main]] +name = 'Films' +pageRef = '/films' +weight = 30 + +[[menus.footer]] +name = 'Legal' +pageRef = '/legal' +weight = 10 + +[[menus.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. + +[`partial`]: /functions/partials/include/ +[`partialCached`]: /functions/partials/includecached/ +[menu templates]: /templates/menu/ +[menus]: /content-management/menus/ diff --git a/docs/content/en/methods/site/Pages.md b/docs/content/en/methods/site/Pages.md new file mode 100644 index 000000000..a6ba5e029 --- /dev/null +++ b/docs/content/en/methods/site/Pages.md @@ -0,0 +1,22 @@ +--- +title: Pages +description: Returns a collection of all pages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [SITE.Pages] +--- + +This method returns all page [kinds](g) in the current language, in the [default sort order](g). 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/ + +```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..929e30e98 --- /dev/null +++ b/docs/content/en/methods/site/Param.md @@ -0,0 +1,28 @@ +--- +title: Param +description: Returns the site parameter with the given key. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..8467be41d --- /dev/null +++ b/docs/content/en/methods/site/Params.md @@ -0,0 +1,42 @@ +--- +title: Params +description: Returns a map of custom parameters as defined in the site configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 = 'jsmith@example.org' + 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](g) the [identifiers](g): + +```go-html-template +{{ .Site.Params.subtitle }} → The Best Widgets on Earth +{{ .Site.Params.author.name }} → John Smith + +{{ $layout := .Site.Params.layouts.rfc_1123 }} +{{ .Site.Lastmod.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/ diff --git a/docs/content/en/methods/site/RegularPages.md b/docs/content/en/methods/site/RegularPages.md new file mode 100644 index 000000000..69a460529 --- /dev/null +++ b/docs/content/en/methods/site/RegularPages.md @@ -0,0 +1,32 @@ +--- +title: RegularPages +description: Returns a collection of all regular pages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [SITE.RegularPages] +--- + +The `RegularPages` method on a `Site` object returns a collection of all [regular pages](g), in the [default sort order](g). + +```go-html-template +{{ range .Site.RegularPages }} + <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> +{{ end }} +``` + +{{% glossary-term "default sort order" %}} + +[default sort order](g) + +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..0ddaf0626 --- /dev/null +++ b/docs/content/en/methods/site/Sections.md @@ -0,0 +1,40 @@ +--- +title: Sections +description: Returns a collection of top-level section pages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [SITE.Sections] +--- + +The `Sections` method on a `Site` object returns a collection of top-level [section pages](g), in the [default sort order](g). + +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..cca71a40a --- /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 default content language then by language weight. +categories: [] +keywords: [] +params: + functions_and_methods: + 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 the home page of the site corresponding to the default content language: + +```go-html-template +{{ with .Site.Sites.Default }} + <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/Store.md b/docs/content/en/methods/site/Store.md new file mode 100644 index 000000000..7dcf7d095 --- /dev/null +++ b/docs/content/en/methods/site/Store.md @@ -0,0 +1,117 @@ +--- +title: Store +description: Returns a "scratch pad" to store and manipulate data, scoped to the current site. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Scratch + signatures: [site.Store] +--- + +{{< new-in 0.139.0 />}} + +Use the `Store` method on a `Site` object to create a [scratch pad](g) to store and manipulate data, scoped to the current site. To create a scratch pad with a different [scope](g), refer to the [scope](#scope) section below. + +## Methods + +### Set + +Sets the value of a given key. + +```go-html-template +{{ site.Store.Set "greeting" "Hello" }} +``` + +### Get + +Gets the value of a given key. + +```go-html-template +{{ site.Store.Set "greeting" "Hello" }} +{{ site.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 +{{ site.Store.Set "greeting" "Hello" }} +{{ site.Store.Add "greeting" "Welcome" }} +{{ site.Store.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ site.Store.Set "total" 3 }} +{{ site.Store.Add "total" 7 }} +{{ site.Store.Get "total" }} → 10 +``` + +```go-html-template +{{ site.Store.Set "greetings" (slice "Hello") }} +{{ site.Store.Add "greetings" (slice "Welcome" "Cheers") }} +{{ site.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 +{{ site.Store.SetInMap "greetings" "english" "Hello" }} +{{ site.Store.SetInMap "greetings" "french" "Bonjour" }} +{{ site.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 +{{ site.Store.SetInMap "greetings" "english" "Hello" }} +{{ site.Store.SetInMap "greetings" "french" "Bonjour" }} +{{ site.Store.DeleteInMap "greetings" "english" }} +{{ site.Store.Get "greetings" }} → map[french:Bonjour] +``` + +### GetSortedMapValues + +Returns an array of values from `key` sorted by `mapKey`. + +```go-html-template +{{ site.Store.SetInMap "greetings" "english" "Hello" }} +{{ site.Store.SetInMap "greetings" "french" "Bonjour" }} +{{ site.Store.GetSortedMapValues "greetings" }} → [Hello Bonjour] +``` + +### Delete + +Removes the given key. + +```go-html-template +{{ site.Store.Set "greeting" "Hello" }} +{{ site.Store.Delete "greeting" }} +``` + +{{% include "_common/scratch-pad-scope.md" %}} + +## Determinate values + +The `Store` method is often used to set scratch pad values within a shortcode, a partial template called by a shortcode, or by a Markdown render hook. In all three cases, the scratch pad values are indeterminate until Hugo renders the page content. + +If you need to access a scratch pad value from a parent template, and the parent template has not yet rendered the page content, you can trigger content rendering by assigning the returned value to a [noop](g) variable: + +```go-html-template +{{ $noop := .Content }} +{{ site.Store.Get "mykey" }} +``` + +You can also trigger content rendering with the `ContentWithoutSummary`, `FuzzyWordCount`, `Len`, `Plain`, `PlainWords`, `ReadingTime`, `Summary`, `Truncated`, and `WordCount` methods. For example: + +```go-html-template +{{ $noop := .WordCount }} +{{ site.Store.Get "mykey" }} +``` diff --git a/docs/content/en/methods/site/Taxonomies.md b/docs/content/en/methods/site/Taxonomies.md new file mode 100644 index 000000000..92dc41a9b --- /dev/null +++ b/docs/content/en/methods/site/Taxonomies.md @@ -0,0 +1,176 @@ +--- +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: [] +params: + functions_and_methods: + returnType: page.TaxonomyList + signatures: [SITE.Taxonomies] +--- + +Conceptually, the `Taxonomies` method on a `Site` object returns a data structure such as: + +{{< code-toggle file=hugo >}} +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 file=hugo >}} +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. + +## Examples + +### List content with the same taxonomy term + +If you are using a taxonomy for something like a series of posts, you can list individual pages associated with the same term. For example: + +```go-html-template +<ul> + {{ range .Site.Taxonomies.series.golang }} + <li><a href="{{ .Page.RelPermalink }}">{{ .Page.Title }}</a></li> + {{ end }} +</ul> +``` + +### List all content in a given taxonomy + +This would be very useful in a sidebar as “featured content”. You could even have different sections of “featured content” by assigning different terms to the content. + +```go-html-template +<section id="menu"> + <ul> + {{ range $term, $taxonomy := .Site.Taxonomies.featured }} + <li>{{ $term }}</li> + <ul> + {{ range $taxonomy.Pages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> + {{ end }} + </ul> +</section> +``` + +### Render a site's taxonomies + +The following example displays all terms in a site's tags taxonomy: + +```go-html-template +<ul> + {{ range .Site.Taxonomies.tags }} + <li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li> + {{ end }} +</ul> +``` +This example will list all taxonomies and their terms, as well as all the content assigned to each of the terms. + +```go-html-template {file="layouts/partials/all-taxonomies.html"} +{{ with .Site.Taxonomies }} + {{ $numberOfTerms := 0 }} + {{ range $taxonomy, $terms := . }} + {{ $numberOfTerms = len . | add $numberOfTerms }} + {{ end }} + + {{ if gt $numberOfTerms 0 }} + <ul> + {{ range $taxonomy, $terms := . }} + {{ with $terms }} + <li> + <a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a> + <ul> + {{ range $term, $weightedPages := . }} + <li> + <a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a> + <ul> + {{ range $weightedPages }} + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> + {{ end }} + </ul> + </li> + {{ end }} + </ul> + </li> + {{ end }} + {{ end }} + </ul> + {{ end }} +{{ end }} +``` + +[taxonomies]: /content-management/taxonomies/ diff --git a/docs/content/en/methods/site/Title.md b/docs/content/en/methods/site/Title.md new file mode 100644 index 000000000..935edda0c --- /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: [] +params: + functions_and_methods: + 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..f395a3693 --- /dev/null +++ b/docs/content/en/methods/site/_index.md @@ -0,0 +1,8 @@ +--- +title: Site methods +linkTitle: Site +description: Use these methods with Site objects. +categories: [] +keywords: [] +aliases: [/variables/site/] +--- diff --git a/docs/content/en/methods/taxonomy/Alphabetical.md b/docs/content/en/methods/taxonomy/Alphabetical.md new file mode 100644 index 000000000..af4af596c --- /dev/null +++ b/docs/content/en/methods/taxonomy/Alphabetical.md @@ -0,0 +1,69 @@ +--- +title: Alphabetical +description: Returns an ordered taxonomy, sorted alphabetically by term. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.OrderedTaxonomy + signatures: [TAXONOMY.Alphabetical] +--- + +The `Alphabetical` method on a `Taxonomy` object returns an [ordered taxonomy](g), sorted alphabetically by [term](g). + +While a `Taxonomy` object is a [map](g), an ordered taxonomy is a [slice](g), where each element is an object that contains the term and a slice of its [weighted pages](g). + +{{% include "/_common/methods/taxonomy/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>{{ debug.Dump $taxonomyObject.Alphabetical }}</pre> +``` + +{{% include "/_common/methods/taxonomy/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> +``` diff --git a/docs/content/en/methods/taxonomy/ByCount.md b/docs/content/en/methods/taxonomy/ByCount.md new file mode 100644 index 000000000..fbf9bb4a1 --- /dev/null +++ b/docs/content/en/methods/taxonomy/ByCount.md @@ -0,0 +1,69 @@ +--- +title: ByCount +description: Returns an ordered taxonomy, sorted by the number of pages associated with each term. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.OrderedTaxonomy + signatures: [TAXONOMY.ByCount] +--- + +The `ByCount` method on a `Taxonomy` object returns an [ordered taxonomy](g), sorted by the number of pages associated with each [term](g). + +While a `Taxonomy` object is a [map](g), an ordered taxonomy is a [slice](g), where each element is an object that contains the term and a slice of its [weighted pages](g). + +{{% include "/_common/methods/taxonomy/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>{{ debug.Dump $taxonomyObject.ByCount }}</pre> +``` + +{{% include "/_common/methods/taxonomy/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> +``` diff --git a/docs/content/en/methods/taxonomy/Count.md b/docs/content/en/methods/taxonomy/Count.md new file mode 100644 index 000000000..76af8ee04 --- /dev/null +++ b/docs/content/en/methods/taxonomy/Count.md @@ -0,0 +1,22 @@ +--- +title: Count +description: Returns the number of number of weighted pages to which the given term has been assigned. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: int + signatures: [TAXONOMY.Count TERM] +--- + +The `Count` method on a `Taxonomy` object returns the number of number of [weighted pages](g) to which the given [term](g) has been assigned. + +{{% include "/_common/methods/taxonomy/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 +``` diff --git a/docs/content/en/methods/taxonomy/Get.md b/docs/content/en/methods/taxonomy/Get.md new file mode 100644 index 000000000..03c184868 --- /dev/null +++ b/docs/content/en/methods/taxonomy/Get.md @@ -0,0 +1,67 @@ +--- +title: Get +description: Returns a slice of weighted pages to which the given term has been assigned. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.WeightedPages + signatures: [TAXONOMY.Get TERM] +--- + +The `Get` method on a `Taxonomy` object returns a slice of [weighted pages](g) to which the given [term](g) has been assigned. + +{{% include "/_common/methods/taxonomy/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](g), you cannot use the [chaining](g) 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>{{ debug.Dump $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> +``` + +[`index`]: /functions/collections/indexfunction/ diff --git a/docs/content/en/methods/taxonomy/Page.md b/docs/content/en/methods/taxonomy/Page.md new file mode 100644 index 000000000..b0b5d3aff --- /dev/null +++ b/docs/content/en/methods/taxonomy/Page.md @@ -0,0 +1,26 @@ +--- +title: Page +description: Returns the taxonomy page or nil if the taxonomy has no terms. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [TAXONOMY.Page] +--- + +{{< new-in 0.125.0 />}} + +This `TAXONOMY` method returns nil if the taxonomy has no terms, so you must code defensively: + +```go-html-template +{{ with .Site.Taxonomies.tags.Page }} + <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> +{{ end }} +``` + +This is rendered to: + +```html +<a href="/tags/">Tags</a> +``` diff --git a/docs/content/en/methods/taxonomy/_index.md b/docs/content/en/methods/taxonomy/_index.md new file mode 100644 index 000000000..13acdb10c --- /dev/null +++ b/docs/content/en/methods/taxonomy/_index.md @@ -0,0 +1,7 @@ +--- +title: Taxonomy methods +linkTitle: Taxonomy +description: Use these methods with Taxonomy objects. +keywords: [] +aliases: [/variables/taxonomy/] +--- diff --git a/docs/content/en/methods/time/Add.md b/docs/content/en/methods/time/Add.md new file mode 100644 index 000000000..e518a1633 --- /dev/null +++ b/docs/content/en/methods/time/Add.md @@ -0,0 +1,20 @@ +--- +title: Add +description: Returns the given time plus the given duration. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..ffc93c712 --- /dev/null +++ b/docs/content/en/methods/time/AddDate.md @@ -0,0 +1,37 @@ +--- +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: [] +params: + functions_and_methods: + 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. + +```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..1c8d41f64 --- /dev/null +++ b/docs/content/en/methods/time/After.md @@ -0,0 +1,17 @@ +--- +title: After +description: Reports whether TIME1 is after TIME2. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..f6dc3a8e7 --- /dev/null +++ b/docs/content/en/methods/time/Before.md @@ -0,0 +1,16 @@ +--- +title: Before +description: Reports whether TIME1 is before TIME2. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..e9e67873c --- /dev/null +++ b/docs/content/en/methods/time/Day.md @@ -0,0 +1,15 @@ +--- +title: Day +description: Returns the day of the month of the given time.Time value. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..6db10423c --- /dev/null +++ b/docs/content/en/methods/time/Equal.md @@ -0,0 +1,17 @@ +--- +title: Equal +description: Reports whether TIME1 is equal to TIME2. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..8a484b74e --- /dev/null +++ b/docs/content/en/methods/time/Format.md @@ -0,0 +1,88 @@ +--- +title: Format +description: Returns a textual representation of the time.Time value formatted according to the layout string. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [TIME.Format LAYOUT] +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](g) the return value, use the [`time.Format`] function instead. + +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. + +## Layout string + +{{% include "/_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 +``` + +[`time.Format`]: /functions/time/format/ diff --git a/docs/content/en/methods/time/Hour.md b/docs/content/en/methods/time/Hour.md new file mode 100644 index 000000000..28ecf62ac --- /dev/null +++ b/docs/content/en/methods/time/Hour.md @@ -0,0 +1,15 @@ +--- +title: Hour +description: Returns the hour within the day of the given time.Time value, in the range [0, 23]. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..28177b105 --- /dev/null +++ b/docs/content/en/methods/time/IsDST.md @@ -0,0 +1,18 @@ +--- +title: IsDST +description: Reports whether the given time.Time value is in Daylight Savings Time. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..400172794 --- /dev/null +++ b/docs/content/en/methods/time/IsZero.md @@ -0,0 +1,18 @@ +--- +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: [] +params: + functions_and_methods: + 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..74fe889e0 --- /dev/null +++ b/docs/content/en/methods/time/Local.md @@ -0,0 +1,15 @@ +--- +title: Local +description: Returns the given time.Time value with the location set to local time. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..b53db6d83 --- /dev/null +++ b/docs/content/en/methods/time/Minute.md @@ -0,0 +1,15 @@ +--- +title: Minute +description: Returns the minute offset within the hour of the given time.Time value, in the range [0, 59]. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..b0ccea9c3 --- /dev/null +++ b/docs/content/en/methods/time/Month.md @@ -0,0 +1,24 @@ +--- +title: Month +description: Returns the month of the year of the given time.Time value. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..d895f9622 --- /dev/null +++ b/docs/content/en/methods/time/Nanosecond.md @@ -0,0 +1,15 @@ +--- +title: Nanosecond +description: Returns the nanosecond offset within the second of the given time.Time value, in the range [0, 999999999]. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/Round.md b/docs/content/en/methods/time/Round.md new file mode 100644 index 000000000..816d41b44 --- /dev/null +++ b/docs/content/en/methods/time/Round.md @@ -0,0 +1,21 @@ +--- +title: Round +description: Returns the result of rounding TIME to the nearest multiple of DURATION since January 1, 0001, 00:00:00 UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: time.Time + signatures: [TIME.Round DURATION] +--- + +The rounding behavior for halfway values is to round up. + +The `Round` method operates on TIME as an absolute duration since the [zero time](g); it does not operate on the presentation form of the time. If DURATION is a multiple of one hour, `Round` may return a time with a non-zero minute, depending on the time zone. + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $d := time.ParseDuration "1h"}} + +{{ ($t.Round $d).Format "2006-01-02T15:04:05-00:00" }} → 2023-01-28T00:00:00-00:00 +``` diff --git a/docs/content/en/methods/time/Second.md b/docs/content/en/methods/time/Second.md new file mode 100644 index 000000000..3af086fd3 --- /dev/null +++ b/docs/content/en/methods/time/Second.md @@ -0,0 +1,15 @@ +--- +title: Second +description: Returns the second offset within the minute of the given time.Time value, in the range [0, 59]. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..d48bf3467 --- /dev/null +++ b/docs/content/en/methods/time/Sub.md @@ -0,0 +1,17 @@ +--- +title: Sub +description: Returns the duration computed by subtracting TIME2 from TIME1. +categories: [] +keywords: [] +params: + functions_and_methods: + 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/Truncate.md b/docs/content/en/methods/time/Truncate.md new file mode 100644 index 000000000..b797afec0 --- /dev/null +++ b/docs/content/en/methods/time/Truncate.md @@ -0,0 +1,19 @@ +--- +title: Truncate +description: Returns the result of rounding TIME down to a multiple of DURATION since January 1, 0001, 00:00:00 UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: time.Time + signatures: [TIME.Truncate DURATION] +--- + +The `Truncate` method operates on TIME as an absolute duration since the [zero time](g); it does not operate on the presentation form of the time. If DURATION is a multiple of one hour, `Truncate` may return a time with a non-zero minute, depending on the time zone. + +```go-html-template +{{ $t := time.AsTime "2023-01-27T23:44:58-08:00" }} +{{ $d := time.ParseDuration "1h"}} + +{{ ($t.Truncate $d).Format "2006-01-02T15:04:05-00:00" }} → 2023-01-27T23:00:00-00:00 +``` diff --git a/docs/content/en/methods/time/UTC.md b/docs/content/en/methods/time/UTC.md new file mode 100644 index 000000000..e131a003e --- /dev/null +++ b/docs/content/en/methods/time/UTC.md @@ -0,0 +1,14 @@ +--- +title: UTC +description: Returns the given time.Time value with the location set to UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..73deb524e --- /dev/null +++ b/docs/content/en/methods/time/Unix.md @@ -0,0 +1,17 @@ +--- +title: Unix +description: Returns the given time.Time value expressed as the number of seconds elapsed since January 1, 1970 UTC. +categories: [] +params: + functions_and_methods: + 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..fadb0916c --- /dev/null +++ b/docs/content/en/methods/time/UnixMicro.md @@ -0,0 +1,17 @@ +--- +title: UnixMicro +description: Returns the given time.Time value expressed as the number of microseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..9d2261d91 --- /dev/null +++ b/docs/content/en/methods/time/UnixMilli.md @@ -0,0 +1,17 @@ +--- +title: UnixMilli +description: Returns the given time.Time value expressed as the number of milliseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..4159ddee2 --- /dev/null +++ b/docs/content/en/methods/time/UnixNano.md @@ -0,0 +1,17 @@ +--- +title: UnixNano +description: Returns the given time.Time value expressed as the number of nanoseconds elapsed since January 1, 1970 UTC. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..da939ff87 --- /dev/null +++ b/docs/content/en/methods/time/Weekday.md @@ -0,0 +1,23 @@ +--- +title: Weekday +description: Returns the day of the week of the given time.Time value. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..3f647ea34 --- /dev/null +++ b/docs/content/en/methods/time/Year.md @@ -0,0 +1,15 @@ +--- +title: Year +description: Returns the year of the given time.Time value. +categories: [] +keywords: [] +params: + functions_and_methods: + 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..a93158b45 --- /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: [] +params: + functions_and_methods: + 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..8114664d3 --- /dev/null +++ b/docs/content/en/methods/time/_index.md @@ -0,0 +1,7 @@ +--- +title: Time methods +linkTitle: Time +description: Use these methods with time.Time values. +categories: [] +keywords: [] +--- |