From: Bjørn Erik Pedersen Date: Wed, 25 Feb 2026 09:29:05 +0000 (+0100) Subject: Merge commit '0c2fa2460f485e0eca564dcccf36d34538374922' X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=a3ea9cd18fc79fbae9f1ce0fc5242268d122e5f7;p=brevno-suite%2Fhugo Merge commit '0c2fa2460f485e0eca564dcccf36d34538374922' --- a3ea9cd18fc79fbae9f1ce0fc5242268d122e5f7 diff --cc docs/assets/css/components/all.css index f5002fd50,000000000..62c2b2a41 mode 100644,000000..100644 --- a/docs/assets/css/components/all.css +++ b/docs/assets/css/components/all.css @@@ -1,7 -1,0 +1,8 @@@ +/* The order of these does not matter. */ +@import "./content.css"; +@import "./fonts.css"; +@import "./helpers.css"; +@import "./shortcodes.css"; +@import "./tableofcontents.css"; +@import "./view-transitions.css"; ++@import "./todo-lists.css"; diff --cc docs/assets/css/components/todo-lists.css index 000000000,000000000..886beb41d new file mode 100644 --- /dev/null +++ b/docs/assets/css/components/todo-lists.css @@@ -1,0 -1,0 +1,15 @@@ ++ul.todo { ++ padding-left: 0; ++} ++ ++ul.todo li { ++ display: flex; ++ gap: 0.8em; ++} ++ ++ul.todo li input[type="checkbox"] { ++ width: 1em; ++ height: 1em; ++ flex-shrink: 0; ++ margin-top: 0.3em; ++} diff --cc docs/assets/css/styles.css index 6734e9a30,000000000..79ce316d1 mode 100644,000000..100644 --- a/docs/assets/css/styles.css +++ b/docs/assets/css/styles.css @@@ -1,143 -1,0 +1,143 @@@ +@import "tailwindcss"; +@plugin "@tailwindcss/typography"; +@variant dark (&:where(.dark, .dark *)); + +@import "components/all.css"; + +/* TailwindCSS ignores files in .gitignore, so make it explicit. */ +@source "hugo_stats.json"; + +@theme { + /* Breakpoints. */ + --breakpoint-sm: 40rem; + --breakpoint-md: 48rem; + --breakpoint-lg: 68rem; /* Default 64rem; */ + --breakpoint-xl: 80rem; + --breakpoint-2xl: 96rem; + + /* Colors. */ + --color-primary: var(--color-blue-600); + --color-dark: #000; + --color-light: var(--color-gray-50); + --color-accent: var(--color-orange-500); + --color-accent-light: var(--color-pink-500); + --color-accent-dark: var(--color-green-500); + + /* https://www.tints.dev/blue/0594CB */ + --color-blue-50: #e1f6fe; + --color-blue-100: #c3edfe; + --color-blue-200: #88dbfc; + --color-blue-300: #4cc9fb; + --color-blue-400: #15b9f9; + --color-blue-500: #0594cb; + --color-blue-600: #0477a4; + --color-blue-700: #035677; + --color-blue-800: #023a50; + --color-blue-900: #011d28; + --color-blue-950: #000e14; + + /* https://www.tints.dev/orange/EBB951 */ + --color-orange-50: #fdf8ed; + --color-orange-100: #fbf1da; + --color-orange-200: #f7e4ba; + --color-orange-300: #f3d596; + --color-orange-400: #efc976; + --color-orange-500: #ebb951; + --color-orange-600: #e5a51a; + --color-orange-700: #a97a13; + --color-orange-800: #72520d; + --color-orange-900: #372806; + --color-orange-950: #1b1403; + + /* https://www.tints.dev/pink/FF4088 */ + --color-pink-50: #ffebf2; + --color-pink-100: #ffdbe9; + --color-pink-200: #ffb3d0; + --color-pink-300: #ff8fba; + --color-pink-400: #ff66a1; + --color-pink-500: #ff4088; + --color-pink-600: #ff0062; + --color-pink-700: #c2004a; + --color-pink-800: #800031; + --color-pink-900: #420019; + --color-pink-950: #1f000c; + + /* https://www.tints.dev/green/33BA91 */ + --color-green-50: #ebfaf5; + --color-green-100: #d3f3e9; + --color-green-200: #abe8d6; + --color-green-300: #7fdcc0; + --color-green-400: #53d0aa; + --color-green-500: #33ba91; + --color-green-600: #299474; + --color-green-700: #1f7058; + --color-green-800: #154c3b; + --color-green-900: #0a241c; + --color-green-950: #051410; + + /* Fonts. */ + --font-sans: + "Mulish", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", + Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", + "Segoe UI Symbol", "Noto Color Emoji"; +} + +html { + scroll-padding-top: 100px; +} + +body { + @apply antialiased font-sans text-black dark:text-gray-100; +} + +.p-safe-area-x { + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); +} + +.p-safe-area-y { + padding-top: env(safe-area-inset-top); + padding-bottom: env(safe-area-inset-bottom); +} + +.px-main { + padding-left: max(env(safe-area-inset-left), 1rem); + padding-right: max(env(safe-area-inset-right), 1rem); +} + - @media screen(md) { ++@media (min-width: theme('--breakpoint-md')) { + .px-main { + padding-left: max(env(safe-area-inset-left), 2rem); + padding-right: max(env(safe-area-inset-right), 2rem); + } +} + - @media screen(lg) { ++@media (min-width: theme('--breakpoint-lg')) { + .px-main { + padding-left: max(env(safe-area-inset-left), 3rem); + padding-right: max(env(safe-area-inset-right), 3rem); + } +} + +/* Algolia DocSearch */ +.algolia-docsearch-suggestion--highlight { + color: var(--color-primary); +} + +/* Footnotes */ +.footnote-backref, +.footnote-ref { + text-decoration: none; + padding-left: .0625em; +} + +/* Code spans within paragraphs, tables cells, list items, etc. */ +:not(pre) > code { + white-space: nowrap; +} + +/* Utility class for tables to prevent word wrapping in the first column. */ +.no-wrap-first-col td:first-child, +.no-wrap-first-col th:first-child { + white-space: nowrap; +} diff --cc docs/content/en/_common/functions/hugo/sites-collection.md index 000000000,000000000..9f4b81b5a new file mode 100644 --- /dev/null +++ b/docs/content/en/_common/functions/hugo/sites-collection.md @@@ -1,0 -1,0 +1,9 @@@ ++--- ++_comment: Do not remove front matter. ++--- ++ ++The returned collection follows a hierarchical sort where each subsequent dimension acts as a tie-breaker for the one above it. ++ ++1. [Language](g) is sorted by [weight](g) in ascending order, falling back to lexicographical order if weights are tied or undefined. ++1. [Version](g) is then sorted by weight in ascending order, with Hugo defaulting to a descending semantic sort for any ties. ++1. [Role](g) is finally sorted by weight in ascending order, using lexicographical order as the final fallback. diff --cc docs/content/en/_common/menu-entries/pre-and-post.md index da3d584d1,000000000..9f101b457 mode 100644,000000..100644 --- a/docs/content/en/_common/menu-entries/pre-and-post.md +++ b/docs/content/en/_common/menu-entries/pre-and-post.md @@@ -1,39 -1,0 +1,39 @@@ +--- +_comment: Do not remove front matter. +--- + - In this site configuration we enable rendering of [emoji shortcodes], and add emoji shortcodes before (pre) and after (post) each menu entry: ++In this project configuration we enable rendering of [emoji shortcodes], and add emoji shortcodes before (pre) and after (post) each menu entry: + +{{< code-toggle file=hugo >}} +enableEmoji = true + +[[menus.main]] +name = 'About' +pageRef = '/about' +post = ':point_left:' +pre = ':point_right:' +weight = 10 + +[[menus.main]] +name = 'Contact' +pageRef = '/contact' +post = ':arrow_left:' +pre = ':arrow_right:' +weight = 20 +{{< /code-toggle >}} + +To render the menu: + +```go-html-template + +``` + +[emoji shortcodes]: /quick-reference/emojis/ diff --cc docs/content/en/_common/methods/page/next-and-prev.md index 27b069ddc,000000000..75f120c02 mode 100644,000000..100644 --- a/docs/content/en/_common/methods/page/next-and-prev.md +++ b/docs/content/en/_common/methods/page/next-and-prev.md @@@ -1,60 -1,0 +1,60 @@@ +--- +_comment: Do not remove front matter. +--- + +Hugo determines the _next_ and _previous_ page by sorting the site's collection of regular pages according to this sorting hierarchy: + +Field|Precedence|Sort direction +:--|:--|:-- +[`weight`]|1|descending +[`date`]|2|descending +[`linkTitle`]|3|descending +[`path`]|4|descending + +[`date`]: /methods/page/date/ +[`weight`]: /methods/page/weight/ +[`linkTitle`]: /methods/page/linktitle/ +[`path`]: /methods/page/path/ + +The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior. + +For example, with this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +And these templates: + +```go-html-template {file="layouts/section.html"} +{{ range .Pages.ByWeight }} +

{{ .LinkTitle }}

+{{ end }} +``` + +```go-html-template {file="layouts/page.html"} +{{ with .Prev }} + Previous +{{ end }} + +{{ with .Next }} + Next +{{ end }} +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + - To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility. ++To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [project configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility. + - [site configuration]: /configuration/page/ ++[project configuration]: /configuration/page/ +[`Next`]: /methods/pages/prev +[`Prev`]: /methods/pages/prev diff --cc docs/content/en/_common/methods/page/nextinsection-and-previnsection.md index 005953324,000000000..4ca8a4ac8 mode 100644,000000..100644 --- a/docs/content/en/_common/methods/page/nextinsection-and-previnsection.md +++ b/docs/content/en/_common/methods/page/nextinsection-and-previnsection.md @@@ -1,78 -1,0 +1,78 @@@ +--- +_comment: Do not remove front matter. +--- + +Hugo determines the _next_ and _previous_ page by sorting the current section's regular pages according to this sorting hierarchy: + +Field|Precedence|Sort direction +:--|:--|:-- +[`weight`]|1|descending +[`date`]|2|descending +[`linkTitle`]|3|descending +[`path`]|4|descending + +[`date`]: /methods/page/date/ +[`weight`]: /methods/page/weight/ +[`linkTitle`]: /methods/page/linktitle/ +[`path`]: /methods/page/path/ + +The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior. + +For example, with this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +And these templates: + +```go-html-template {file="layouts/section.html"} +{{ range .Pages.ByWeight }} +

{{ .LinkTitle }}

+{{ end }} +``` + +```go-html-template {file="layouts/page.html"} +{{ with .PrevInSection }} + Previous +{{ end }} + +{{ with .NextInSection }} + Next +{{ end }} +``` + +When you visit page-2: + +- The `PrevInSection` method points to page-3 +- The `NextInSection` method points to page-1 + - To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility. ++To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [project configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility. + - [site configuration]: /configuration/page/ ++[project configuration]: /configuration/page/ +[`Next`]: /methods/pages/prev +[`Prev`]: /methods/pages/prev + +## Example + +Code defensively by checking for page existence: + +```go-html-template +{{ with .PrevInSection }} + Previous +{{ end }} + +{{ with .NextInSection }} + Next +{{ end }} +``` + +## Alternative + +Use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility. diff --cc docs/content/en/_common/methods/resource/processing-spec.md index 20b8f8498,000000000..226c0ba6d mode 100644,000000..100644 --- a/docs/content/en/_common/methods/resource/processing-spec.md +++ b/docs/content/en/_common/methods/resource/processing-spec.md @@@ -1,73 -1,0 +1,73 @@@ +--- +_comment: Do not remove front matter. +--- + +## Processing specification + +The processing specification is a space-delimited, case-insensitive list containing one or more of the following options in any sequence: + +action +: Specify one of `crop`, `fill`, `fit`, or `resize`. This is applicable to the [`Process`][] method and the [`images.Process`][] filter. If you specify an action, you must also provide dimensions. + +anchor - : The focal point used when cropping or filling an image. Valid options include `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. The `Smart` option utilizes the [`smartcrop.js`][] library to identify the most interesting area of the image. This defaults to the [`anchor`][] parameter in your site configuration. ++: The focal point used when cropping or filling an image. Valid options include `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. The `Smart` option utilizes the [`smartcrop.js`][] library to identify the most interesting area of the image. This defaults to the [`anchor`][] parameter in your project configuration. + +background color - : The background color used when converting transparent images to formats that do not support transparency, such as PNG to JPEG. This color also fills the empty space created when rotating an image by a non-orthogonal angle if the space is not transparent and a background color is not specified in the processing specification. The value must be an RGB [hexadecimal color][]. This defaults to the [`bgColor`][] parameter in your site configuration. ++: The background color used when converting transparent images to formats that do not support transparency, such as PNG to JPEG. This color also fills the empty space created when rotating an image by a non-orthogonal angle if the space is not transparent and a background color is not specified in the processing specification. The value must be an RGB [hexadecimal color][]. This defaults to the [`bgColor`][] parameter in your project configuration. + +compression +: {{< new-in 0.153.5 />}} - : The encoding strategy used for the image. Options are `lossy` or `lossless`. Note that `lossless` is only supported by the WebP format. This defaults to the [`compression`][] parameter in your site configuration. ++: The encoding strategy used for the image. Options are `lossy` or `lossless`. Note that `lossless` is only supported by the WebP format. This defaults to the [`compression`][] parameter in your project configuration. + +dimensions +: The dimensions of the resulting image, in pixels. The format is `WIDTHxHEIGHT` where `WIDTH` and `HEIGHT` are whole numbers. When resizing an image, you may specify only the width (such as `600x`) or only the height (such as `x400`) for proportional scaling. Specifying both width and height when resizing an image may result in non-proportional scaling. When cropping, fitting, or filling, you must provide both width and height such as `600x400`. + +format +: The format of the resulting image. Valid options include `bmp`, `gif`, `jpeg`, `png`, `tiff`, or `webp`. This defaults to the format of the source image. + +hint - : The encoding preset used when processing WebP images, equivalent to the `-preset` flag for the [`cwebp`][] CLI. Valid options include `drawing`, `icon`, `photo`, `picture`, or `text`. This defaults to the [`hint`][] parameter in your site configuration. ++: The encoding preset used when processing WebP images, equivalent to the `-preset` flag for the [`cwebp`][] CLI. Valid options include `drawing`, `icon`, `photo`, `picture`, or `text`. This defaults to the [`hint`][] parameter in your project configuration. + + Value|Example + :--|:-- + `drawing`|Hand or line drawing with high-contrast details + `icon`|Small colorful image + `photo`|Outdoor photograph with natural lighting + `picture`|Indoor photograph such as a portrait + `text`|Image that is primarily text + +quality - : The visual fidelity of the image, applicable to JPEG and WebP formats when using `lossy` compression. The format is `qQUALITY` where `QUALITY` is a whole number between `1` and `100`, inclusive. Lower numbers prioritize smaller file size, while higher numbers prioritize visual clarity. This defaults to the [`quality`][] parameter in your site configuration. ++: The visual fidelity of the image, applicable to JPEG and WebP formats when using `lossy` compression. The format is `qQUALITY` where `QUALITY` is a whole number between `1` and `100`, inclusive. Lower numbers prioritize smaller file size, while higher numbers prioritize visual clarity. This defaults to the [`quality`][] parameter in your project configuration. + +resampling filter - : The algorithm used to calculate new pixels when resizing, fitting, or filling an image. Common options include `box`, `lanczos`, `catmullRom`, `mitchellNetravali`, `linear`, or `nearestNeighbor`. This defaults to the [`resampleFilter`][] parameter in your site configuration. ++: The algorithm used to calculate new pixels when resizing, fitting, or filling an image. Common options include `box`, `lanczos`, `catmullRom`, `mitchellNetravali`, `linear`, or `nearestNeighbor`. This defaults to the [`resampleFilter`][] parameter in your project configuration. + + Filter|Description + :--|:-- + `box`|Simple and fast averaging filter appropriate for downscaling + `lanczos`|High-quality resampling filter for photographic images yielding sharp results + `catmullRom`|Sharp cubic filter that is faster than the Lanczos filter while providing similar results + `mitchellNetravali`|Cubic filter that produces smoother results with less ringing artifacts than CatmullRom + `linear`|Bilinear resampling filter, produces smooth output, faster than cubic filters + `nearestNeighbor`|Fastest resampling filter, no antialiasing + + Refer to the [source documentation][] for a complete list of available resampling filters. If you wish to improve image quality at the expense of performance, you may wish to experiment with the alternative filters. + +rotation +: The number of whole degrees to rotate an image counter-clockwise. The format is `rDEGREES` where `DEGREES` is a whole number. Hugo performs rotation before any other transformations, so your [target dimensions](#dimensions) and any [anchor](#anchor) should refer to the image orientation after rotation. Use `r90`, `r180`, or `r270` for orthogonal rotations, or arbitrary angles such as `r45`. To rotate clockwise, use a negative number such as `r-45`. To automatically rotate an image based on its Exif orientation tag, use the [`images.AutoOrient`][] filter instead of manual rotation. + - Rotating by non-orthogonal values increases the image extents to fit the rotated corners. For formats supporting alpha channels such as PNG or WebP, this resulting empty space is transparent by default. If the target format does not support transparency such as JPEG, or if you explicitly specify a [background color](#background-color) in the processing specification, the space is filled. If a color is required but not specified in the processing string, it defaults to the [`bgColor`][] parameter in your site configuration. ++ Rotating by non-orthogonal values increases the image extents to fit the rotated corners. For formats supporting alpha channels such as PNG or WebP, this resulting empty space is transparent by default. If the target format does not support transparency such as JPEG, or if you explicitly specify a [background color](#background-color) in the processing specification, the space is filled. If a color is required but not specified in the processing string, it defaults to the [`bgColor`][] parameter in your project configuration. + +[`anchor`]: /configuration/imaging/#anchor +[`bgcolor`]: /configuration/imaging/#bgcolor +[`compression`]: /configuration/imaging/#compression +[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp +[`hint`]: /configuration/imaging/#hint +[`images.AutoOrient`]: /functions/images/autoorient/ +[`images.Process`]: /functions/images/process/ +[`Process`]: /methods/resource/process +[`quality`]: /configuration/imaging/#quality +[`resampleFilter`]: /configuration/imaging/#resamplefilter +[`smartcrop.js`]: https://github.com/jwagner/smartcrop.js +[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color +[source documentation]: https://github.com/disintegration/imaging#image-resizing diff --cc docs/content/en/_common/methods/taxonomy/get-a-taxonomy-object.md index c90224338,000000000..75386145c mode 100644,000000..100644 --- a/docs/content/en/_common/methods/taxonomy/get-a-taxonomy-object.md +++ b/docs/content/en/_common/methods/taxonomy/get-a-taxonomy-object.md @@@ -1,67 -1,0 +1,67 @@@ +--- +_comment: Do not remove front matter. +--- + +Before we can use a `Taxonomy` method, we need to capture a `Taxonomy` object. + +## Capture a Taxonomy object + - Consider this site configuration: ++Consider this project configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +genre = 'genres' +author = 'authors' +{{< /code-toggle >}} + +And this content structure: + +```text +content/ +├── books/ +│ ├── and-then-there-were-none.md --> genres: suspense +│ ├── death-on-the-nile.md --> genres: suspense +│ └── jamaica-inn.md --> genres: suspense, romance +│ └── pride-and-prejudice.md --> genres: romance +└── _index.md +``` + +To capture the "genres" `Taxonomy` object from within any template, use the [`Taxonomies`] method on a `Site` object. + +```go-html-template +{{ $taxonomyObject := .Site.Taxonomies.genres }} +``` + +To capture the "genres" `Taxonomy` object when rendering its page with a _taxonomy_ template, use the [`Terms`] method on the page's [`Data`] object: + +```go-html-template {file="layouts/taxonomy.html"} +{{ $taxonomyObject := .Data.Terms }} +``` + +To inspect the data structure: + +```go-html-template +
{{ debug.Dump $taxonomyObject }}
+``` + +Although the [`Alphabetical`] and [`ByCount`] methods provide a better data structure for ranging through the taxonomy, you can render the weighted pages by term directly from the `Taxonomy` object: + +```go-html-template +{{ range $term, $weightedPages := $taxonomyObject }} +

{{ .Page.LinkTitle }}

+ +{{ end }} +``` + +In the example above, the first anchor element is a link to the term page. + +[`Alphabetical`]: /methods/taxonomy/alphabetical/ +[`ByCount`]: /methods/taxonomy/bycount/ + +[`data`]: /methods/page/data/ +[`terms`]: /methods/page/data/#in-a-taxonomy-template +[`taxonomies`]: /methods/site/taxonomies/ diff --cc docs/content/en/_common/ref-and-relref-error-handling.md index 1d67bbc1f,000000000..9ec185d09 mode 100644,000000..100644 --- a/docs/content/en/_common/ref-and-relref-error-handling.md +++ b/docs/content/en/_common/ref-and-relref-error-handling.md @@@ -1,10 -1,0 +1,10 @@@ +--- +_comment: Do not remove front matter. +--- + - By default, Hugo will throw an error and fail the build if it cannot resolve the path. You can change this to a warning in your site configuration, and specify a URL to return when the path cannot be resolved. ++By default, Hugo will throw an error and fail the build if it cannot resolve the path. You can change this to a warning in your project configuration, and specify a URL to return when the path cannot be resolved. + +{{< code-toggle file=hugo >}} +refLinksErrorLevel = 'warning' +refLinksNotFoundURL = '/some/other/url' +{{< /code-toggle >}} diff --cc docs/content/en/about/features.md index e39e359ec,000000000..04c61fc65 mode 100644,000000..100644 --- a/docs/content/en/about/features.md +++ b/docs/content/en/about/features.md @@@ -1,140 -1,0 +1,140 @@@ +--- +title: Features +description: Hugo's rich and powerful feature set provides the framework and tools to create static sites that build in seconds, often less. +categories: [] +keywords: [] +weight: 20 +--- + +## Framework + +[Multiplatform] +: Install Hugo's single executable on Linux, macOS, Windows, and more. + +[Multilingual] +: Localize your project for each language and region, including translations, images, dates, currencies, numbers, percentages, and collation sequence. Hugo's multilingual framework supports single-host and multihost configurations. + +[Output formats] +: Render each page of your site to one or more output formats, with granular control by page kind, section, and path. While HTML is the default output format, you can add JSON, RSS, CSV, and more. For example, create a REST API to access content. + +[Templates] +: Create templates using variables, functions, and methods to transform your content, resources, and data into a published page. While HTML templates are the most common, you can create templates for any output format. + +[Themes] +: Reduce development time and cost by using one of the hundreds of themes contributed by the Hugo community. Themes are available for corporate sites, documentation projects, image portfolios, landing pages, personal and professional blogs, resumes, CVs, and more. + +[Modules] +: Reduce development time and cost by creating or importing packaged combinations of archetypes, assets, content, data, templates, translation tables, static files, or configuration settings. A module may serve as the basis for a new site, or to augment an existing site. + +[Privacy] +: Configure your site to help comply with regional privacy regulations. + +[Security] +: Hugo's security model is based on the premise that template and configuration authors are trusted, but content authors are not. This model enables generation of HTML output safe against code injection. Other protections prevent "shelling out" to arbitrary applications, limit access to specific environment variables, prevent connections to arbitrary remote data sources, and more. + +## Content authoring + +[Content formats] +: Create your content using Markdown, HTML, AsciiDoc, Emacs Org Mode, Pandoc, or reStructuredText. Markdown is the default content format, conforming to the [CommonMark] and [GitHub Flavored Markdown] specifications. + +[Markdown attributes] +: Apply HTML attributes such as `class` and `id` to Markdown images and block elements including blockquotes, fenced code blocks, headings, horizontal rules, lists, paragraphs, and tables. + +[Markdown extensions] +: Leverage the embedded Markdown extensions to create tables, definition lists, footnotes, task lists, inserted text, mark text, subscripts, superscripts, and more. + +[Markdown render hooks] +: Override the conversion of Markdown to HTML when rendering blockquotes, fenced code blocks, headings, images, links, and tables. For example, render every standalone image as an HTML `figure` element. + +[Diagrams] +: Use fenced code blocks and Markdown render hooks to include diagrams in your content. + +[Mathematics] +: Include mathematical equations and expressions in Markdown using LaTeX markup. + +[Syntax highlighting] +: Syntactically highlight code examples using Hugo's embedded syntax highlighter, enabled by default for fenced code blocks in Markdown. The syntax highlighter supports hundreds of code languages and dozens of styles. + +[Shortcodes] +: Use Hugo's embedded shortcodes, or create your own, to insert complex content. For example, use shortcodes to include `audio` and `video` elements, render tables from local or remote data sources, insert snippets from other pages, and more. + +## Content management + +[Multidimensional content model] - : Generate pages across any combination of language, role, and version from a single source. This allows a single piece of content to be published to multiple [sites](g) within your project, removing the need to duplicate files for different audiences or versions. ++: Generate pages across any combination of language, version, and role from a single source. This allows a single piece of content to be published to multiple [sites](g) within your project, removing the need to duplicate files for different audiences or versions. + +[Content adapters] - : Create content adapters to dynamically add content when building your site. For example, use a content adapter to create pages from a remote data source such as JSON, TOML, YAML, or XML. ++: Create content adapters to dynamically add content when building your project. For example, use a content adapter to create pages from a remote data source such as JSON, TOML, YAML, or XML. + +[Taxonomies] +: Classify content to establish simple or complex logical relationships between pages. For example, create an authors taxonomy, and assign one or more authors to each page. Among other uses, the taxonomy system provides an inverted, weighted index to render a list of related pages, ordered by relevance. + +[Data] +: Augment your content using local or remote data sources including CSV, JSON, TOML, YAML, and XML. For example, create a shortcode to render an HTML table from a remote CSV file. + +[Menus] +: Provide rapid access to content via Hugo's menu system, configured automatically, globally, or on a page-by-page basis. The menu system is a key component of Hugo's multilingual architecture. + +[URL management] +: Serve any page from any path via global configuration or on a page-by-page basis. + +## Asset pipelines + +[Image processing] +: Convert, resize, crop, rotate, adjust colors, apply filters, overlay text and images, and extract metadata. + +[JavaScript bundling] +: Transpile TypeScript and JSX to JavaScript, bundle, tree shake, minify, create source maps, and perform SRI hashing. + +[Sass processing] +: Transpile Sass to CSS, bundle, tree shake, minify, create source maps, perform SRI hashing, and integrate with PostCSS. + +[Tailwind CSS processing] +: Compile Tailwind CSS utility classes into standard CSS, bundle, tree shake, optimize, minify, perform SRI hashing, and integrate with PostCSS. + +## Performance + +[Caching] +: Reduce build time and cost by rendering a _partial_ template once then cache the result, either globally or within a given context. For example, cache the result of an asset pipeline to prevent reprocessing on every rendered page. + +[Segmentation] +: Reduce build time and cost by partitioning your sites into segments. For example, render the home page and the "news section" every hour, and render the entire site once a week. + +[Minification] +: Minify HTML, CSS, and JavaScript to reduce file size, bandwidth consumption, and loading times. + +[Multilingual]: /content-management/multilingual/ +[Multiplatform]: /installation/ +[Output formats]: /configuration/output-formats/ +[Templates]: /templates/introduction/ +[Themes]: https://themes.gohugo.io/ +[Modules]: /hugo-modules/ +[Privacy]: /configuration/privacy/ +[Security]: /about/security/ + +[Content formats]: /content-management/formats/ +[CommonMark]: https://spec.commonmark.org/current/ +[GitHub Flavored Markdown]: https://github.github.com/gfm/ +[Markdown attributes]: /content-management/markdown-attributes/ +[Markdown extensions]: /configuration/markup/#extensions +[Markdown render hooks]: /render-hooks/introduction/ +[Diagrams]: /content-management/diagrams/ +[Mathematics]: /content-management/mathematics/ +[Syntax highlighting]: /content-management/syntax-highlighting/ +[Shortcodes]: /content-management/shortcodes/ + +[Multidimensional content model]: /quick-reference/glossary/#sites-matrix +[Content adapters]: /content-management/content-adapters/ +[Taxonomies]: /content-management/taxonomies/ +[Data]: /content-management/data-sources/ +[Menus]: /content-management/menus/ +[URL management]: /content-management/urls/ + +[Image processing]: /content-management/image-processing/ +[JavaScript bundling]: /functions/js/build/ +[Sass processing]: /functions/css/Sass/ +[Tailwind CSS processing]: /functions/css/tailwindcss/ + +[Caching]: /functions/partials/includecached/ +[Segmentation]: /configuration/segments/ +[Minification]: /configuration/minify/ diff --cc docs/content/en/commands/hugo.md index ef0bca9a5,000000000..ad06ecab3 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo.md +++ b/docs/content/en/commands/hugo.md @@@ -1,84 -1,0 +1,83 @@@ +--- +title: "hugo" +slug: hugo +url: /commands/hugo/ +--- +## hugo + - Build your site ++Build your project + +### Synopsis + - hugo is the main command, used to build your Hugo site. ++hugo is the main command, used to build your Hugo project. + +Hugo is a Fast and Flexible Static Site Generator +built with love by spf13 and friends in Go. + +Complete documentation is available at https://gohugo.io/. + +``` +hugo [flags] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + -D, --buildDrafts include content marked as draft + -E, --buildExpired include expired content + -F, --buildFuture include content with publishdate in the future + --cacheDir string filesystem path to cache directory + --cleanDestinationDir remove files from destination not found in static directories + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -c, --contentDir string filesystem path to content directory + -d, --destination string filesystem path to write files to + --disableKinds strings disable different kind of pages (home, RSS etc.) + --enableGitInfo add Git revision, date, author, and CODEOWNERS info to the pages + -e, --environment string build environment + --forceSyncStatic copy all files when static is changed. + --gc enable to run some cleanup tasks (remove unused cache files) after the build + -h, --help help for hugo + --ignoreCache ignores the cache directory + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + -l, --layoutDir string filesystem path to layout directory + --logLevel string log level (debug|info|warn|error) + --minify minify any supported output format (HTML, XML etc.) + --noBuildLock don't create .hugo_build.lock file + --noChmod don't sync permission mode of files + --noTimes don't sync modification time of files + --panicOnWarning panic on first WARNING log + --poll string set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes + --printI18nWarnings print missing translations + --printMemoryUsage print memory usage to screen at intervals + --printPathWarnings print warnings on duplicate target paths etc. + --printUnusedTemplates print warnings on unused templates. + --quiet build in quiet mode + --renderSegments strings named segments to render (configured in the segments config) + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --templateMetrics display metrics about template executions + --templateMetricsHints calculate some improvement hints when combined with --templateMetrics + -t, --theme strings themes to use (located in /themes/THEMENAME/) + --themesDir string filesystem path to themes directory + --trace file write trace to file (not useful in general) + -w, --watch watch filesystem for changes and recreate as needed +``` + +### SEE ALSO + - * [hugo build](/commands/hugo_build/) - Build your site ++* [hugo build](/commands/hugo_build/) - Build your project +* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell - * [hugo config](/commands/hugo_config/) - Display site configuration ++* [hugo config](/commands/hugo_config/) - Display project configuration +* [hugo convert](/commands/hugo_convert/) - Convert front matter to another format - * [hugo deploy](/commands/hugo_deploy/) - Deploy your site to a cloud provider ++* [hugo deploy](/commands/hugo_deploy/) - Deploy your project to a cloud provider +* [hugo env](/commands/hugo_env/) - Display version and environment info +* [hugo gen](/commands/hugo_gen/) - Generate documentation and syntax highlighting styles - * [hugo import](/commands/hugo_import/) - Import a site from another system ++* [hugo import](/commands/hugo_import/) - Import a project from another system +* [hugo list](/commands/hugo_list/) - List content +* [hugo mod](/commands/hugo_mod/) - Manage modules +* [hugo new](/commands/hugo_new/) - Create new content +* [hugo server](/commands/hugo_server/) - Start the embedded web server +* [hugo version](/commands/hugo_version/) - Display version - diff --cc docs/content/en/commands/hugo_build.md index 582cbe511,000000000..173cb095e mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_build.md +++ b/docs/content/en/commands/hugo_build.md @@@ -1,72 -1,0 +1,71 @@@ +--- +title: "hugo build" +slug: hugo_build +url: /commands/hugo_build/ +--- +## hugo build + - Build your site ++Build your project + +### Synopsis + - build is the main command, used to build your Hugo site. ++build is the main command, used to build your Hugo project. + +Hugo is a Fast and Flexible Static Site Generator +built with love by spf13 and friends in Go. + +Complete documentation is available at https://gohugo.io/. + +``` +hugo build [flags] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + -D, --buildDrafts include content marked as draft + -E, --buildExpired include expired content + -F, --buildFuture include content with publishdate in the future + --cacheDir string filesystem path to cache directory + --cleanDestinationDir remove files from destination not found in static directories + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -c, --contentDir string filesystem path to content directory + -d, --destination string filesystem path to write files to + --disableKinds strings disable different kind of pages (home, RSS etc.) + --enableGitInfo add Git revision, date, author, and CODEOWNERS info to the pages + -e, --environment string build environment + --forceSyncStatic copy all files when static is changed. + --gc enable to run some cleanup tasks (remove unused cache files) after the build + -h, --help help for build + --ignoreCache ignores the cache directory + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + -l, --layoutDir string filesystem path to layout directory + --logLevel string log level (debug|info|warn|error) + --minify minify any supported output format (HTML, XML etc.) + --noBuildLock don't create .hugo_build.lock file + --noChmod don't sync permission mode of files + --noTimes don't sync modification time of files + --panicOnWarning panic on first WARNING log + --poll string set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes + --printI18nWarnings print missing translations + --printMemoryUsage print memory usage to screen at intervals + --printPathWarnings print warnings on duplicate target paths etc. + --printUnusedTemplates print warnings on unused templates. + --quiet build in quiet mode + --renderSegments strings named segments to render (configured in the segments config) + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --templateMetrics display metrics about template executions + --templateMetricsHints calculate some improvement hints when combined with --templateMetrics + -t, --theme strings themes to use (located in /themes/THEMENAME/) + --themesDir string filesystem path to themes directory + --trace file write trace to file (not useful in general) + -w, --watch watch filesystem for changes and recreate as needed +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site - ++* [hugo](/commands/hugo/) - Build your project diff --cc docs/content/en/commands/hugo_completion.md index ac60dc148,000000000..34b411481 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_completion.md +++ b/docs/content/en/commands/hugo_completion.md @@@ -1,46 -1,0 +1,45 @@@ +--- +title: "hugo completion" +slug: hugo_completion +url: /commands/hugo_completion/ +--- +## hugo completion + +Generate the autocompletion script for the specified shell + +### Synopsis + +Generate the autocompletion script for hugo for the specified shell. +See each sub-command's help for details on how to use the generated script. + + +### Options + +``` + -h, --help help for completion +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo completion bash](/commands/hugo_completion_bash/) - Generate the autocompletion script for bash +* [hugo completion fish](/commands/hugo_completion_fish/) - Generate the autocompletion script for fish +* [hugo completion powershell](/commands/hugo_completion_powershell/) - Generate the autocompletion script for powershell +* [hugo completion zsh](/commands/hugo_completion_zsh/) - Generate the autocompletion script for zsh - diff --cc docs/content/en/commands/hugo_completion_bash.md index 41fb47c0c,000000000..9f18169ca mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_completion_bash.md +++ b/docs/content/en/commands/hugo_completion_bash.md @@@ -1,65 -1,0 +1,64 @@@ +--- +title: "hugo completion bash" +slug: hugo_completion_bash +url: /commands/hugo_completion_bash/ +--- +## hugo completion bash + +Generate the autocompletion script for bash + +### Synopsis + +Generate the autocompletion script for the bash shell. + +This script depends on the 'bash-completion' package. +If it is not installed already, you can install it via your OS's package manager. + +To load completions in your current shell session: + + source <(hugo completion bash) + +To load completions for every new session, execute once: + +#### Linux: + + hugo completion bash > /etc/bash_completion.d/hugo + +#### macOS: + + hugo completion bash > $(brew --prefix)/etc/bash_completion.d/hugo + +You will need to start a new shell for this setup to take effect. + + +``` +hugo completion bash +``` + +### Options + +``` + -h, --help help for bash + --no-descriptions disable completion descriptions +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell - diff --cc docs/content/en/commands/hugo_completion_fish.md index 7f971c3ca,000000000..3015d230c mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_completion_fish.md +++ b/docs/content/en/commands/hugo_completion_fish.md @@@ -1,56 -1,0 +1,55 @@@ +--- +title: "hugo completion fish" +slug: hugo_completion_fish +url: /commands/hugo_completion_fish/ +--- +## hugo completion fish + +Generate the autocompletion script for fish + +### Synopsis + +Generate the autocompletion script for the fish shell. + +To load completions in your current shell session: + + hugo completion fish | source + +To load completions for every new session, execute once: + + hugo completion fish > ~/.config/fish/completions/hugo.fish + +You will need to start a new shell for this setup to take effect. + + +``` +hugo completion fish [flags] +``` + +### Options + +``` + -h, --help help for fish + --no-descriptions disable completion descriptions +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell - diff --cc docs/content/en/commands/hugo_completion_powershell.md index 6ea17892b,000000000..780f7fc7d mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_completion_powershell.md +++ b/docs/content/en/commands/hugo_completion_powershell.md @@@ -1,53 -1,0 +1,52 @@@ +--- +title: "hugo completion powershell" +slug: hugo_completion_powershell +url: /commands/hugo_completion_powershell/ +--- +## hugo completion powershell + +Generate the autocompletion script for powershell + +### Synopsis + +Generate the autocompletion script for powershell. + +To load completions in your current shell session: + + hugo completion powershell | Out-String | Invoke-Expression + +To load completions for every new session, add the output of the above command +to your powershell profile. + + +``` +hugo completion powershell [flags] +``` + +### Options + +``` + -h, --help help for powershell + --no-descriptions disable completion descriptions +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell - diff --cc docs/content/en/commands/hugo_completion_zsh.md index b9e79f9f3,000000000..e5743e988 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_completion_zsh.md +++ b/docs/content/en/commands/hugo_completion_zsh.md @@@ -1,67 -1,0 +1,66 @@@ +--- +title: "hugo completion zsh" +slug: hugo_completion_zsh +url: /commands/hugo_completion_zsh/ +--- +## hugo completion zsh + +Generate the autocompletion script for zsh + +### Synopsis + +Generate the autocompletion script for the zsh shell. + +If shell completion is not already enabled in your environment you will need +to enable it. You can execute the following once: + + echo "autoload -U compinit; compinit" >> ~/.zshrc + +To load completions in your current shell session: + + source <(hugo completion zsh) + +To load completions for every new session, execute once: + +#### Linux: + + hugo completion zsh > "${fpath[1]}/_hugo" + +#### macOS: + + hugo completion zsh > $(brew --prefix)/share/zsh/site-functions/_hugo + +You will need to start a new shell for this setup to take effect. + + +``` +hugo completion zsh [flags] +``` + +### Options + +``` + -h, --help help for zsh + --no-descriptions disable completion descriptions +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo completion](/commands/hugo_completion/) - Generate the autocompletion script for the specified shell - diff --cc docs/content/en/commands/hugo_config.md index 2b4eaafa1,000000000..3de89f18c mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_config.md +++ b/docs/content/en/commands/hugo_config.md @@@ -1,53 -1,0 +1,52 @@@ +--- +title: "hugo config" +slug: hugo_config +url: /commands/hugo_config/ +--- +## hugo config + - Display site configuration ++Display project configuration + +### Synopsis + - Display site configuration, both default and custom settings. ++Display project configuration, both default and custom settings. + +``` +hugo config [command] [flags] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + --format string preferred file format (toml, yaml or json) (default "toml") + -h, --help help for config + --lang string the language to display config for. Defaults to the first language defined. + --printZero include config options with zero values (e.g. false, 0, "") in the output + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo config mounts](/commands/hugo_config_mounts/) - Print the configured file mounts - diff --cc docs/content/en/commands/hugo_config_mounts.md index 06a781220,000000000..eb540acff mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_config_mounts.md +++ b/docs/content/en/commands/hugo_config_mounts.md @@@ -1,45 -1,0 +1,44 @@@ +--- +title: "hugo config mounts" +slug: hugo_config_mounts +url: /commands/hugo_config_mounts/ +--- +## hugo config mounts + +Print the configured file mounts + +``` +hugo config mounts [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for mounts + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo config](/commands/hugo_config/) - Display site configuration - ++* [hugo config](/commands/hugo_config/) - Display project configuration diff --cc docs/content/en/commands/hugo_convert.md index a8d0b6a38,000000000..f293fa4b4 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_convert.md +++ b/docs/content/en/commands/hugo_convert.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo convert" +slug: hugo_convert +url: /commands/hugo_convert/ +--- +## hugo convert + +Convert front matter to another format + +### Synopsis + +Convert front matter to another format. + +See convert's subcommands toJSON, toTOML and toYAML for more information. + +### Options + +``` + -h, --help help for convert + -o, --output string filesystem path to write files to + --unsafe enable less safe operations, please backup first +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo convert toJSON](/commands/hugo_convert_tojson/) - Convert front matter to JSON +* [hugo convert toTOML](/commands/hugo_convert_totoml/) - Convert front matter to TOML +* [hugo convert toYAML](/commands/hugo_convert_toyaml/) - Convert front matter to YAML - diff --cc docs/content/en/commands/hugo_convert_toJSON.md index fe81146f9,000000000..59a6376fe mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_convert_toJSON.md +++ b/docs/content/en/commands/hugo_convert_toJSON.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo convert toJSON" +slug: hugo_convert_toJSON +url: /commands/hugo_convert_tojson/ +--- +## hugo convert toJSON + +Convert front matter to JSON + +### Synopsis + +toJSON converts all front matter in the content directory +to use JSON for the front matter. + +``` +hugo convert toJSON [flags] [args] +``` + +### Options + +``` + -h, --help help for toJSON +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + -o, --output string filesystem path to write files to + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory + --unsafe enable less safe operations, please backup first +``` + +### SEE ALSO + +* [hugo convert](/commands/hugo_convert/) - Convert front matter to another format - diff --cc docs/content/en/commands/hugo_convert_toTOML.md index 490b15ee6,000000000..de48f71cd mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_convert_toTOML.md +++ b/docs/content/en/commands/hugo_convert_toTOML.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo convert toTOML" +slug: hugo_convert_toTOML +url: /commands/hugo_convert_totoml/ +--- +## hugo convert toTOML + +Convert front matter to TOML + +### Synopsis + +toTOML converts all front matter in the content directory +to use TOML for the front matter. + +``` +hugo convert toTOML [flags] [args] +``` + +### Options + +``` + -h, --help help for toTOML +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + -o, --output string filesystem path to write files to + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory + --unsafe enable less safe operations, please backup first +``` + +### SEE ALSO + +* [hugo convert](/commands/hugo_convert/) - Convert front matter to another format - diff --cc docs/content/en/commands/hugo_convert_toYAML.md index 9b00ce247,000000000..ae14e8e33 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_convert_toYAML.md +++ b/docs/content/en/commands/hugo_convert_toYAML.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo convert toYAML" +slug: hugo_convert_toYAML +url: /commands/hugo_convert_toyaml/ +--- +## hugo convert toYAML + +Convert front matter to YAML + +### Synopsis + +toYAML converts all front matter in the content directory +to use YAML for the front matter. + +``` +hugo convert toYAML [flags] [args] +``` + +### Options + +``` + -h, --help help for toYAML +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + -o, --output string filesystem path to write files to + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory + --unsafe enable less safe operations, please backup first +``` + +### SEE ALSO + +* [hugo convert](/commands/hugo_convert/) - Convert front matter to another format - diff --cc docs/content/en/commands/hugo_deploy.md index 696acf51f,000000000..b8c08a33f mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_deploy.md +++ b/docs/content/en/commands/hugo_deploy.md @@@ -1,55 -1,0 +1,54 @@@ +--- +title: "hugo deploy" +slug: hugo_deploy +url: /commands/hugo_deploy/ +--- +## hugo deploy + - Deploy your site to a cloud provider ++Deploy your project to a cloud provider + +### Synopsis + - Deploy your site to a cloud provider ++Deploy your project to a cloud provider + +See https://gohugo.io/hosting-and-deployment/hugo-deploy/ for detailed +documentation. + + +``` +hugo deploy [flags] [args] +``` + +### Options + +``` + --confirm ask for confirmation before making changes to the target + --dryRun dry run + --force force upload of all files + -h, --help help for deploy + --invalidateCDN invalidate the CDN cache listed in the deployment target (default true) + --maxDeletes int maximum # of files to delete, or -1 to disable (default 256) + --target string target deployment from deployments section in config file; defaults to the first one + --workers int number of workers to transfer files. defaults to 10 (default 10) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site - ++* [hugo](/commands/hugo/) - Build your project diff --cc docs/content/en/commands/hugo_env.md index 7e21733a4,000000000..007eb2ad4 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_env.md +++ b/docs/content/en/commands/hugo_env.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo env" +slug: hugo_env +url: /commands/hugo_env/ +--- +## hugo env + +Display version and environment info + +### Synopsis + +Display version and environment info. This is useful in Hugo bug reports + +``` +hugo env [flags] [args] +``` + +### Options + +``` + -h, --help help for env +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site - ++* [hugo](/commands/hugo/) - Build your project diff --cc docs/content/en/commands/hugo_gen.md index ae11a0321,000000000..605a8faa8 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_gen.md +++ b/docs/content/en/commands/hugo_gen.md @@@ -1,43 -1,0 +1,42 @@@ +--- +title: "hugo gen" +slug: hugo_gen +url: /commands/hugo_gen/ +--- +## hugo gen + +Generate documentation and syntax highlighting styles + +### Synopsis + +Generate documentation for your project using Hugo's documentation engine, including syntax highlighting for various programming languages. + +### Options + +``` + -h, --help help for gen +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo gen chromastyles](/commands/hugo_gen_chromastyles/) - Generate CSS stylesheet for the Chroma code highlighter +* [hugo gen doc](/commands/hugo_gen_doc/) - Generate Markdown documentation for the Hugo CLI +* [hugo gen man](/commands/hugo_gen_man/) - Generate man pages for the Hugo CLI - diff --cc docs/content/en/commands/hugo_gen_chromastyles.md index 78cc62f88,000000000..5d6ed753c mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_gen_chromastyles.md +++ b/docs/content/en/commands/hugo_gen_chromastyles.md @@@ -1,52 -1,0 +1,51 @@@ +--- +title: "hugo gen chromastyles" +slug: hugo_gen_chromastyles +url: /commands/hugo_gen_chromastyles/ +--- +## hugo gen chromastyles + +Generate CSS stylesheet for the Chroma code highlighter + +### Synopsis + +Generate CSS stylesheet for the Chroma code highlighter for a given style. This stylesheet is needed if markup.highlight.noClasses is disabled in config. + +See https://xyproto.github.io/splash/docs/all.html for a preview of the available styles + +``` +hugo gen chromastyles [flags] [args] +``` + +### Options + +``` + -h, --help help for chromastyles + --highlightStyle string foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff" + --lineNumbersInlineStyle string foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff" + --lineNumbersTableStyle string foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff" + --omitClassComments omit CSS class comment prefixes in the generated CSS + --omitEmpty omit empty CSS rules (deprecated, no longer needed) + --style string highlighter style (see https://xyproto.github.io/splash/docs/) (default "friendly") +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo gen](/commands/hugo_gen/) - Generate documentation and syntax highlighting styles - diff --cc docs/content/en/commands/hugo_gen_doc.md index 3d808e75c,000000000..28f061735 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_gen_doc.md +++ b/docs/content/en/commands/hugo_gen_doc.md @@@ -1,50 -1,0 +1,49 @@@ +--- +title: "hugo gen doc" +slug: hugo_gen_doc +url: /commands/hugo_gen_doc/ +--- +## hugo gen doc + +Generate Markdown documentation for the Hugo CLI + +### Synopsis + +Generate Markdown documentation for the Hugo CLI. + This command is, mostly, used to create up-to-date documentation + of Hugo's command-line interface for https://gohugo.io/. + + It creates one Markdown file per command with front matter suitable + for rendering in Hugo. + +``` +hugo gen doc [flags] [args] +``` + +### Options + +``` + --dir string the directory to write the doc. (default "/tmp/hugodoc/") + -h, --help help for doc +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo gen](/commands/hugo_gen/) - Generate documentation and syntax highlighting styles - diff --cc docs/content/en/commands/hugo_gen_man.md index 14fe859e3,000000000..7ebc9ffb8 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_gen_man.md +++ b/docs/content/en/commands/hugo_gen_man.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo gen man" +slug: hugo_gen_man +url: /commands/hugo_gen_man/ +--- +## hugo gen man + +Generate man pages for the Hugo CLI + +### Synopsis + +This command automatically generates up-to-date man pages of Hugo's + command-line interface. By default, it creates the man page files + in the "man" directory under the current directory. + +``` +hugo gen man [flags] [args] +``` + +### Options + +``` + --dir string the directory to write the man pages. (default "man/") + -h, --help help for man +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo gen](/commands/hugo_gen/) - Generate documentation and syntax highlighting styles - diff --cc docs/content/en/commands/hugo_import.md index 2b8e62951,000000000..5e38a68c4 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_import.md +++ b/docs/content/en/commands/hugo_import.md @@@ -1,43 -1,0 +1,42 @@@ +--- +title: "hugo import" +slug: hugo_import +url: /commands/hugo_import/ +--- +## hugo import + - Import a site from another system ++Import a project from another system + +### Synopsis + - Import a site from another system. ++Import a project from another system. + +Import requires a subcommand, e.g. `hugo import jekyll jekyll_root_path target_path`. + +### Options + +``` + -h, --help help for import +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo import jekyll](/commands/hugo_import_jekyll/) - hugo import from Jekyll - diff --cc docs/content/en/commands/hugo_import_jekyll.md index 8746c156e,000000000..d1f16b926 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_import_jekyll.md +++ b/docs/content/en/commands/hugo_import_jekyll.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo import jekyll" +slug: hugo_import_jekyll +url: /commands/hugo_import_jekyll/ +--- +## hugo import jekyll + +hugo import from Jekyll + +### Synopsis + +hugo import from Jekyll. - ++ +Import from Jekyll requires two paths, e.g. `hugo import jekyll jekyll_root_path target_path`. + +``` +hugo import jekyll [flags] [args] +``` + +### Options + +``` + --force allow import into non-empty target directory + -h, --help help for jekyll +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo import](/commands/hugo_import/) - Import a site from another system - ++* [hugo import](/commands/hugo_import/) - Import a project from another system diff --cc docs/content/en/commands/hugo_list.md index 741ca1d68,000000000..90b8e6d69 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list.md +++ b/docs/content/en/commands/hugo_list.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo list" +slug: hugo_list +url: /commands/hugo_list/ +--- +## hugo list + +List content + +### Synopsis + +List content. + +List requires a subcommand, e.g. hugo list drafts + +### Options + +``` + -h, --help help for list +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo list all](/commands/hugo_list_all/) - List all content +* [hugo list drafts](/commands/hugo_list_drafts/) - List draft content +* [hugo list expired](/commands/hugo_list_expired/) - List expired content +* [hugo list future](/commands/hugo_list_future/) - List future content +* [hugo list published](/commands/hugo_list_published/) - List published content - diff --cc docs/content/en/commands/hugo_list_all.md index e0f1efdcb,000000000..6b324ab17 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list_all.md +++ b/docs/content/en/commands/hugo_list_all.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo list all" +slug: hugo_list_all +url: /commands/hugo_list_all/ +--- +## hugo list all + +List all content + +### Synopsis + +List all content including draft, future, and expired. + +``` +hugo list all [flags] [args] +``` + +### Options + +``` + -h, --help help for all +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo list](/commands/hugo_list/) - List content - diff --cc docs/content/en/commands/hugo_list_drafts.md index 25ddc78d3,000000000..c6a89077c mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list_drafts.md +++ b/docs/content/en/commands/hugo_list_drafts.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo list drafts" +slug: hugo_list_drafts +url: /commands/hugo_list_drafts/ +--- +## hugo list drafts + +List draft content + +### Synopsis + +List draft content. + +``` +hugo list drafts [flags] [args] +``` + +### Options + +``` + -h, --help help for drafts +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo list](/commands/hugo_list/) - List content - diff --cc docs/content/en/commands/hugo_list_expired.md index 1936b9920,000000000..b0618ca06 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list_expired.md +++ b/docs/content/en/commands/hugo_list_expired.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo list expired" +slug: hugo_list_expired +url: /commands/hugo_list_expired/ +--- +## hugo list expired + +List expired content + +### Synopsis + +List content with a past expiration date. + +``` +hugo list expired [flags] [args] +``` + +### Options + +``` + -h, --help help for expired +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo list](/commands/hugo_list/) - List content - diff --cc docs/content/en/commands/hugo_list_future.md index 3152639c2,000000000..4f2fdcaff mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list_future.md +++ b/docs/content/en/commands/hugo_list_future.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo list future" +slug: hugo_list_future +url: /commands/hugo_list_future/ +--- +## hugo list future + +List future content + +### Synopsis + +List content with a future publication date. + +``` +hugo list future [flags] [args] +``` + +### Options + +``` + -h, --help help for future +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo list](/commands/hugo_list/) - List content - diff --cc docs/content/en/commands/hugo_list_published.md index a7a08c7b4,000000000..a49768707 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_list_published.md +++ b/docs/content/en/commands/hugo_list_published.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo list published" +slug: hugo_list_published +url: /commands/hugo_list_published/ +--- +## hugo list published + +List published content + +### Synopsis + +List content that is not draft, future, or expired. + +``` +hugo list published [flags] [args] +``` + +### Options + +``` + -h, --help help for published +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo list](/commands/hugo_list/) - List content - diff --cc docs/content/en/commands/hugo_mod.md index 25a27185d,000000000..5cc9eef4e mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod.md +++ b/docs/content/en/commands/hugo_mod.md @@@ -1,59 -1,0 +1,58 @@@ +--- +title: "hugo mod" +slug: hugo_mod +url: /commands/hugo_mod/ +--- +## hugo mod + +Manage modules + +### Synopsis + +Various helpers to help manage the modules in your project's dependency graph. +Most operations here requires a Go version installed on your system (>= Go 1.12) and the relevant VCS client (typically Git). +This is not needed if you only operate on modules inside /themes or if you have vendored them via "hugo mod vendor". + + - Note that Hugo will always start out by resolving the components defined in the site ++Note that Hugo will always start out by resolving the components defined in the project +configuration, provided by a _vendor directory (if no --ignoreVendorPaths flag provided), +Go Modules, or a folder inside the themes directory, in that order. + +See https://gohugo.io/hugo-modules/ for more information. + + + +### Options + +``` + -h, --help help for mod +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo mod clean](/commands/hugo_mod_clean/) - Delete the Hugo Module cache for the current project +* [hugo mod get](/commands/hugo_mod_get/) - Resolves dependencies in your current Hugo project +* [hugo mod graph](/commands/hugo_mod_graph/) - Print a module dependency graph +* [hugo mod init](/commands/hugo_mod_init/) - Initialize this project as a Hugo Module +* [hugo mod npm](/commands/hugo_mod_npm/) - Various npm helpers +* [hugo mod tidy](/commands/hugo_mod_tidy/) - Remove unused entries in go.mod and go.sum +* [hugo mod vendor](/commands/hugo_mod_vendor/) - Vendor all module dependencies into the _vendor directory +* [hugo mod verify](/commands/hugo_mod_verify/) - Verify dependencies - diff --cc docs/content/en/commands/hugo_mod_clean.md index ff2255e53,000000000..9abb1cbd9 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_clean.md +++ b/docs/content/en/commands/hugo_mod_clean.md @@@ -1,51 -1,0 +1,50 @@@ +--- +title: "hugo mod clean" +slug: hugo_mod_clean +url: /commands/hugo_mod_clean/ +--- +## hugo mod clean + +Delete the Hugo Module cache for the current project + +### Synopsis + +Delete the Hugo Module cache for the current project. + +``` +hugo mod clean [flags] [args] +``` + +### Options + +``` + --all clean entire module cache + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for clean + --pattern string pattern matching module paths to clean (all if not set), e.g. "**hugo*" + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_get.md index a5c9a9ea9,000000000..a7eebd7ea mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_get.md +++ b/docs/content/en/commands/hugo_mod_get.md @@@ -1,75 -1,0 +1,74 @@@ +--- +title: "hugo mod get" +slug: hugo_mod_get +url: /commands/hugo_mod_get/ +--- +## hugo mod get + +Resolves dependencies in your current Hugo project + +### Synopsis + + +Resolves dependencies in your current Hugo project. + +Some examples: + +Install the latest version possible for a given module: + + hugo mod get github.com/gohugoio/testshortcodes + +Install a specific version: + + hugo mod get github.com/gohugoio/testshortcodes@v0.3.0 + +Install the latest versions of all direct module dependencies: + + hugo mod get + hugo mod get ./... (recursive) + +Install the latest versions of all module dependencies (direct and indirect): + + hugo mod get -u + hugo mod get -u ./... (recursive) + +Run "go help get" for more information. All flags available for "go get" is also relevant here. + - Note that Hugo will always start out by resolving the components defined in the site ++Note that Hugo will always start out by resolving the components defined in the project +configuration, provided by a _vendor directory (if no --ignoreVendorPaths flag provided), +Go Modules, or a folder inside the themes directory, in that order. + +See https://gohugo.io/hugo-modules/ for more information. + + + +``` +hugo mod get [flags] [args] +``` + +### Options + +``` + -h, --help help for get +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_graph.md index cb2bdfb5a,000000000..2e840918c mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_graph.md +++ b/docs/content/en/commands/hugo_mod_graph.md @@@ -1,52 -1,0 +1,51 @@@ +--- +title: "hugo mod graph" +slug: hugo_mod_graph +url: /commands/hugo_mod_graph/ +--- +## hugo mod graph + +Print a module dependency graph + +### Synopsis + +Print a module dependency graph with information about module status (disabled, vendored). +Note that for vendored modules, that is the version listed and not the one from go.mod. + + +``` +hugo mod graph [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + --clean delete module cache for dependencies that fail verification + -c, --contentDir string filesystem path to content directory + -h, --help help for graph + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_init.md index 3315e97d6,000000000..05d785caf mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_init.md +++ b/docs/content/en/commands/hugo_mod_init.md @@@ -1,56 -1,0 +1,55 @@@ +--- +title: "hugo mod init" +slug: hugo_mod_init +url: /commands/hugo_mod_init/ +--- +## hugo mod init + +Initialize this project as a Hugo Module + +### Synopsis + +Initialize this project as a Hugo Module. + It will try to guess the module path, but you may help by passing it as an argument, e.g: + + hugo mod init github.com/gohugoio/testshortcodes + + Note that Hugo Modules supports multi-module projects, so you can initialize a Hugo Module + inside a subfolder on GitHub, as one example. + + +``` +hugo mod init [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for init + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_npm.md index 39a559e0f,000000000..eafda1768 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_npm.md +++ b/docs/content/en/commands/hugo_mod_npm.md @@@ -1,45 -1,0 +1,44 @@@ +--- +title: "hugo mod npm" +slug: hugo_mod_npm +url: /commands/hugo_mod_npm/ +--- +## hugo mod npm + +Various npm helpers + +### Synopsis + +Various npm (Node package manager) helpers. + +``` +hugo mod npm [command] [flags] +``` + +### Options + +``` + -h, --help help for npm +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules +* [hugo mod npm pack](/commands/hugo_mod_npm_pack/) - Experimental: Prepares and writes a composite package.json file for your project - diff --cc docs/content/en/commands/hugo_mod_npm_pack.md index 5ece05769,000000000..8637d7486 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_npm_pack.md +++ b/docs/content/en/commands/hugo_mod_npm_pack.md @@@ -1,59 -1,0 +1,58 @@@ +--- +title: "hugo mod npm pack" +slug: hugo_mod_npm_pack +url: /commands/hugo_mod_npm_pack/ +--- +## hugo mod npm pack + +Experimental: Prepares and writes a composite package.json file for your project + +### Synopsis + +Prepares and writes a composite package.json file for your project. + +On first run it creates a "package.hugo.json" in the project root if not already there. This file will be used as a template file +with the base dependency set. + +This set will be merged with all "package.hugo.json" files found in the dependency tree, picking the version closest to the project. + +This command is marked as 'Experimental'. We think it's a great idea, so it's not likely to be +removed from Hugo, but we need to test this out in "real life" to get a feel of it, +so this may/will change in future versions of Hugo. + + +``` +hugo mod npm pack [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for pack + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod npm](/commands/hugo_mod_npm/) - Various npm helpers - diff --cc docs/content/en/commands/hugo_mod_tidy.md index c7ae40625,000000000..1114772d5 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_tidy.md +++ b/docs/content/en/commands/hugo_mod_tidy.md @@@ -1,45 -1,0 +1,44 @@@ +--- +title: "hugo mod tidy" +slug: hugo_mod_tidy +url: /commands/hugo_mod_tidy/ +--- +## hugo mod tidy + +Remove unused entries in go.mod and go.sum + +``` +hugo mod tidy [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for tidy + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_vendor.md index dc403affe,000000000..4e828fe35 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_vendor.md +++ b/docs/content/en/commands/hugo_mod_vendor.md @@@ -1,51 -1,0 +1,50 @@@ +--- +title: "hugo mod vendor" +slug: hugo_mod_vendor +url: /commands/hugo_mod_vendor/ +--- +## hugo mod vendor + +Vendor all module dependencies into the _vendor directory + +### Synopsis + +Vendor all module dependencies into the _vendor directory. + If a module is vendored, that is where Hugo will look for it's dependencies. + + +``` +hugo mod vendor [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + -h, --help help for vendor + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_mod_verify.md index 2f22a2e49,000000000..6c15a88c2 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_mod_verify.md +++ b/docs/content/en/commands/hugo_mod_verify.md @@@ -1,50 -1,0 +1,49 @@@ +--- +title: "hugo mod verify" +slug: hugo_mod_verify +url: /commands/hugo_mod_verify/ +--- +## hugo mod verify + +Verify dependencies + +### Synopsis + +Verify checks that the dependencies of the current module, which are stored in a local downloaded source cache, have not been modified since being downloaded. + +``` +hugo mod verify [flags] [args] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + --clean delete module cache for dependencies that fail verification + -c, --contentDir string filesystem path to content directory + -h, --help help for verify + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo mod](/commands/hugo_mod/) - Manage modules - diff --cc docs/content/en/commands/hugo_new.md index 56ab4aef9,000000000..a6587e469 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_new.md +++ b/docs/content/en/commands/hugo_new.md @@@ -1,50 -1,0 +1,49 @@@ +--- +title: "hugo new" +slug: hugo_new +url: /commands/hugo_new/ +--- +## hugo new + +Create new content + +### Synopsis + +Create a new content file and automatically set the date and title. +It will guess which kind of file to create based on the path provided. + +You can also specify the kind with `-k KIND`. + - If archetypes are provided in your theme or site, they will be used. ++If archetypes are provided in your theme or project, they will be used. + - Ensure you run this within the root directory of your site. ++Ensure you run this within the root directory of your project. + +### Options + +``` + -h, --help help for new +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo new content](/commands/hugo_new_content/) - Create new content - * [hugo new site](/commands/hugo_new_site/) - Create a new site ++* [hugo new project](/commands/hugo_new_project/) - Create a new project +* [hugo new theme](/commands/hugo_new_theme/) - Create a new theme - diff --cc docs/content/en/commands/hugo_new_content.md index 9624e9a61,000000000..0a5b5439e mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_new_content.md +++ b/docs/content/en/commands/hugo_new_content.md @@@ -1,59 -1,0 +1,58 @@@ +--- +title: "hugo new content" +slug: hugo_new_content +url: /commands/hugo_new_content/ +--- +## hugo new content + +Create new content + +### Synopsis + +Create a new content file and automatically set the date and title. +It will guess which kind of file to create based on the path provided. + +You can also specify the kind with `-k KIND`. + - If archetypes are provided in your theme or site, they will be used. ++If archetypes are provided in your theme or project, they will be used. + - Ensure you run this within the root directory of your site. ++Ensure you run this within the root directory of your project. + +``` +hugo new content [path] [flags] +``` + +### Options + +``` + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --cacheDir string filesystem path to cache directory + -c, --contentDir string filesystem path to content directory + --editor string edit new content with this editor, if provided + -f, --force overwrite file if it already exists + -h, --help help for content + -k, --kind string content type to create + --renderSegments strings named segments to render (configured in the segments config) + -t, --theme strings themes to use (located in /themes/THEMENAME/) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo new](/commands/hugo_new/) - Create new content - diff --cc docs/content/en/commands/hugo_new_project.md index 000000000,000000000..652eefec6 new file mode 100644 --- /dev/null +++ b/docs/content/en/commands/hugo_new_project.md @@@ -1,0 -1,0 +1,45 @@@ ++--- ++title: "hugo new project" ++slug: hugo_new_project ++url: /commands/hugo_new_project/ ++--- ++## hugo new project ++ ++Create a new project ++ ++### Synopsis ++ ++Create a new project at the specified path. ++ ++``` ++hugo new project [path] [flags] ++``` ++ ++### Options ++ ++``` ++ -f, --force init inside non-empty directory ++ --format string preferred file format (toml, yaml or json) (default "toml") ++ -h, --help help for project ++``` ++ ++### Options inherited from parent commands ++ ++``` ++ --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 ++ --config string config file (default is hugo.yaml|json|toml) ++ --configDir string config dir (default "config") ++ -d, --destination string filesystem path to write files to ++ -e, --environment string build environment ++ --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern ++ --logLevel string log level (debug|info|warn|error) ++ --noBuildLock don't create .hugo_build.lock file ++ --quiet build in quiet mode ++ -M, --renderToMemory render to memory (mostly useful when running the server) ++ -s, --source string filesystem path to read files relative from ++ --themesDir string filesystem path to themes directory ++``` ++ ++### SEE ALSO ++ ++* [hugo new](/commands/hugo_new/) - Create new content diff --cc docs/content/en/commands/hugo_new_theme.md index 140660077,000000000..7a7e0407b mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_new_theme.md +++ b/docs/content/en/commands/hugo_new_theme.md @@@ -1,46 -1,0 +1,45 @@@ +--- +title: "hugo new theme" +slug: hugo_new_theme +url: /commands/hugo_new_theme/ +--- +## hugo new theme + +Create a new theme + +### Synopsis + +Create a new theme with the specified name in the ./themes directory. +This generates a functional theme including template examples and sample content. + +``` +hugo new theme [name] [flags] +``` + +### Options + +``` + --format string preferred file format (toml, yaml or json) (default "toml") + -h, --help help for theme +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo new](/commands/hugo_new/) - Create new content - diff --cc docs/content/en/commands/hugo_server.md index d735f449a,000000000..4345fbd7a mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_server.md +++ b/docs/content/en/commands/hugo_server.md @@@ -1,98 -1,0 +1,97 @@@ +--- +title: "hugo server" +slug: hugo_server +url: /commands/hugo_server/ +--- +## hugo server + +Start the embedded web server + +### Synopsis + - Hugo provides its own webserver which builds and serves the site. ++Hugo provides its own webserver which builds and serves the project. +While hugo server is high performance, it is a webserver with limited options. + +The `hugo server` command will by default write and serve files from disk, but +you can render to memory by using the `--renderToMemory` flag. This can be +faster in some cases, but it will consume more memory. + +By default hugo will also watch your files for any changes you make and - automatically rebuild the site. It will then live reload any open browser pages - and push the latest content to them. As most Hugo sites are built in a fraction ++automatically rebuild the project. It will then live reload any open browser pages ++and push the latest content to them. As most Hugo projects are built in a fraction +of a second, you will be able to save and see your changes nearly instantly. + +``` +hugo server [command] [flags] +``` + +### Options + +``` + --appendPort append port to baseURL (default true) + -b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/ + --bind string interface to which the server will bind (default "127.0.0.1") + -D, --buildDrafts include content marked as draft + -E, --buildExpired include expired content + -F, --buildFuture include content with publishdate in the future + --cacheDir string filesystem path to cache directory + --cleanDestinationDir remove files from destination not found in static directories + -c, --contentDir string filesystem path to content directory + --disableBrowserError do not show build errors in the browser + --disableFastRender enables full re-renders on changes + --disableKinds strings disable different kind of pages (home, RSS etc.) + --disableLiveReload watch without enabling live browser reload on rebuild + --enableGitInfo add Git revision, date, author, and CODEOWNERS info to the pages + --forceSyncStatic copy all files when static is changed. + --gc enable to run some cleanup tasks (remove unused cache files) after the build + -h, --help help for server + --ignoreCache ignores the cache directory + -l, --layoutDir string filesystem path to layout directory + --liveReloadPort int port for live reloading (i.e. 443 in HTTPS proxy situations) (default -1) + --minify minify any supported output format (HTML, XML etc.) + -N, --navigateToChanged navigate to changed content file on live browser reload + --noChmod don't sync permission mode of files + --noHTTPCache prevent HTTP caching + --noTimes don't sync modification time of files - -O, --openBrowser open the site in a browser after server startup ++ -O, --openBrowser open the project in a browser after server startup + --panicOnWarning panic on first WARNING log + --poll string set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes + -p, --port int port on which the server will listen (default 1313) + --pprof enable the pprof server (port 8080) + --printI18nWarnings print missing translations + --printMemoryUsage print memory usage to screen at intervals + --printPathWarnings print warnings on duplicate target paths etc. + --printUnusedTemplates print warnings on unused templates. + --renderSegments strings named segments to render (configured in the segments config) + --renderStaticToDisk serve static files from disk and dynamic files from memory + --templateMetrics display metrics about template executions + --templateMetricsHints calculate some improvement hints when combined with --templateMetrics + -t, --theme strings themes to use (located in /themes/THEMENAME/) + --tlsAuto generate and use locally-trusted certificates. + --tlsCertFile string path to TLS certificate file + --tlsKeyFile string path to TLS key file + --trace file write trace to file (not useful in general) + -w, --watch watch filesystem for changes and recreate as needed (default true) +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site ++* [hugo](/commands/hugo/) - Build your project +* [hugo server trust](/commands/hugo_server_trust/) - Install the local CA in the system trust store - diff --cc docs/content/en/commands/hugo_server_trust.md index 22ca2491e,000000000..86498385e mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_server_trust.md +++ b/docs/content/en/commands/hugo_server_trust.md @@@ -1,41 -1,0 +1,40 @@@ +--- +title: "hugo server trust" +slug: hugo_server_trust +url: /commands/hugo_server_trust/ +--- +## hugo server trust + +Install the local CA in the system trust store + +``` +hugo server trust [flags] [args] +``` + +### Options + +``` + -h, --help help for trust + --uninstall Uninstall the local CA (but do not delete it). +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + +* [hugo server](/commands/hugo_server/) - Start the embedded web server - diff --cc docs/content/en/commands/hugo_version.md index 14cc92a00,000000000..e71abdc28 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_version.md +++ b/docs/content/en/commands/hugo_version.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: "hugo version" +slug: hugo_version +url: /commands/hugo_version/ +--- +## hugo version + +Display version + +### Synopsis + +Display version and environment info. This is useful in Hugo bug reports. + +``` +hugo version [flags] [args] +``` + +### Options + +``` + -h, --help help for version +``` + +### Options inherited from parent commands + +``` + --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 + --config string config file (default is hugo.yaml|json|toml) + --configDir string config dir (default "config") + -d, --destination string filesystem path to write files to + -e, --environment string build environment + --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern + --logLevel string log level (debug|info|warn|error) + --noBuildLock don't create .hugo_build.lock file + --quiet build in quiet mode + -M, --renderToMemory render to memory (mostly useful when running the server) + -s, --source string filesystem path to read files relative from + --themesDir string filesystem path to themes directory +``` + +### SEE ALSO + - * [hugo](/commands/hugo/) - Build your site - ++* [hugo](/commands/hugo/) - Build your project diff --cc docs/content/en/configuration/all.md index fe8e3248d,000000000..cff51a2ae mode 100644,000000..100644 --- a/docs/content/en/configuration/all.md +++ b/docs/content/en/configuration/all.md @@@ -1,430 -1,0 +1,429 @@@ +--- +title: All settings +description: The complete list of Hugo configuration settings. +categories: [] +keywords: [] +weight: 20 +aliases: [/getting-started/configuration/] +--- + +## Settings + +archetypeDir +: (`string`) The designated directory for [archetypes](g). Default is `archetypes`. {{% module-mounts-note %}} + +assetDir +: (`string`) The designated directory for [global resources](g). Default is `assets`. {{% module-mounts-note %}} + +baseURL +: (`string`) The absolute URL of your published site including the protocol, host, path, and a trailing slash. + +build +: See [configure build][]. + +buildDrafts +: (`bool`) Whether to include draft content when building a site. Default is `false`. + +buildExpired +: (`bool`) Whether to include expired content when building a site. Default is `false`. + +buildFuture +: (`bool`) Whether to include future content when building a site. Default is `false`. + +cacheDir +: (`string`) The designated cache directory. See [details](#cache-directory). + +caches +: See [configure file caches][]. + +canonifyURLs +: (`bool`) See [details](/content-management/urls/#canonical-urls) before enabling this feature. Default is `false`. + +capitalizeListTitles +: (`bool`) Whether to capitalize automatic list titles. Applicable to section, taxonomy, and term pages. Use the [`titleCaseStyle`][] setting to configure capitalization rules. Default is `true`. + +cascade +: See [configure cascade][]. + +cleanDestinationDir +: (`bool`) Whether to remove files from the [`publishDir`][] that do not exist in the [`staticDir`][] when building the site. This setting will not take effect if the `staticDir` does not exist. Note that `.gitignore` and `.gitattributes` files, along with directories named `.git`, are always preserved in the `publishDir`. Default is `false`. + +contentDir +: (`string`) The designated directory for content files. Default is `content`. {{% module-mounts-note %}} + +copyright +: (`string`) The copyright notice for a site, typically displayed in the footer. + +dataDir +: (`string`) The designated directory for data files. Default is `data`. {{% module-mounts-note %}} + +defaultContentLanguage - : (`string`) The projects's default content language, conforming to the syntax described in [RFC 5646][]. This value must match one of the defined [language keys][]. Default is `en`. ++: (`string`) The projects's [default language](g), conforming to the syntax described in [RFC 5646][]. + +defaultContentLanguageInSubdir +: (`bool`) Whether to publish the default content language to a subdirectory matching the [`defaultContentLanguage`][]. Default is `false`. + +defaultContentRole +: {{< new-in 0.153.0 />}} - : (`string`) The project's default content [role](g). Default is `guest`. ++: (`string`) The project's [default role](g). + +defaultContentRoleInSubdir +: {{< new-in 0.153.0 />}} +: (`bool`) Whether to publish the default content [role](g) to a subdirectory matching the [`defaultContentRole`][]. Default is `false`. + +defaultContentVersion +: {{< new-in 0.153.0 />}} - : (`string`) The project's default content version. Default is `v1.0.0`. ++: (`string`) The project's [default version](g). + +defaultContentVersionInSubdir +: {{< new-in 0.153.0 />}} +: (`bool`) Whether to publish the default content version to a subdirectory matching the [`defaultContentVersion`][]. Default is `false`. + +defaultOutputFormat +: (`string`) The default output format for the site. If unspecified, the first available format in the defined order (by weight, then alphabetically) will be used. + +deployment +: See [configure deployment][]. + +disableAliases +: (`bool`) Whether to disable the generation of HTML redirect files for each path defined in the [`aliases`][aliases_front_matter] front matter field. When `true`, Hugo will not create physical files for [client-side redirection][], but the alias data remains available via the [`Aliases`][aliases_page_method] method on a `Page` object. Default is `false`. + +disableDefaultLanguageRedirect +: {{< new-in 0.140.0 />}} +: (`bool`) Whether to disable generation of the alias redirect for the default content language. When [`defaultContentLanguageInSubdir`][] is `true`, this setting prevents the root directory from redirecting to the language subdirectory. Conversely, when `defaultContentLanguageInSubdir` is `false`, this setting prevents the language subdirectory from redirecting to the root directory. This is superseded by the more general [`disableDefaultSiteRedirect`][] setting. Default is `false`. + +disableDefaultSiteRedirect +: {{< new-in 0.154.5 />}} - : (bool) Whether to disable generation of the alias redirect to the [default site](g). When [`defaultContentLanguageInSubdir`][], [`defaultContentRoleInSubdir`][], or [`defaultContentVersionInSubdir`][] is `true`, this prevents the root directory from redirecting to the default site's subdirectory. Conversely, when these are `false`, it prevents the subdirectories from redirecting back to the root. The default site is the site with the default content language, version, and role. Default is `false`. ++: (bool) Whether to disable generation of the alias redirect to the [default site](g). When [`defaultContentLanguageInSubdir`][], [`defaultContentRoleInSubdir`][], or [`defaultContentVersionInSubdir`][] is `true`, this prevents the root directory from redirecting to the default site's subdirectory. Conversely, when these are `false`, it prevents the subdirectories from redirecting back to the root. Default is `false`. + +disableHugoGeneratorInject +: (`bool`) Whether to disable injection of a `` tag into the home page. Default is `false`. + +disableKinds +: (`[]string`) A slice of page [kinds](g) to disable during the build process, any of `404`, `home`, `page`, `robotstxt`, `rss`, `section`, `sitemap`, `taxonomy`, or `term`. + +disableLanguages +: (`[]string`) A slice of language keys representing the languages to disable during the build process. Although this is functional, consider using the [`disabled`][] key under each language instead. + +disableLiveReload +: (`bool`) Whether to disable automatic live reloading of the browser window. Default is `false`. + +disablePathToLower +: (`bool`) Whether to disable transformation of page URLs to lower case. Default is `false`. + +enableEmoji +: (`bool`) Whether to allow emoji in Markdown. Default is `false`. + +enableGitInfo +: (`bool`) For sites under Git version control, whether to enable the [`GitInfo`][] object for each page. With the [default front matter configuration][], the `Lastmod` method on a `Page` object will return the Git author date. Default is `false`. + +enableMissingTranslationPlaceholders +: (`bool`) Whether to show a placeholder instead of the default value or an empty string if a translation is missing. Default is `false`. + +enableRobotsTXT +: (`bool`) Whether to enable generation of a `robots.txt` file. Default is `false`. + +environment - : (`string`) The build environment. Default is `production` when running `hugo` and `development` when running `hugo server`. ++: (`string`) The build environment. Default is `production` when running `hugo build` and `development` when running `hugo server`. + +frontmatter +: See [configure front matter][]. + +hasCJKLanguage +: (`bool`) Whether to automatically detect [CJK](g) languages in content. Affects the values returned by the [`WordCount`][] and [`FuzzyWordCount`][] methods. Default is `false`. + +HTTPCache +: See [configure HTTP cache][]. + +i18nDir +: (`string`) The designated directory for translation tables. Default is `i18n`. {{% module-mounts-note %}} + +ignoreCache +: (`bool`) Whether to ignore the cache directory. Default is `false`. + +ignoreFiles +: (`[]string`) A slice of [regular expressions](g) used to exclude specific files from a build. These expressions are matched against the absolute file path and apply to files within the `content`, `data`, and `i18n` directories. For more advanced file exclusion options, see the section on [module mounts][]. + +ignoreLogs +: (`[]string`) A slice of message identifiers corresponding to warnings and errors you wish to suppress. See [`erroridf`][] and [`warnidf`][]. + +ignoreVendorPaths +: (`string`) A [glob pattern](g) matching the module paths to exclude from the `_vendor` directory. + +imaging +: See [configure imaging][]. + +languageCode +: (`string`) The site's language tag, conforming to the syntax described in [RFC 5646][]. This value does not affect translations or localization. Hugo uses this value to populate: + + - The `language` element in the [embedded RSS template][] + - The `lang` attribute of the `html` element in the [embedded alias template][] + - The `og:locale` `meta` element in the [embedded Open Graph template][] + + When present in the root of the configuration, this value is ignored if one or more language keys exists. Please specify this value independently for each language key. + +languages +: See [configure languages][]. + +layoutDir +: (`string`) The designated directory for templates. Default is `layouts`. {{% module-mounts-note %}} + +mainSections +: (`string` or `[]string`) The main sections of a site. If set, the [`MainSections`][] method on the `Site` object returns the given sections, otherwise it returns the section with the most pages. + +markup +: See [configure markup][]. + +mediaTypes +: See [configure media types][]. + +menus +: See [configure menus][]. + +minify +: See [configure minify][]. + +module +: See [configure modules][]. + +newContentEditor +: (`string`) The editor to use when creating new content. + +noBuildLock +: (`bool`) Whether to disable creation of the `.hugo_build.lock` file. Default is `false`. + +noChmod +: (`bool`) Whether to disable synchronization of file permission modes. Default is `false`. + +noTimes +: (`bool`) Whether to disable synchronization of file modification times. Default is `false`. + +outputFormats +: See [configure output formats][]. + +outputs +: See [configure outputs][]. + +page +: See [configure page][]. + +pagination +: See [configure pagination][]. + +panicOnWarning +: (`bool`) Whether to panic on the first WARNING. Default is `false`. + +params +: See [configure params][]. + +permalinks +: See [configure permalinks][]. + +pluralizeListTitles +: (`bool`) Whether to pluralize automatic list titles. Applicable to section pages. Default is `true`. + +printI18nWarnings +: (`bool`) Whether to log WARNINGs for each missing translation. Default is `false`. + +printPathWarnings +: (`bool`) Whether to log WARNINGs when Hugo publishes two or more files to the same path. Default is `false`. + +printUnusedTemplates +: (`bool`) Whether to log WARNINGs for each unused template. Default is `false`. + +privacy +: See [configure privacy][]. + +publishDir +: (`string`) The designated directory for publishing the site. Default is `public`. + +refLinksErrorLevel +: (`string`) The logging error level to use when the `ref` and `relref` functions, methods, and shortcodes are unable to resolve a reference to a page. Either `ERROR` or `WARNING`. Any `ERROR` will fail the build. Default is `ERROR`. + +refLinksNotFoundURL +: (`string`) The URL to return when the `ref` and `relref` functions, methods, and shortcodes are unable to resolve a reference to a page. + +related +: See [configure related content][]. + +relativeURLs +: (`bool`) See [details](/content-management/urls/#relative-urls) before enabling this feature. Default is `false`. + +removePathAccents +: (`bool`) Whether to remove [non-spacing marks][] from [composite characters][] in content paths. Default is `false`. + +renderSegments - : (`[]string`) A slice of [segments](g) to render. If omitted, all segments are rendered. This option is typically set via a command-line flag, such as `hugo --renderSegments segment1,segment2`. The provided segment names must correspond to those defined in the [`segments`][] configuration. ++: (`[]string`) A slice of [segments](g) to render. If omitted, all segments are rendered. This option is typically set via a command-line flag, such as `hugo build --renderSegments segment1,segment2`. The provided segment names must correspond to those defined in the [`segments`][] configuration. + +resourceDir +: (`string`) The designated directory for caching output from [asset pipelines](g). Default is `resources`. + +roles +: See [configure roles][]. + +security +: See [configure security][]. + +sectionPagesMenu +: (`string`) When set, each top-level section will be added to the menu identified by the provided value. See [details](/content-management/menus/#define-automatically). + +segments +: See [configure segments][]. + +server +: See [configure server][]. + +services +: See [configure services][]. + +sitemap +: See [configure sitemap][]. + +staticDir +: (`string`) The designated directory for static files. Default is `static`. {{% module-mounts-note %}} + +summaryLength +: (`int`) Applicable to [automatic summaries][], the minimum number of words returned by the [`Summary`][] method on a `Page` object. The `Summary` method will return content truncated at the paragraph boundary closest to the specified `summaryLength`, but at least this minimum number of words. Default is `70`. + +taxonomies +: See [configure taxonomies][]. + +templateMetrics +: (`bool`) Whether to print template execution metrics to the console. Default is `false`. See [details](/troubleshooting/performance/#template-metrics). + +templateMetricsHints +: (`bool`) Whether to print template execution improvement hints to the console. Applicable when `templateMetrics` is `true`. Default is `false`. See [details](/troubleshooting/performance/#template-metrics). + +theme +: (`string` or `[]string`) The [theme](g) to use. Multiple themes can be listed, with precedence given from left to right. See [details](/hugo-modules/theme-components/). + +themesDir +: (`string`) The designated directory for themes. Default is `themes`. + +timeout +: (`string`) The timeout for generating page content, either as a [duration][] or in seconds. This timeout is used to prevent infinite recursion during content generation. You may need to increase this value if your pages take a long time to generate, for example, due to extensive image processing or reliance on remote content. Default is `60s`. + +timeZone +: (`string`) The time zone used to parse dates without time zone offsets, including front matter date fields and values passed to the [`time.AsTime`][] and [`time.Format`][] template functions. The list of valid values may be system dependent, but should include `UTC`, `Local`, and any location in the [IANA Time Zone Database][]. For example, `America/Los_Angeles` and `Europe/Oslo` are valid time zones. + +title +: (`string`) The site title. + +titleCaseStyle +: (`string`) The capitalization rules to follow when Hugo automatically generates a section title, or when using the [`strings.Title`][] function. One of `ap`, `chicago`, `go`, `firstupper`, or `none`. Default is `ap`. See [details](#title-case-style). + +uglyurls +: See [configure ugly URLs][]. + +versions +: See [configure versions][]. + +## Cache directory + +Hugo's file cache directory is configurable via the [`cacheDir`][] configuration option or the `HUGO_CACHEDIR` environment variable. If neither is set, Hugo will use, in order of preference: + +1. If running on Netlify: `/opt/build/cache/hugo_cache/`. This means that if you run your builds on Netlify, all caches configured with `:cacheDir` will be saved and restored on the next build. For other [CI/CD](g) platforms, please read their documentation. For a CircleCI example, see [this configuration][]. +1. In a `hugo_cache` directory below the OS user cache directory as defined by Go's [os.UserCacheDir][] function. On Unix systems, per the [XDG base directory specification][], this is `$XDG_CACHE_HOME` if non-empty, else `$HOME/.cache`. On MacOS, this is `$HOME/Library/Caches`. On Windows, this is`%LocalAppData%`. On Plan 9, this is `$home/lib/cache`. +1. In a `hugo_cache_$USER` directory below the OS temp dir. + +To determine the current `cacheDir`: + +```sh +hugo config | grep cachedir +``` + +## Title case style + +Hugo's [`titleCaseStyle`][] setting governs capitalization for automatically generated section titles and the [`strings.Title`][] function. By default, it follows the capitalization rules published in the Associated Press Stylebook. Change this setting to use other capitalization rules. + +ap +: Use the capitalization rules published in the [Associated Press Stylebook][]. This is the default. + +chicago +: Use the capitalization rules published in the [Chicago Manual of Style][]. + +go +: Capitalize the first letter of every word. + +firstupper +: Capitalize the first letter of the first word. + +none +: Disable transformation of automatic section titles, and disable the transformation performed by the `strings.Title` function. This is useful if you would prefer to manually capitalize section titles as needed, and to bypass opinionated theme usage of the `strings.Title` function. + +## Localized settings + +Some configuration settings, such as menus and custom parameters, can be defined separately for each language. See [configure languages][]. + +[`cacheDir`]: #cachedir +[`defaultContentLanguage`]: #defaultcontentlanguage +[`defaultContentLanguageInSubdir`]: #defaultcontentlanguageinsubdir +[`defaultContentRole`]: #defaultcontentrole +[`defaultContentRoleInSubdir`]: #defaultcontentroleinsubdir +[`defaultContentVersion`]: #defaultcontentversion +[`defaultContentVersionInSubdir`]: #defaultcontentversioninsubdir +[`disabled`]: /configuration/languages/#disabled +[`disableDefaultSiteRedirect`]: #disabledefaultsiteredirect +[`erroridf`]: /functions/fmt/erroridf/ +[`FuzzyWordCount`]: /methods/page/fuzzywordcount/ +[`GitInfo`]: /methods/page/gitinfo/ +[`MainSections`]: /methods/site/mainsections/ +[`publishDir`]: #publishdir +[`segments`]: /configuration/segments/ +[`staticDir`]: #staticdir +[`strings.Title`]: /functions/strings/title/ +[`Summary`]: /methods/page/summary/ +[`time.AsTime`]: /functions/time/astime/ +[`time.Format`]: /functions/time/format/ +[`titleCaseStyle`]: #titlecasestyle +[`warnidf`]: /functions/fmt/warnidf/ +[`WordCount`]: /methods/page/wordcount/ +[aliases_front_matter]: /content-management/front-matter/#aliases +[aliases_page_method]: /methods/page/aliases/ +[Associated Press Stylebook]: https://www.apstylebook.com/ +[automatic summaries]: /content-management/summaries/#automatic-summary +[Chicago Manual of Style]: https://www.chicagomanualofstyle.org/home.html +[client-side redirection]: /content-management/urls/#client-side-redirection +[composite characters]: https://en.wikipedia.org/wiki/Precomposed_character +[configure build]: /configuration/build/ +[configure cascade]: /configuration/cascade/ +[configure deployment]: /configuration/deployment/ +[configure file caches]: /configuration/caches/ +[configure front matter]: /configuration/front-matter/ +[configure HTTP cache]: /configuration/http-cache/ +[configure imaging]: /configuration/imaging/ +[configure languages]: /configuration/languages/ +[configure markup]: /configuration/markup/ +[configure media types]: /configuration/media-types/ +[configure menus]: /configuration/menus/ +[configure minify]: /configuration/minify/ +[configure modules]: /configuration/module/ +[configure output formats]: /configuration/output-formats/ +[configure outputs]: /configuration/outputs/ +[configure page]: /configuration/page/ +[configure pagination]: /configuration/pagination/ +[configure params]: /configuration/params/ +[configure permalinks]: /configuration/permalinks/ +[configure privacy]: /configuration/privacy/ +[configure related content]: /configuration/related-content +[configure roles]: /configuration/roles/ +[configure security]: /configuration/security/ +[configure segments]: /configuration/segments/ +[configure server]: /configuration/server/ +[configure services]: /configuration/services/ +[configure sitemap]: /configuration/sitemap/ +[configure taxonomies]: /configuration/taxonomies/ +[configure ugly URLs]: /configuration/ugly-urls/ +[configure versions]: /configuration/versions/ +[default front matter configuration]: /configuration/front-matter/ +[duration]: https://pkg.go.dev/time#Duration +[embedded alias template]: <{{% eturl alias %}}> +[embedded Open Graph template]: <{{% eturl opengraph %}}> +[embedded RSS template]: <{{% eturl rss %}}> +[IANA Time Zone Database]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - [language keys]: /configuration/languages/#language-keys +[module mounts]: /configuration/module/#mounts +[non-spacing marks]: https://www.compart.com/en/unicode/category/Mn +[os.UserCacheDir]: https://pkg.go.dev/os#UserCacheDir +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 +[this configuration]: https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml +[XDG base directory specification]: https://specifications.freedesktop.org/basedir-spec/latest/ diff --cc docs/content/en/configuration/build.md index 1354f0860,000000000..77432cf1a mode 100644,000000..100644 --- a/docs/content/en/configuration/build.md +++ b/docs/content/en/configuration/build.md @@@ -1,83 -1,0 +1,83 @@@ +--- +title: Configure build +linkTitle: Build +description: Configure global build options. +categories: [] +keywords: [] +aliases: [/getting-started/configuration-build/] +--- + +The `build` configuration section contains global build-related configuration options. + +{{< code-toggle config=build />}} + +buildStats +: See the [build stats](#build-stats) section below. + +cachebusters +: See the [cache busters](#cache-busters) section below. + +noJSConfigInAssets +: (`bool`) Whether to disable writing a `jsconfig.json` in your `assets` directory with mapping of imports from running [js.Build](/hugo-pipes/js). This file is intended to help with intellisense/navigation inside code editors such as [VS Code](https://code.visualstudio.com/). Note that if you do not use `js.Build`, no file will be written. + +useResourceCacheWhen +: (`string`) When to use the resource file cache, one of `never`, `fallback`, or `always`. Applicable when transpiling Sass to CSS. Default is `fallback`. + +## Cache busters + +The `build.cachebusters` configuration option was added to support development using Tailwind 3.x's JIT compiler where a `build` configuration may look like this: + + +{{< code-toggle file=hugo >}} +[build] + [build.buildStats] + enable = true + [[build.cachebusters]] + source = "assets/watching/hugo_stats\\.json" + target = "styles\\.css" + [[build.cachebusters]] + source = "(postcss|tailwind)\\.config\\.js" + target = "css" + [[build.cachebusters]] + source = "assets/.*\\.(js|ts|jsx|tsx)" + target = "js" + [[build.cachebusters]] + source = "assets/.*\\.(.*)$" + target = "$1" +{{< /code-toggle >}} + + +When `buildStats` is enabled, Hugo writes a `hugo_stats.json` file on each build with HTML classes etc. that's used in the rendered output. Changes to this file will trigger a rebuild of the `styles.css` file. You also need to add `hugo_stats.json` to Hugo's server watcher. See [Hugo Starter Tailwind Basic](https://github.com/bep/hugo-starter-tailwind-basic) for a running example. + +source +: (`string`) A [regular expression](g) matching file(s) relative to one of the virtual component directories in Hugo, typically `assets/...`. + +target +: (`string`) A [regular expression](g) matching the keys in the resource cache that should be expired when `source` changes. You can use the matching regexp groups from `source` in the expression, e.g. `$1`. + +## Build stats + +{{< code-toggle config=build.buildStats />}} + +enable +: (`bool`) Whether to create a `hugo_stats.json` file in the root of your project. This file contains arrays of the `class` attributes, `id` attributes, and tags of every HTML element within your published site. Use this file as data source when [removing unused CSS] from your site. This process is also known as pruning, purging, or tree shaking. Default is `false`. + +[removing unused CSS]: /functions/resources/postprocess/ + +disableIDs +: (`bool`) Whether to exclude `id` attributes. Default is `false`. + +disableTags +: (`bool`) Whether to exclude element tags. Default is `false`. + +disableClasses +: (`bool`) Whether to exclude `class` attributes. Default is `false`. + +> [!note] +> Given that CSS purging is typically limited to production builds, place the `buildStats` object below [`config/production`]. +> +> Built for speed, there may be "false positive" detections (e.g., HTML elements that are not HTML elements) while parsing the published site. These "false positives" are infrequent and inconsequential. + - Due to the nature of partial server builds, new HTML entities are added while the server is running, but old values will not be removed until you restart the server or run a regular `hugo` build. ++Due to the nature of partial server builds, new HTML entities are added while the server is running, but old values will not be removed until you restart the server or run `hugo build`. + +[`config/production`]: /configuration/introduction/#configuration-directory diff --cc docs/content/en/configuration/caches.md index 15783a7af,000000000..fb8ec3ad1 mode 100644,000000..100644 --- a/docs/content/en/configuration/caches.md +++ b/docs/content/en/configuration/caches.md @@@ -1,58 -1,0 +1,58 @@@ +--- +title: Configure file caches +linkTitle: Caches +description: Configure file caches. +categories: [] +keywords: [] +--- + +This is the default configuration: + +{{< code-toggle config=caches />}} + +## Purpose + +Hugo uses file caches to store data on disk, avoiding repeated operations within the same build and persisting data from one build to the next. + +assets +: Caches processed CSS and Sass resources. + +getresource +: Caches files fetched from remote URLs via the [`resources.GetRemote`][] function. + +images +: Caches processed images. + +misc +: Caches miscellaneous data. + +modulequeries +: Caches the results of module resolution queries. + +modules +: Caches downloaded modules. + +## Keys + +dir +: (`string`) The absolute file system path where Hugo stores the cached files. You can begin the path with the `:cacheDir` or `:resourceDir` [tokens](#tokens) to anchor the cache to specific system or project locations. + +maxAge +: (`string`) The duration a cached entry remains valid before being evicted, expressed as a [duration](g). A value of `0` disables the cache for that key, and a value of `-1` means the cache entry never expires. Default is `-1`. + +## Tokens + +`:cacheDir` +: (`string`) The designated cache directory. See [details](/configuration/all/#cachedir). + +`:project` - : (`string`) The base directory name of the current Hugo project. This ensures isolated file caches for each project, preventing the `hugo --gc` command from affecting other projects on the same machine. ++: (`string`) The base directory name of the current Hugo project. This ensures isolated file caches for each project, preventing the `hugo build --gc` command from affecting other projects on the same machine. + +`:resourceDir` +: (`string`) The designated directory for caching output from [asset pipelines](g). See [details](/configuration/all/#resourcedir). + +## Garbage collection + - As you modify your site or change your configuration, cached files from previous builds may remain on disk, consuming unnecessary space. Use the `hugo --gc` command to remove these expired or unused entries from the file cache. ++As you modify your site or change your configuration, cached files from previous builds may remain on disk, consuming unnecessary space. Use the `hugo build --gc` command to remove these expired or unused entries from the file cache. + +[`resources.GetRemote`]: /functions/resources/getremote/ diff --cc docs/content/en/configuration/cascade.md index 7b6ccd933,000000000..5616314a8 mode 100644,000000..100644 --- a/docs/content/en/configuration/cascade.md +++ b/docs/content/en/configuration/cascade.md @@@ -1,76 -1,0 +1,74 @@@ +--- +title: Configure cascade +linkTitle: Cascade +description: Configure cascade. +categories: [] +keywords: [] +--- + +You can configure your site to cascade front matter values to the home page and any of its descendants. However, this cascading will be prevented if the descendant already defines the field, or if a closer ancestor [node](g) has already cascaded a value for the same field through its front matter's `cascade` key. + +> [!note] +> You can also configure cascading behavior within a page's front matter. See [details]. + +For example, to cascade a "color" parameter to the home page and all its descendants: + +{{< code-toggle file=hugo >}} +[cascade.params] +color = 'red' +{{< /code-toggle >}} + +## Target + + + +The `target`[^1] keyword allows you to target specific pages or [environments](g). For example, to cascade a "color" parameter to pages within the "articles" section, including the "articles" section page itself: + +[^1]: The `_target` alias for `target` is deprecated and will be removed in a future release. + +{{< code-toggle file=hugo >}} +[cascade.params] +color = 'red' +[cascade.target] +path = '{/articles,/articles/**}' +{{< /code-toggle >}} + +Use any combination of these keywords to target pages and/or environments: + +environment +: (`string`) A [glob pattern](g) matching the build [environment](g). For example: `{staging,production}`. + +kind +: (`string`) A [glob pattern](g) matching the [page kind](g). For example: `{taxonomy,term}`. + +lang +: (`string`) A [glob pattern](g) matching the [page language]. For example: `{en,de}`. + +path +: (`string`) A [glob pattern](g) matching the page's [logical path](g). For example: `{/books,/books/**}`. + +## Array + +Define an array of cascade parameters to apply different values to different targets. For example: + +{{< code-toggle file=hugo >}} +[[cascade]] +[cascade.params] +color = 'red' +[cascade.target] +path = '/books/**' +kind = 'page' +lang = '{en,de}' +[[cascade]] +[cascade.params] +color = 'blue' +[cascade.target] +path = '/films/**' +kind = 'page' +environment = 'production' +{{< /code-toggle >}} + +[details]: /content-management/front-matter/#cascade-1 +[page language]: /methods/page/language/ diff --cc docs/content/en/configuration/front-matter.md index edffd302d,000000000..e348f8578 mode 100644,000000..100644 --- a/docs/content/en/configuration/front-matter.md +++ b/docs/content/en/configuration/front-matter.md @@@ -1,103 -1,0 +1,103 @@@ +--- +title: Configure front matter +linkTitle: Front matter +description: Configure front matter. +categories: [] +keywords: [] +--- + +## Dates + +There are four methods on a `Page` object that return a date. + +Method|Description +:--|:-- +[`Date`]|Returns the date of the given page. +[`ExpiryDate`]|Returns the expiry date of the given page. +[`Lastmod`]|Returns the last modification date of the given page. +[`PublishDate`]|Returns the publish date of the given page. + +[`Date`]: /methods/page/date +[`ExpiryDate`]: /methods/page/expirydate +[`Lastmod`]: /methods/page/lastmod +[`PublishDate`]: /methods/page/publishdate + +Hugo determines the values to return based on this configuration: + +{{< code-toggle config=frontmatter />}} + +The `ExpiryDate` method, for example, returns the `expirydate` value if it exists, otherwise it returns `unpublishdate`. + +You can also use custom date parameters: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = ["myDate", "date"] +{{< /code-toggle >}} + +In the example above, the `Date` method returns the `myDate` value if it exists, otherwise it returns `date`. + +To fall back to the default sequence of dates, use the `:default` token: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = ["myDate", ":default"] +{{< /code-toggle >}} + +In the example above, the `Date` method returns the `myDate` value if it exists, otherwise it returns the first valid date from `date`, `publishdate`, `pubdate`, `published`, `lastmod`, and `modified`. + +## Aliases + +Some of the front matter fields have aliases. + +Front matter field|Aliases +:--|:-- +`expiryDate`|`unpublishdate` +`lastmod`|`modified` +`publishDate`|`pubdate`, `published` + +The default front matter configuration includes these aliases. + +## Tokens + +Hugo provides the following [tokens](g) to help you configure your front matter: + +`:default` +: The default ordered sequence of date fields. + +`:fileModTime` +: The file's last modification timestamp. + +`:filename` +: Extracts the date from the file name, provided the file name begins with a date in one of the following formats: + + - `YYYY-MM-DD` + - `YYYY-MM-DD-HH-MM-SS` {{< new-in 0.148.0 />}} + + Within the `YYYY-MM-DD-HH-MM-SS` format, the date and time values may be separated by any character including a space (e.g., `2025-02-01T14-30-00`). + - Hugo resolves the extracted date to the [`timeZone`] defined in your site configuration, falling back to the system time zone. After extracting the date, Hugo uses the remaining part of the file name to generate the page's [`slug`], but only if you haven't already specified a slug in the page's front matter. ++ Hugo resolves the extracted date to the [`timeZone`] defined in your project configuration, falling back to the system time zone. After extracting the date, Hugo uses the remaining part of the file name to generate the page's [`slug`], but only if you haven't already specified a slug in the page's front matter. + + For example, if you name your file `2025-02-01-article.md`, Hugo will set the date to `2025-02-01` and the slug to `article`. + +`:git` - : The Git author date for the file's last revision. To enable access to the Git author date, set [`enableGitInfo`] to `true`, or use the `--enableGitInfo` flag when building your site. ++: The Git author date for the file's last revision. To enable access to the Git author date, set [`enableGitInfo`] to `true`, or use the `--enableGitInfo` flag when building your project. + +## Example + - Consider this site configuration: ++Consider this project configuration: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = [':filename', ':default'] +publishDate = [':filename', ':default'] +lastmod = ['lastmod', ':fileModTime'] +{{< /code-toggle >}} + +To determine `date` and `publishDate`, Hugo tries to extract the value from the file name, falling back to the default ordered sequence of date fields. + +To determine `lastmod`, Hugo looks for a `lastmod` field in front matter, falling back to the file's last modification timestamp. + +[`enableGitInfo`]: /configuration/all/#enablegitinfo +[`slug`]: /content-management/front-matter/#slug +[`timeZone`]: /configuration/all/#timezone diff --cc docs/content/en/configuration/introduction.md index c1f94ae8d,000000000..f4a60884c mode 100644,000000..100644 --- a/docs/content/en/configuration/introduction.md +++ b/docs/content/en/configuration/introduction.md @@@ -1,288 -1,0 +1,288 @@@ +--- +title: Introduction +description: Configure your site using files, directories, and environment variables. +categories: [] +keywords: [] +weight: 10 +--- + +## Sensible defaults + +Hugo offers many configuration options, but its defaults are often sufficient. A new site requires only these settings: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/' +languageCode = 'en-us' +title = 'My New Hugo Site' +{{< /code-toggle >}} + +Only define settings that deviate from the defaults. A smaller configuration file is easier to read, understand, and debug. Keep your configuration concise. + +> [!note] +> The best configuration file is a short configuration file. + +## Configuration file + - Create a site configuration file in the root of your project directory, naming it `hugo.toml`, `hugo.yaml`, or `hugo.json`, with that order of precedence. ++Create a project configuration file in the root of your project directory, naming it `hugo.toml`, `hugo.yaml`, or `hugo.json`, with that order of precedence. + +```text +my-project/ +└── hugo.toml +``` + +> [!note] - > For versions v0.109.0 and earlier, the site configuration file was named `config`. While you can still use this name, it's recommended to switch to the newer naming convention, `hugo`. ++> For versions v0.109.0 and earlier, the project configuration file was named `config`. While you can still use this name, it's recommended to switch to the newer naming convention, `hugo`. + +A simple example: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/' +languageCode = 'en-us' +title = 'ABC Widgets, Inc.' +[params] +subtitle = 'The Best Widgets on Earth' +[params.contact] +email = 'info@example.org' +phone = '+1 202-555-1212' +{{< /code-toggle >}} + - To use a different configuration file when building your site, use the `--config` flag: ++To use a different configuration file when building your project, use the `--config` flag: + +```sh - hugo --config other.toml ++hugo build --config other.toml +``` + +Combine two or more configuration files, with left-to-right precedence: + +```sh - hugo --config a.toml,b.yaml,c.json ++hugo build --config a.toml,b.yaml,c.json +``` + +> [!note] +> See the specifications for each file format: [TOML], [YAML], and [JSON]. + +## Configuration directory + - Instead of a single site configuration file, split your configuration by [environment](g), root configuration key, and language. For example: ++Instead of a single project configuration file, split your configuration by [environment](g), root configuration key, and language. For example: + +```text +my-project/ +└── config/ + ├── _default/ + │ ├── hugo.toml + │ ├── menus.en.toml + │ ├── menus.de.toml + │ └── params.toml + └── production/ + └── params.toml +``` + +The root configuration keys are {{< root-configuration-keys >}}. + +> [!note] +> You must define `cascade` tables in the root configuration file. You cannot define `cascade` tables in a dedicated file. See issue [#12899] for details. + +[#12899]: https://github.com/gohugoio/hugo/issues/12899 + +### Omit the root key + +When splitting the configuration by root key, omit the root key in the component file. For example, these are equivalent: + +{{< code-toggle file=config/_default/hugo >}} +[params] +foo = 'bar' +{{< /code-toggle >}} + +{{< code-toggle file=config/_default/params >}} +foo = 'bar' +{{< /code-toggle >}} + +### Recursive parsing + +Hugo parses the `config` directory recursively, allowing you to organize the files into subdirectories. For example: + +```text +my-project/ +└── config/ + └── _default/ + ├── navigation/ + │ ├── menus.de.toml + │ └── menus.en.toml + └── hugo.toml +``` + +### Example + +```text +my-project/ +└── config/ + ├── _default/ + │ ├── hugo.toml + │ ├── menus.en.toml + │ ├── menus.de.toml + │ └── params.toml + ├── production/ + │ ├── hugo.toml + │ └── params.toml + └── staging/ + ├── hugo.toml + └── params.toml +``` + - Considering the structure above, when running `hugo --environment staging`, Hugo will use every setting from `config/_default` and merge `staging`'s on top of those. ++Considering the structure above, when running `hugo build --environment staging`, Hugo will use every setting from `config/_default` and merge `staging`'s on top of those. + - Let's take an example to understand this better. Let's say you are using Google Analytics for your website. This requires you to specify a [Google tag ID] in your site configuration: ++Let's take an example to understand this better. Let's say you are using Google Analytics for your website. This requires you to specify a [Google tag ID] in your project configuration: + +{{< code-toggle file=hugo >}} +[services.googleAnalytics] +ID = 'G-XXXXXXXXX' +{{< /code-toggle >}} + +Now consider the following scenario: + +1. You don't want to load the analytics code when running `hugo server`. +1. You want to use different Google tag IDs for your production and staging environments. For example: + - `G-PPPPPPPPP` for production + - `G-SSSSSSSSS` for staging + +To satisfy these requirements, configure your site as follows: + +1. `config/_default/hugo.toml` + - Exclude the `services.googleAnalytics` section. This will prevent loading of the analytics code when you run `hugo server`. + - By default, Hugo sets its `environment` to `development` when running `hugo server`. In the absence of a `config/development` directory, Hugo uses the `config/_default` directory. +1. `config/production/hugo.toml` + - Include this section only: + + {{< code-toggle file=hugo >}} + [services.googleAnalytics] + ID = 'G-PPPPPPPPP' + {{< /code-toggle >}} + + - You do not need to include other parameters in this file. Include only those parameters that are specific to your production environment. Hugo will merge these parameters with the default configuration. - - By default, Hugo sets its `environment` to `production` when running `hugo`. The analytics code will use the `G-PPPPPPPPP` tag ID. ++ - By default, Hugo sets its `environment` to `production` when running `hugo build`. The analytics code will use the `G-PPPPPPPPP` tag ID. + +1. `config/staging/hugo.toml` + + - Include this section only: + + {{< code-toggle file=hugo >}} + [services.googleAnalytics] + ID = 'G-SSSSSSSSS' + {{< /code-toggle >}} + + - You do not need to include other parameters in this file. Include only those parameters that are specific to your staging environment. Hugo will merge these parameters with the default configuration. - - To build your staging site, run `hugo --environment staging`. The analytics code will use the `G-SSSSSSSSS` tag ID. ++ - To build your staging site, run `hugo build --environment staging`. The analytics code will use the `G-SSSSSSSSS` tag ID. + +## Merge configuration settings + +Hugo merges configuration settings from themes and modules, prioritizing the project's own settings. Given this simplified project structure with two themes: + +```text +project/ +├── themes/ +│ ├── theme-a/ +│ │ └── hugo.toml +│ └── theme-b/ +│ └── hugo.toml +└── hugo.toml +``` + +and this project-level configuration: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/' +languageCode = 'en-us' +title = 'My New Hugo Site' +theme = ['theme-a','theme-b'] +{{< /code-toggle >}} + +Hugo merges settings in this order: + +1. Project configuration (`hugo.toml` in the project root) +1. `theme-a` configuration +1. `theme-b` configuration + +The `_merge` setting within each top-level configuration key controls _which_ settings are merged and _how_ they are merged. + +The value for `_merge` can be one of: + +none +: No merge. + +shallow +: Only add values for new keys. + +deep +: Add values for new keys, merge existing. + +Note that you don't need to be so verbose as in the default setup below; a `_merge` value higher up will be inherited if not set. + +{{< code-toggle file=hugo dataKey="config_helpers.mergeStrategy" skipHeader=true />}} + +## Environment variables + +You can also configure settings using operating system environment variables: + +```sh +export HUGO_BASEURL=https://example.org/ +export HUGO_ENABLEGITINFO=true +export HUGO_ENVIRONMENT=staging +hugo +``` + +The above sets the [`baseURL`], [`enableGitInfo`], and [`environment`] configuration options and then builds your site. + +> [!note] +> An environment variable takes precedence over the values set in the configuration file. This means that if you set a configuration value with both an environment variable and in the configuration file, the value in the environment variable will be used. + +Environment variables simplify configuration for [CI/CD](g) platforms by allowing you to set values directly within their respective configuration and workflow files. + +> [!note] +> Environment variable names must be prefixed with `HUGO_`. +> +> To set custom site parameters, prefix the name with `HUGO_PARAMS_`. + +For snake_case variable names, the standard `HUGO_` prefix won't work. Hugo infers the delimiter from the first character following `HUGO`. This allows for variations like `HUGOxPARAMSxAPI_KEY=abcdefgh` using any [permitted delimiter]. + +In addition to configuring standard settings, environment variables may be used to override default values for certain internal settings: + +DART_SASS_BINARY +: (`string`) The absolute path to the Dart Sass executable. By default, Hugo searches for the executable in each of the paths in the `PATH` environment variable. + +HUGO_FILE_LOG_FORMAT +: (`string`) A format string for the file path, line number, and column number displayed when reporting errors, or when calling the `Position` method from a shortcode or Markdown render hook. Valid tokens are `:file`, `:line`, and `:col`. Default is `:file::line::col`. + +HUGO_MEMORYLIMIT - : (`int`) The maximum amount of system memory, in gigabytes, that Hugo can use while rendering your site. Default is 25% of total system memory. Note that `HUGO_MEMORYLIMIT` is a "best effort" setting. Don't expect Hugo to build a million pages with only 1 GB of memory. You can get more information about how this behaves during the build by building with `hugo --logLevel info` and look for the `dynacache` label. ++: (`int`) The maximum amount of system memory, in gigabytes, that Hugo can use while rendering your site. Default is 25% of total system memory. Note that `HUGO_MEMORYLIMIT` is a "best effort" setting. Don't expect Hugo to build a million pages with only 1 GB of memory. You can get more information about how this behaves during the build by running `hugo build --logLevel info` and look for the `dynacache` label. + +HUGO_NUMWORKERMULTIPLIER +: (`int`) The number of workers used in parallel processing. Default is the number of logical CPUs. + +## Current configuration + - Display the complete site configuration with: ++Display the complete project configuration with: + +```sh +hugo config +``` + +Display a specific configuration setting with: + +```sh +hugo config | grep [key] +``` + +Display the configured file mounts with: + +```sh +hugo config mounts +``` + +[`baseURL`]: /configuration/all#baseurl +[`enableGitInfo`]: /configuration/all#enablegitinfo +[`environment`]: /configuration/all#environment +[Google tag ID]: https://support.google.com/tagmanager/answer/12326985?hl=en +[JSON]: https://datatracker.ietf.org/doc/html/rfc7159 +[permitted delimiter]: https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html +[TOML]: https://toml.io/en/latest +[YAML]: https://yaml.org/spec/ diff --cc docs/content/en/configuration/languages.md index f9f81e1ea,000000000..0ad9d44c6 mode 100644,000000..100644 --- a/docs/content/en/configuration/languages.md +++ b/docs/content/en/configuration/languages.md @@@ -1,203 -1,0 +1,207 @@@ +--- +title: Configure languages +linkTitle: Languages +description: Configure the languages in your multilingual site. +categories: [] +keywords: [] +--- + +## Base settings + +Configure the following base settings within the site's root configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = false +disableDefaultLanguageRedirect = false +disableLanguages = [] +{{< /code-toggle >}} + +defaultContentLanguage +: (`string`) The projects's default content language, conforming to the syntax described in [RFC 5646][]. This value must match one of the defined [language keys][]. Default is `en`. + +defaultContentLanguageInSubdir +: (`bool`) Whether to publish the default content language to a subdirectory matching the [`defaultContentLanguage`][]. Default is `false`. + +disableDefaultLanguageRedirect +: {{< new-in 0.140.0 />}} +: (`bool`) Whether to disable generation of the alias redirect for the default content language. When [`defaultContentLanguageInSubdir`][] is `true`, this setting prevents the root directory from redirecting to the language subdirectory. Conversely, when `defaultContentLanguageInSubdir` is `false`, this setting prevents the language subdirectory from redirecting to the root directory. This is superseded by the more general [`disableDefaultSiteRedirect`][] setting. Default is `false`. + +disableLanguages +: (`[]string]`) A slice of language keys representing the languages to disable during the build process. Although this is functional, consider using the [`disabled`](#disabled) key under each language instead. + +## Language settings + +Configure each language under the `languages` key: + +{{< code-toggle config=languages />}} + +In the above, `en` is the [language key](#language-keys). + +disabled +: (`bool`) Whether to disable this language when building the site. Default is `false`. + +languageCode +: (`string`) The language tag as described in [RFC 5646][]. This is the primary value used by the [`language.Translate`][] function to select a translation table, falling back to the language key if a matching translation table does not exist. + + Hugo also uses this value to populate: + + - The `lang` attribute of the `html` element in the [embedded alias template][] + - The `language` element in the [embedded RSS template][] + - The `locale` property in the [embedded OpenGraph template][] + + > [!note] + > This value does not affect localization of dates, numbers, and currencies, nor does it affect the site's URL structure. These are controlled by the [language key](#language-keys). + + Access this value from a template using the [`Language.LanguageCode`][] method on a `Site` or `Page` object. + +languageDirection - : (`string`) The language direction, either left-to-right (`ltr`) or right-to-left (`rtl`). Use this value in your templates with the global [`dir`][] HTML attribute. Access this value from a template using the [`Language.LanguageDirection`][] method on a `Site` or `Page` object. ++: (`string`) The language direction, either left-to-right (`ltr`) or right-to-left (`rtl`). Use this value in your templates with the global [`dir`][] HTML attribute. Access this value from a template using the [`Language.LanguageDirection`][] method on a `Site` or `Page` object. Default is `ltr`. + +languageName +: (`string`) The language name, typically used when rendering a language switcher. Access this value from a template using the [`Language.LanguageName`][] method on a `Site` or `Page` object. + +title +: (`string`) The site title for this language. Access this value from a template using the [`Title`][] method on a `Site` object. + +weight +: (`int`) The language [weight](g). When set to a non-zero value, this is the primary sort criteria for this language. Access this value from a template using the [`Language.Weight`][] method on a `Site` or `Page` object. + ++## Sort order ++ ++Hugo sorts languages by weight in ascending order, then lexicographically in ascending order. This affects build order and complement selection. ++ +## Localized settings + +Some configuration settings can be defined separately for each language. For example: + +{{< code-toggle file=hugo >}} +[languages.en] +languageCode = 'en-US' +languageName = 'English' +weight = 1 +title = 'Project Documentation' +timeZone = 'America/New_York' +[languages.en.pagination] +path = 'page' +[languages.en.params] +subtitle = 'Reference, Tutorials, and Explanations' +{{< /code-toggle >}} + +The following configuration keys can be defined separately for each language: + +{{< per-lang-config-keys >}} + - Any key not defined in a `languages` object will fall back to the global value in the root of the site configuration. ++Any key not defined in a `languages` object will fall back to the global value in the root of your project configuration. + +## Language keys + +Language keys must conform to the syntax described in [RFC 5646][]. For example: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +[languages.de] + weight = 1 +[languages.en-US] + weight = 2 +[languages.pt-BR] + weight = 3 +{{< /code-toggle >}} + +Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7][] are also supported. Omit the `art-x-` prefix from the language key. For example: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' +[languages.en] +weight = 1 +[languages.hugolang] +weight = 2 +{{< /code-toggle >}} + +> [!note] +> Private use subtags must not exceed 8 alphanumeric characters. + +## Example + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true +disableDefaultLanguageRedirect = false + +[languages.de] +contentDir = 'content/de' +disabled = false +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +title = 'Projekt Dokumentation' +weight = 1 + +[languages.de.params] +subtitle = 'Referenz, Tutorials und Erklärungen' + +[languages.en] +contentDir = 'content/en' +disabled = false +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +title = 'Project Documentation' +weight = 2 + +[languages.en.params] +subtitle = 'Reference, Tutorials, and Explanations' +{{< /code-toggle >}} + +> [!note] +> In the example above, omit `contentDir` if [translating by file name][]. + +## Multihost + +Hugo supports multiple languages in a multihost configuration. This means you can configure a `baseURL` per `language`. + +> [!note] +> If you define a `baseURL` for one language, you must define a unique `baseURL` for all languages. + +For example: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'fr' +[languages] + [languages.en] + baseURL = 'https://en.example.org/' + languageName = 'English' + title = 'In English' + weight = 2 + [languages.fr] + baseURL = 'https://fr.example.org' + languageName = 'Français' + title = 'En Français' + weight = 1 +{{}} + +With the above, Hugo publishes two sites, each with their own root: + +```text +public +├── en +└── fr +``` + +[`defaultContentLanguage`]: #defaultcontentlanguage +[`defaultContentLanguageInSubdir`]: #defaultcontentlanguageinsubdir +[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir +[`disableDefaultSiteRedirect`]: /configuration/all/#disabledefaultsiteredirect +[`Language.LanguageCode`]: /methods/site/language/#languagecode +[`Language.LanguageDirection`]: /methods/site/language/#languagedirection +[`Language.LanguageName`]: /methods/site/language/#languagename +[`language.Translate`]: /functions/lang/translate/ +[`Language.Weight`]: /methods/site/language/#weight +[`Title`]: /methods/site/title/ +[embedded alias template]: <{{% eturl alias %}}> +[embedded OpenGraph template]: <{{% eturl opengraph %}}> +[embedded RSS template]: <{{% eturl rss %}}> +[language keys]: #language-keys +[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7 +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 +[translating by file name]: /content-management/multilingual/#translation-by-file-name diff --cc docs/content/en/configuration/markup.md index 31c8de505,000000000..0829f9db5 mode 100644,000000..100644 --- a/docs/content/en/configuration/markup.md +++ b/docs/content/en/configuration/markup.md @@@ -1,367 -1,0 +1,365 @@@ +--- +title: Configure markup +linkTitle: Markup +description: Configure markup. +categories: [] +keywords: [] +aliases: [/getting-started/configuration-markup/] +--- + +## Default handler + +In its default configuration, Hugo uses [Goldmark] to render Markdown to HTML. + +{{< code-toggle file=hugo >}} +[markup] +defaultMarkdownHandler = 'goldmark' +{{< /code-toggle >}} + +Files with ending with `.md`, `.mdown`, or `.markdown` are processed as Markdown, unless you've explicitly set a different format using the `markup` field in your front matter. + - To use a different renderer for Markdown files, specify one of `asciidocext`, `org`, `pandoc`, or `rst` in your site configuration. ++To use a different renderer for Markdown files, specify one of `asciidocext`, `org`, `pandoc`, or `rst` in your project configuration. + +`defaultMarkdownHandler`|Renderer +:--|:-- +`asciidocext`|[AsciiDoc] +`goldmark`|[Goldmark] +`org`|[Emacs Org Mode] +`pandoc`|[Pandoc] +`rst`|[reStructuredText] + +To use AsciiDoc, Pandoc, or reStructuredText you must install the relevant renderer and update your [security policy]. + +> [!note] +> Unless you need a unique capability provided by one of the alternative Markdown handlers, we strongly recommend that you use the default setting. Goldmark is fast, well maintained, conforms to the [CommonMark] specification, and is compatible with [GitHub Flavored Markdown] (GFM). + +## Goldmark + +This is the default configuration for the Goldmark Markdown renderer: + +{{< code-toggle config=markup.goldmark />}} + +### Extensions + +The extensions below, excluding Extras and Passthrough, are enabled by default. + +Extension|Documentation|Enabled +:--|:--|:-: +`cjk`|[Goldmark Extensions: CJK]|:heavy_check_mark: +`definitionList`|[PHP Markdown Extra: Definition lists]|:heavy_check_mark: +`extras`|[Hugo Goldmark Extensions: Extras]|  +`footnote`|[PHP Markdown Extra: Footnotes]|:heavy_check_mark: +`linkify`|[GitHub Flavored Markdown: Autolinks]|:heavy_check_mark: +`passthrough`|[Hugo Goldmark Extensions: Passthrough]|  +`strikethrough`|[GitHub Flavored Markdown: Strikethrough]|:heavy_check_mark: +`table`|[GitHub Flavored Markdown: Tables]|:heavy_check_mark: +`taskList`|[GitHub Flavored Markdown: Task list items]|:heavy_check_mark: +`typographer`|[Goldmark Extensions: Typographer]|:heavy_check_mark: + +#### Extras + - {{< new-in 0.126.0 />}} - +Enable [deleted text], [inserted text], [mark text], [subscript], and [superscript] elements in Markdown. + +Element|Markdown|Rendered +:--|:--|:-- +Deleted text|`~~foo~~`|`foo` +Inserted text|`++bar++`|`bar` +Mark text|`==baz==`|`baz` +Subscript|`H~2~O`|`H2O` +Superscript|`1^st^`|`1st` + +To avoid a conflict[^1], if you enable the "subscript" feature of the Extras extension, you must disable the Strikethrough extension: + +[^1]: See [details](https://github.com/gohugoio/hugo-goldmark-extensions/commit/4d4fcd022fe45a9b51483df001c9e5f4e632d5a9). + +{{< code-toggle file=hugo >}} +[markup.goldmark.extensions] +strikethrough = false + +[markup.goldmark.extensions.extras.subscript] +enable = true +{{< /code-toggle >}} + +If you still need to show deleted text after disabling the Strikethrough extension, enable the "deleted text" feature of the Extras extension: + +{{< code-toggle file=hugo >}} +[markup.goldmark.extensions] +strikethrough = false + +[markup.goldmark.extensions.extras.delete] +enable = true +{{< /code-toggle >}} + +With this configuration, to format text as deleted, wrap it with double-tildes. + +#### Footnote + +Enabled by default, the Footnote extension enables inclusion of footnotes in Markdown. + +enable +: {{< new-in 0.151.0 />}} +: (`bool`) Whether to enable the Footnotes extension. Default is `true`. + +backlinkHTML +: {{< new-in 0.151.0 />}} +: (`string`) The HTML to be displayed at the end of a footnote that links the user back to the corresponding reference in the main text. The default is ↩︎ (a return arrow symbol). + +enableAutoIDPrefix +: {{< new-in 0.151.0 />}} +: (`bool`) Whether to prepend a unique prefix to footnote IDs, preventing clashes when multiple documents are rendered together. This prefix is unique to each logical path, which means that the prefix is not unique across content dimensions such as language. Default is `false`. + +#### Passthrough + +Enable the Passthrough extension to include mathematical equations and expressions in Markdown using LaTeX markup. See [mathematics in Markdown] for details. + +#### Typographer + +The Typographer extension replaces certain character combinations with HTML entities as specified below: + +Markdown|Replaced by|Description +:--|:--|:-- +`...`|`…`|horizontal ellipsis +`'`|`’`|apostrophe +`--`|`–`|en dash +`---`|`—`|em dash +`«`|`«`|left angle quote +`“`|`“`|left double quote +`‘`|`‘`|left single quote +`»`|`»`|right angle quote +`”`|`”`|right double quote +`’`|`’`|right single quote + +### Goldmark settings explained + +Most of the Goldmark settings above are self-explanatory, but some require explanation. + +duplicateResourceFiles +: (`bool`) Whether to duplicate shared page resources for each language on multilingual single-host sites. See [multilingual page resources] for details. Default is `false`. + + > [!note] + > With multilingual single-host sites, setting this parameter to `false` will enable Hugo's [embedded link render hook] and [embedded image render hook]. This is the default configuration for multilingual single-host sites. + +parser.wrapStandAloneImageWithinParagraph +: (`bool`) Whether to wrap image elements without adjacent content within a `p` element when rendered. This is the default Markdown behavior. Set to `false` when using an [image render hook] to render standalone images as `figure` elements. Default is `true`. + +parser.autoDefinitionTermID +: {{< new-in 0.144.0 />}} +: (`bool`) Whether to automatically add `id` attributes to description list terms (i.e., `dt` elements). When `true`, the `id` attribute of each `dt` element is accessible through the [`Fragments.Identifiers`] method on a `Page` object. + +parser.autoHeadingID +: (`bool`) Whether to automatically add `id` attributes to headings (i.e., `h1`, `h2`, `h3`, `h4`, `h5`, and `h6` elements). + +parser.autoIDType +: (`string`) The strategy used to automatically generate `id` attributes, one of `github`, `github-ascii` or `blackfriday`. Default is `github`. + + - `github`: Generate GitHub-compatible `id` attributes + - `github-ascii`: Drop any non-ASCII characters after accent normalization + - `blackfriday`: Generate `id` attributes compatible with the Blackfriday Markdown renderer + + This is also the strategy used by the [anchorize] template function. + +parser.attribute.block +: (`bool`) Whether to enable [Markdown attributes] for block elements. Default is `false`. + +parser.attribute.title +: (`bool`) Whether to enable [Markdown attributes] for headings. Default is `true`. + + +renderHooks.image.enableDefault +: Deprecated in v0.148.0. Use `renderHooks.image.useEmbedded` instead. + +renderHooks.image.useEmbedded +: {{< new-in 0.148.0 />}} +: (`string`) When to use the [embedded image render hook]. One of `auto`, `never`, `always`, or `fallback`. Default is `auto`. + + - `auto`: Use the embedded image render hook only for multilingual single-host projects where the [duplication of shared page resources] feature is disabled. If custom image render hooks are defined by your project, modules, or themes, these will be used instead. + - `never`: Never use the embedded image render hook. If custom image render hooks are defined by your project, modules, or themes, these will be used instead. + - `always`: Always use the embedded image render hook, even if custom image render hooks are provided by your project, modules, or themes. + - `fallback`: Use the embedded image render hook only if custom image render hooks are not provided by your project, modules, or themes. If custom image render hooks exist, these will be used instead. + + +renderHooks.link.enableDefault +: Deprecated in v0.148.0. Use `renderHooks.link.useEmbedded` instead. + +renderHooks.link.useEmbedded +: (`string`) When to use the [embedded link render hook]. One of `auto`, `never`, `always`, or `fallback`. Default is `auto`. + + - `auto`: Use the embedded link render hook only for multilingual single-host projects where the [duplication of shared page resources] feature is disabled. If custom link render hooks are defined by your project, modules, or themes, these will be used instead. + - `never`: Never use the embedded link render hook. If custom link render hooks are defined by your project, modules, or themes, these will be used instead. + - `always`: Always use the embedded link render hook, even if custom link render hooks are provided by your project, modules, or themes. + - `fallback`: Use the embedded link render hook only if custom link render hooks are not provided by your project, modules, or themes. If custom link render hooks exist, these will be used instead. + +renderer.hardWraps +: (`bool`) Whether to replace newline characters within a paragraph with `br` elements. Default is `false`. + +renderer.unsafe +: (`bool`) Whether to render raw HTML mixed within Markdown. This is unsafe unless the content is under your control. Default is `false`. + +## AsciiDoc + +This is the default configuration for the AsciiDoc renderer: + +{{< code-toggle config=markup.asciidocExt />}} + +### AsciiDoc settings explained + +attributes +: (`map`) A map of key-value pairs, each a document attribute. See Asciidoctor's [attributes]. + +backend +: (`string`) The backend output file format. Default is `html5`. + +extensions +: (`[]string`) An array of enabled extensions, such as `asciidoctor-html5s`, `asciidoctor-bibtex`, or `asciidoctor-diagram`. + + > [!note] + > To mitigate security risks, entries in the extension array may not contain forward slashes (`/`), backslashes (`\`), or periods. Due to this restriction, extensions must be in Ruby's `$LOAD_PATH`. + +failureLevel +: (`string`) The minimum logging level that triggers a non-zero exit code (failure). Default is `fatal`. + +noHeaderOrFooter +: (`bool`) Whether to output an embeddable document, which excludes the header, the footer, and everything outside the body of the document. Default is `true`. + +preserveTOC +: (`bool`) Whether to preserve the table of contents (TOC) rendered by Asciidoctor. By default, to make the TOC compatible with existing themes, Hugo removes the TOC rendered by Asciidoctor. To render the TOC, use the [`TableOfContents`] method on a `Page` object in your templates. Default is `false`. + +safeMode +: (`string`) The safe mode level, one of `unsafe`, `safe`, `server`, or `secure`. Default is `unsafe`. + +sectionNumbers +: (`bool`) Whether to number each section title. Default is `false`. + +trace +: (`bool`) Whether to include backtrace information on errors. Default is `false`. + +verbose +: (`bool`) Whether to verbosely print processing information and configuration file checks to stderr. Default is `false`. + +workingFolderCurrent +: (`bool`) Whether to set the working directory to be the same as that of the AsciiDoc file being processed, allowing [includes] to work with relative paths. Set to `true` to render diagrams with the [asciidoctor-diagram] extension. Default is `false`. + +### Configuration example + +{{< code-toggle file=hugo >}} +[markup.asciidocExt] + extensions = ["asciidoctor-html5s", "asciidoctor-diagram"] + workingFolderCurrent = true + [markup.asciidocExt.attributes] + my-base-url = "https://example.com/" + my-attribute-name = "my value" +{{< /code-toggle >}} + +### Syntax highlighting + +Follow the steps below to enable syntax highlighting. + +Step 1 - : Set the `source-highlighter` attribute in your site configuration. For example: ++: Set the `source-highlighter` attribute in your project configuration. For example: + + {{< code-toggle file=hugo >}} + [markup.asciidocExt.attributes] + source-highlighter = 'rouge' + {{< /code-toggle >}} + +Step 2 +: Generate the highlighter CSS. For example: + + ```text + rougify style monokai.sublime > assets/css/syntax.css + ``` + +Step 3 +: In your base template add a link to the CSS file: + + ```go-html-template {file="layouts/baseof.html"} + + ... + {{ with resources.Get "css/syntax.css" }} + + {{ end }} + ... + + ``` + +Step 4 +: Add the code to be highlighted to your markup: + + ```text + [#hello,ruby] + ---- + require 'sinatra' + + get '/hi' do + "Hello World!" + end + ---- + ``` + +### Troubleshooting + - Run `hugo --logLevel debug` to examine Hugo's call to the Asciidoctor executable: ++Run `hugo build --logLevel debug` to examine Hugo's call to the Asciidoctor executable: + +```txt +INFO 2019/12/22 09:08:48 Rendering book-as-pdf.adoc with C:\Ruby26-x64\bin\asciidoctor.bat using asciidoc args [--no-header-footer -r asciidoctor-html5s -b html5s -r asciidoctor-diagram --base-dir D:\prototypes\hugo_asciidoc_ddd\docs -a outdir=D:\prototypes\hugo_asciidoc_ddd\build -] ... +``` + +## Highlight + +This is the default configuration. + +{{< code-toggle config=markup.highlight />}} + +{{% include "/_common/syntax-highlighting-options.md" %}} + +## Table of contents + +This is the default configuration for the table of contents, applicable to Goldmark and Asciidoctor: + +{{< code-toggle config=markup.tableOfContents />}} + +startLevel +: (`int`) Heading levels less than this value will be excluded from the table of contents. For example, to exclude `h1` elements from the table of contents, set this value to `2`. Default is `2`. + +endLevel +: (`int`) Heading levels greater than this value will be excluded from the table of contents. For example, to exclude `h4`, `h5`, and `h6` elements from the table of contents, set this value to `3`. Default is `3`. + +ordered +: (`bool`) Whether to generates an ordered list instead of an unordered list. Default is `false`. + +[`Fragments.Identifiers`]: /methods/page/fragments/#identifiers +[`TableOfContents`]: /methods/page/tableofcontents/ +[anchorize]: /functions/urls/anchorize +[AsciiDoc]: https://asciidoc.org/ +[asciidoctor-diagram]: https://asciidoctor.org/docs/asciidoctor-diagram/ +[attributes]: https://asciidoctor.org/docs/asciidoc-syntax-quick-reference/#attributes-and-substitutions +[CommonMark]: https://spec.commonmark.org/current/ +[deleted text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[Emacs Org Mode]: https://orgmode.org/ +[embedded image render hook]: /render-hooks/images/#embedded +[embedded link render hook]: /render-hooks/links/#embedded +[GitHub Flavored Markdown: Autolinks]: https://github.github.com/gfm/#autolinks-extension- +[GitHub Flavored Markdown: Strikethrough]: https://github.github.com/gfm/#strikethrough-extension- +[GitHub Flavored Markdown: Tables]: https://github.github.com/gfm/#tables-extension- +[GitHub Flavored Markdown: Task list items]: https://github.github.com/gfm/#task-list-items-extension- +[GitHub Flavored Markdown]: https://github.github.com/gfm/ +[Goldmark Extensions: CJK]: https://github.com/yuin/goldmark?tab=readme-ov-file#cjk-extension +[Goldmark Extensions: Typographer]: https://github.com/yuin/goldmark?tab=readme-ov-file#typographer-extension +[Goldmark]: https://github.com/yuin/goldmark/ +[Hugo Goldmark Extensions: Extras]: https://github.com/gohugoio/hugo-goldmark-extensions?tab=readme-ov-file#extras-extension +[Hugo Goldmark Extensions: Passthrough]: https://github.com/gohugoio/hugo-goldmark-extensions?tab=readme-ov-file#passthrough-extension +[image render hook]: /render-hooks/images/ +[includes]: https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/#includes +[inserted text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins +[mark text]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark +[Markdown attributes]: /content-management/markdown-attributes/ +[mathematics in Markdown]: content-management/mathematics/ +[multilingual page resources]: /content-management/page-resources/#multilingual +[Pandoc]: https://pandoc.org/ +[PHP Markdown Extra: Definition lists]: https://michelf.ca/projects/php-markdown/extra/#def-list +[PHP Markdown Extra: Footnotes]: https://michelf.ca/projects/php-markdown/extra/#footnotes +[reStructuredText]: https://docutils.sourceforge.io/rst.html +[security policy]: /configuration/security/ +[subscript]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub +[superscript]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup diff --cc docs/content/en/configuration/menus.md index 6b27e966b,000000000..6eae4f268 mode 100644,000000..100644 --- a/docs/content/en/configuration/menus.md +++ b/docs/content/en/configuration/menus.md @@@ -1,137 -1,0 +1,137 @@@ +--- +title: Configure menus +linkTitle: Menus +description: Centrally define menu entries for one or more menus. +categories: [] +keywords: [] +--- + +> [!note] +> To understand Hugo's menu system, please refer to the [menus] page. + +There are three ways to define menu entries: + +1. [Automatically] - 1. [In front matter] - 1. In site configuration ++1. In [front matter] ++1. In your project configuration + - This page covers the site configuration method. ++This page covers the project configuration method. + +## Example + +To define entries for a "main" menu: + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Home' +pageRef = '/' +weight = 10 + +[[menus.main]] +name = 'Products' +pageRef = '/products' +weight = 20 + +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 30 +{{< /code-toggle >}} + +This creates a menu structure that you can access with [`Menus`] method on a `Site` object: + +```go-html-template +{{ range .Site.Menus.main }} + ... +{{ end }} +``` + +See [menu templates] for a detailed example. + +To define entries for a "footer" menu: + +{{< code-toggle file=hugo >}} +[[menus.footer]] +name = 'Terms' +pageRef = '/terms' +weight = 10 + +[[menus.footer]] +name = 'Privacy' +pageRef = '/privacy' +weight = 20 +{{< /code-toggle >}} + +Access this menu structure in the same way: + +```go-html-template +{{ range .Site.Menus.footer }} + ... +{{ end }} +``` + +## Properties + +Menu entries usually include at least three properties: `name`, `weight`, and either `pageRef` or `url`. Use `pageRef` for internal page destinations and `url` for external destinations. + +These are the available menu entry properties: + +{{% include "/_common/menu-entry-properties.md" %}} + +pageRef +: (`string`) The [logical path](g) of the target page. For example: + + page kind|pageRef + :--|:-- + home|`/` + page|`/books/book-1` + section|`/books` + taxonomy|`/tags` + term|`/tags/foo` + +url +: (`string`) The destination URL. Use this for external destinations only. + +## Nested menu + +This nested menu demonstrates some of the available properties: + + +{{< code-toggle file=hugo >}} +[[menus.main]] +name = 'Products' +pageRef = '/products' +weight = 10 + +[[menus.main]] +name = 'Hardware' +pageRef = '/products/hardware' +parent = 'Products' +weight = 1 + +[[menus.main]] +name = 'Software' +pageRef = '/products/software' +parent = 'Products' +weight = 2 + +[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 20 + +[[menus.main]] +name = 'Hugo' +pre = '' +url = 'https://gohugo.io/' +weight = 30 +[menus.main.params] +rel = 'external' +{{< /code-toggle >}} + + +[`Menus`]: /methods/site/menus/ +[Automatically]: /content-management/menus/#define-automatically - [In front matter]: /content-management/menus/#define-in-front-matter ++[front matter]: /content-management/menus/#define-in-front-matter +[menu templates]: /templates/menu/ +[menus]: /content-management/menus/ diff --cc docs/content/en/configuration/output-formats.md index bf61b3d2e,000000000..f2a8e2da7 mode 100644,000000..100644 --- a/docs/content/en/configuration/output-formats.md +++ b/docs/content/en/configuration/output-formats.md @@@ -1,207 -1,0 +1,207 @@@ +--- +title: Configure output formats +linkTitle: Output formats +description: Configure output formats. +categories: [] +keywords: [] +--- + +{{% glossary-term "output format" %}} + +You can output a page in as many formats as you want. Define an infinite number of output formats, provided they each resolve to a unique file system path. + +This is the default output format configuration in tabular form: + +{{< datatable + "config" + "outputFormats" + "_key" + "mediaType" + "weight" + "baseName" + "isHTML" + "isPlainText" + "noUgly" + "notAlternative" + "path" + "permalinkable" + "protocol" + "rel" + "root" + "ugly" +>}} + +## Default configuration + +The following is the default configuration that matches the table above: + +{{< code-toggle config=outputFormats />}} + +baseName +: (`string`) The base name of the published file. Default is `index`. + +isHTML +: (`bool`) Whether to classify the output format as HTML. This value determines when the LiveReload script is injected and, in conjunction with [`permalinkable`](#permalinkable), whether [alias redirects][] are generated. Default is `false`. + +isPlainText +: (`bool`) Whether to parse templates for this output format with Go's [text/template][] package instead of the [html/template][] package. Default is `false`. + +mediaType +: (`string`) The [media type](g) of the published file. This must match one of the [configured media types][]. + +notAlternative +: (`bool`) Whether to exclude this output format from the values returned by the [`AlternativeOutputFormats`][] method on a `Page` object. Default is `false`. + +noUgly - : (`bool`) Whether to disable ugly URLs for this output format when [`uglyURLs`][] are enabled in your site configuration. Default is `false`. ++: (`bool`) Whether to disable ugly URLs for this output format when [`uglyURLs`][] are enabled in your project configuration. Default is `false`. + +path +: (`string`) The first segment of the publication path for this output format. This path segment is relative to the root of your [`publishDir`][]. If omitted, Hugo will use the file's original content path for publishing. + +permalinkable +: (`bool`) Whether to return the rendering output format rather than the main output format when invoking the [`Permalink`][] and [`RelPermalink`][] methods on a `Page` object. Along with [`isHTML`](#ishtml), this must be `true` to create [alias redirects][]. Enabled by default for the `html` and `amp` output formats. Default is `false`. + +protocol - : (`string`) The protocol (scheme) of the URL for this output format. For example, `https://` or `webcal://`. Default is the scheme of the [`baseURL`][] parameter in your site configuration, typically `https://`. ++: (`string`) The protocol (scheme) of the URL for this output format. For example, `https://` or `webcal://`. Default is the scheme of the [`baseURL`][] parameter in your project configuration, typically `https://`. + +rel +: (`string`) The relationship of the output format to the current page. Hugo uses this property to determine the [canonical output format](g) of the current page. For the predefined `html` output format, the default value is `canonical`; for all other predefined output formats, the default value is `alternate`. + +root +: (`bool`) Whether to publish files to the root of the publish directory. Default is `false`. + +ugly - : (`bool`) Whether to enable uglyURLs for this output format when `uglyURLs` is `false` in your site configuration. Default is `false`. ++: (`bool`) Whether to enable uglyURLs for this output format when `uglyURLs` is `false` in your project configuration. Default is `false`. + +weight +: (`int`) When set to a non-zero value, Hugo uses the `weight` as the first criteria when sorting output formats, falling back to the name of the output format. Lighter items float to the top, while heavier items sink to the bottom. Hugo renders output formats sequentially based on the sort order. Default is `0`, except for the `html` output format, which has a default weight of `10`. + +## Modify an output format + +You can modify any of the default output formats. For example, to prioritize `json` rendering over `html` rendering, when both are generated, adjust the [`weight`](#weight): + +{{< code-toggle file=hugo >}} +[outputFormats.json] +weight = 1 +[outputFormats.html] +weight = 2 +{{< /code-toggle >}} + +The example above shows that when you modify a default content format, you only need to define the properties that differ from their default values. + +## Create an output format + +You can create new output formats as needed. For example, you may wish to create an output format to support Atom feeds. + +Step 1 +: Output formats require a specified media type. Because Atom feeds use `application/atom+xml`, which is not one of the [default media types][], you must create it first. + + {{< code-toggle file=hugo >}} + [mediaTypes.'application/atom+xml'] + suffixes = ['atom'] + {{< /code-toggle >}} + + See [configure media types][] for more information. + +Step 2 +: Create a new output format: + + {{< code-toggle file=hugo >}} + [outputFormats.atom] + mediaType = 'application/atom+xml' + noUgly = true + {{< /code-toggle >}} + + Note that we use the default settings for all other output format properties. + +Step 3 +: Specify the page [kinds](g) for which to render this output format: + + {{< code-toggle file=hugo >}} + [outputs] + home = ['html', 'rss', 'atom'] + section = ['html', 'rss', 'atom'] + taxonomy = ['html', 'rss', 'atom'] + term = ['html', 'rss', 'atom'] + {{< /code-toggle >}} + + See [configure outputs][] for more information. + +Step 4 +: Create a template to render the output format. Since Atom feeds are lists, you need to create a list template. Consult the [template lookup order] to find the correct template path: + + ```text + layouts/list.atom.atom + ``` + + We leave writing the template code as an exercise for you. Aim for a result similar to the [embedded RSS template][]. + +## List output formats + - To access output formats, each `Page` object provides two methods: [`OutputFormats`][] (for all formats, including the current one) and [`AlternativeOutputFormats`][]. Use `AlternativeOutputFormats` to create a link `rel` list within your site's `head` element, as shown below: ++To access output formats, each `Page` object provides two methods: [`OutputFormats`][] (for all formats, including the current one) and [`AlternativeOutputFormats`][]. Use `AlternativeOutputFormats` to create a link `rel` list within a `head` element, as shown below: + +```go-html-template +{{ range .AlternativeOutputFormats }} + +{{ end }} +``` + +## Link to output formats + +By default, a `Page` object's [`Permalink`][] and [`RelPermalink`][] methods return the URL of the [primary output format](g), typically `html`. This behavior remains consistent regardless of the template used. + +For example, in `page.json.json`, you'll see: + +```go-html-template +{{ .RelPermalink }} → /that-page/ +{{ with .OutputFormats.Get "json" }} + {{ .RelPermalink }} → /that-page/index.json +{{ end }} +``` + +To make these methods return the URL of the _current_ template's output format, you must set the [`permalinkable`][] setting to `true` for that format. + +With `permalinkable` set to true for `json` in the same `page.json.json` template: + +```go-html-template +{{ .RelPermalink }} → /that-page/index.json +{{ with .OutputFormats.Get "html" }} + {{ .RelPermalink }} → /that-page/ +{{ end }} +``` + +## Template lookup order + +Each output format requires a template conforming to the [template lookup order][]. + +For the highest specificity in the template lookup order, include the page kind, output format, and suffix in the file name: + +```text +[page kind].[output format].[suffix] +``` + +For example, for section pages: + +Output format|Template path +:--|:-- +`html`|`layouts/section.html.html` +`json`|`layouts/section.json.json` +`rss`|`layouts/section.rss.xml` + +[`AlternativeOutputFormats`]: /methods/page/alternativeoutputformats/ +[`baseURL`]: /configuration/all/#baseurl +[`OutputFormats`]: /methods/page/outputformats/ +[`Permalink`]: /methods/page/permalink/ +[`permalinkable`]: #permalinkable +[`publishDir`]: /configuration/all/#publishdir +[`RelPermalink`]: /methods/page/relpermalink/ +[`uglyURLs`]: /configuration/ugly-urls/ +[alias redirects]: /content-management/urls/#aliases +[configure media types]: /configuration/media-types/ +[configure outputs]: /configuration/outputs/ +[configured media types]: /configuration/media-types/ +[default media types]: /configuration/media-types/ +[embedded RSS template]: <{{% eturl rss %}}> +[html/template]: https://pkg.go.dev/html/template +[template lookup order]: /templates/lookup-order/ +[text/template]: https://pkg.go.dev/text/template diff --cc docs/content/en/configuration/outputs.md index 9a83cb6e9,000000000..ba23f9ee8 mode 100644,000000..100644 --- a/docs/content/en/configuration/outputs.md +++ b/docs/content/en/configuration/outputs.md @@@ -1,49 -1,0 +1,49 @@@ +--- +title: Configure outputs +linkTitle: Outputs +description: Configure which output formats to render for each page kind. +categories: [] +keywords: [] +--- + +{{% glossary-term "output format" %}} + +Learn more about creating and configuring output formats in the [configure output formats] section. + +## Outputs per page kind + +The following default configuration determines the output formats generated for each page kind: + +{{< code-toggle config=outputs />}} + +To render the built-in `json` output format for the `home` page kind, assuming you've already created the necessary template, add the following to your configuration: + +{{< code-toggle file=hugo >}} +[outputs] +home = ['html','rss','json'] +{{< /code-toggle >}} + +Notice in this example that we only specified the `home` page kind. You don't need to include entries for other page kinds unless you intend to modify their default output formats. + +> [!note] +> The order of the output formats in the arrays above is important. The first element will be the _primary output format_ for that page kind, and in most cases that should be `html` as shown in the default configuration. +> +> The primary output format for a given page kind determines the value returned by the [`Permalink`] and [`RelPermalink`] methods on a `Page` object. +> +> See the [link to output formats] section for details. + +## Outputs per page + +Add output formats to a page's rendering using the `outputs` field in its front matter. For example, to include `json` in the output formats rendered for a specific page: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +outputs = ['json'] +{{< /code-toggle >}} + - In its default configuration, Hugo will render both the `html` and `json` output formats for this page. The `outputs` field appends to, rather than replaces, the site's configured outputs. ++In its default configuration, Hugo will render both the `html` and `json` output formats for this page. The `outputs` field appends to, rather than replaces, the project's configured outputs. + +[`Permalink`]: /methods/page/permalink/ +[`RelPermalink`]: /methods/page/relpermalink/ +[configure output formats]: /configuration/output-formats/ +[link to output formats]: configuration/output-formats/#link-to-output-formats diff --cc docs/content/en/configuration/page.md index 81169e546,000000000..9012c928b mode 100644,000000..100644 --- a/docs/content/en/configuration/page.md +++ b/docs/content/en/configuration/page.md @@@ -1,34 -1,0 +1,34 @@@ +--- +title: Configure page +linkTitle: Page +description: Configure page behavior. +categories: [] +keywords: [] +--- + +{{< new-in 0.133.0 />}} + +{{% glossary-term "default sort order" %}} + +Hugo uses the default sort order to determine the _next_ and _previous_ page relative to the current page when calling these methods on a `Page` object: + +- [`Next`](/methods/page/next/) and [`Prev`](/methods/page/prev/) +- [`NextInSection`](/methods/page/nextinsection/) and [`PrevInSection`](/methods/page/previnsection/) + - This is based on this default site configuration: ++This is based on this default project configuration: + +{{< code-toggle config=page />}} + +To reverse the meaning of _next_ and _previous_: + +{{< code-toggle file=hugo >}} +[page] + nextPrevInSectionSortOrder = 'asc' + nextPrevSortOrder = 'asc' +{{< /code-toggle >}} + +> [!note] +> These settings do not apply to the [`Next`] or [`Prev`] methods on a `Pages` object. + +[`Next`]: /methods/pages/next +[`Prev`]: /methods/pages/next diff --cc docs/content/en/configuration/permalinks.md index 0810624a6,000000000..cd1c38083 mode 100644,000000..100644 --- a/docs/content/en/configuration/permalinks.md +++ b/docs/content/en/configuration/permalinks.md @@@ -1,162 -1,0 +1,162 @@@ +--- +title: Configure permalinks +linkTitle: Permalinks +description: Configure permalinks. +categories: [] +keywords: [] +--- + +This is the default configuration: + +{{< code-toggle config=permalinks />}} + +Define a URL pattern for each top-level section. Each URL pattern can target a given language and/or page kind. + +> [!note] +> The [`url`] front matter field overrides any matching permalink pattern. + +## Monolingual example + +With this content structure: + +```text +content/ +├── posts/ +│ ├── bash-in-slow-motion.md +│ └── tls-in-a-nutshell.md +├── tutorials/ +│ ├── git-for-beginners.md +│ └── javascript-bundling-with-hugo.md +└── _index.md +``` + +Render tutorials under "training", and render the posts under "articles" with a date-base hierarchy: + +{{< code-toggle file=hugo >}} +[permalinks.page] +posts = '/articles/:year/:month/:slug/' +tutorials = '/training/:slug/' +[permalinks.section] +posts = '/articles/' +tutorials = '/training/' +{{< /code-toggle >}} + +The structure of the published site will be: + +```text +public/ +├── articles/ +│ ├── 2023/ +│ │ ├── 04/ +│ │ │ └── bash-in-slow-motion/ +│ │ │ └── index.html +│ │ └── 06/ +│ │ └── tls-in-a-nutshell/ +│ │ └── index.html +│ └── index.html +├── training/ +│ ├── git-for-beginners/ +│ │ └── index.html +│ ├── javascript-bundling-with-hugo/ +│ │ └── index.html +│ └── index.html +└── index.html +``` + +To create a date-based hierarchy for regular pages in the content root: + +{{< code-toggle file=hugo >}} +[permalinks.page] +"/" = "/:year/:month/:slug/" +{{< /code-toggle >}} + +Use the same approach with taxonomy terms. For example, to omit the taxonomy segment of the URL: + +{{< code-toggle file=hugo >}} +[permalinks.term] +'tags' = '/:slug/' +{{< /code-toggle >}} + +## Multilingual example + +Use the `permalinks` configuration as a component of your localization strategy. + +With this content structure: + +```text +content/ +├── en/ +│ ├── books/ +│ │ ├── les-miserables.md +│ │ └── the-hunchback-of-notre-dame.md +│ └── _index.md +└── es/ + ├── books/ + │ ├── les-miserables.md + │ └── the-hunchback-of-notre-dame.md + └── _index.md +``` + - And this site configuration: ++And this project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = true + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +weight = 1 + +[languages.en.permalinks.page] +books = "/books/:slug/" + +[languages.en.permalinks.section] +books = "/books/" + +[languages.es] +contentDir = 'content/es' +languageCode = 'es-ES' +languageDirection = 'ltr' +languageName = 'Español' +weight = 2 + +[languages.es.permalinks.page] +books = "/libros/:slug/" + +[languages.es.permalinks.section] +books = "/libros/" +{{< /code-toggle >}} + +The structure of the published site will be: + +```text +public/ +├── en/ +│ ├── books/ +│ │ ├── les-miserables/ +│ │ │ └── index.html +│ │ ├── the-hunchback-of-notre-dame/ +│ │ │ └── index.html +│ │ └── index.html +│ └── index.html +├── es/ +│ ├── libros/ +│ │ ├── les-miserables/ +│ │ │ └── index.html +│ │ ├── the-hunchback-of-notre-dame/ +│ │ │ └── index.html +│ │ └── index.html +│ └── index.html +└── index.html +``` + +## Tokens + +Use these tokens when defining a URL pattern. + +{{% include "/_common/permalink-tokens.md" %}} + +[`url`]: /content-management/front-matter/#url diff --cc docs/content/en/configuration/related-content.md index 967c72a9a,000000000..de8b33be4 mode 100644,000000..100644 --- a/docs/content/en/configuration/related-content.md +++ b/docs/content/en/configuration/related-content.md @@@ -1,111 -1,0 +1,111 @@@ +--- +title: Configure related content +linkTitle: Related content +description: Configure related content. +categories: [] +keywords: [] +--- + +> [!note] +> To understand Hugo's related content identification, please refer to the [related content] page. + - Hugo provides a sensible default configuration for identifying related content, but you can customize it in your site configuration, either globally or per language. ++Hugo provides a sensible default configuration for identifying related content, but you can customize it in your project configuration, either globally or per language. + +## Default configuration + +This is the default configuration: + +{{< code-toggle config=related />}} + +> [!note] - > Adding a `related` section to your site configuration requires you to provide a full configuration. You cannot override individual default values without specifying all related settings. ++> Adding a `related` section to your project configuration requires you to provide a full configuration. You cannot override individual default values without specifying all related settings. + +## Top-level options + +threshold +: (`int`) A value between 0-100, inclusive. A lower value will return more, but maybe not so relevant, matches. + +includeNewer +: (`bool`) Whether to include pages newer than the current page in the related content listing. This will mean that the output for older posts may change as new related content gets added. Default is `false`. + +toLower +: (`bool`) Whether to transform keywords in both the indexes and the queries to lower case. This may give more accurate results at a slight performance penalty. Default is `false`. + +## Per-index options + +name +: (`string`) The index name. This value maps directly to a page parameter. Hugo supports string values (`author` in the example) and lists (`tags`, `keywords` etc.) and time and date objects. + +type +: (`string`) One of `basic` or `fragments`. Default is `basic`. + +applyFilter +: (`string`) Apply a `type` specific filter to the result of a search. This is currently only used for the `fragments` type. + +weight +: (`int`) An integer weight that indicates how important this parameter is relative to the other parameters. It can be `0`, which has the effect of turning this index off, or even negative. Test with different values to see what fits your content best. Default is `0`. + +cardinalityThreshold +: (`int`) If between `1` and `100`, this is a percentage. All keywords that are used in more than this percentage of documents are removed. For example, setting this to `60` will remove all keywords that are used in more than 60% of the documents in the index. If `0`, no keyword is removed from the index. Default is `0`. + +pattern +: (`string`) This is currently only relevant for dates. When listing related content, we may want to list content that is also close in time. Setting "2006" (default value for date indexes) as the pattern for a date index will add weight to pages published in the same year. For busier blogs, "200601" (year and month) may be a better default. + +toLower +: (`bool`) Whether to transform keywords in both the indexes and the queries to lower case. This may give more accurate results at a slight performance penalty. Default is `false`. + +## Example + +Imagine we're building a book review site. Our main content will be book reviews, and we'll use genres and authors as taxonomies. When someone views a book review, we want to show a short list of related reviews based on shared authors and genres. + +Create the content: + +```text +content/ +└── book-reviews/ + ├── book-review-1.md + ├── book-review-2.md + ├── book-review-3.md + ├── book-review-4.md + └── book-review-5.md +``` + +Configure the taxonomies: + +{{< code-toggle file=hugo >}} +[taxonomies] +author = 'authors' +genre = 'genres' +{{< /code-toggle >}} + +Configure the related content identification: + +{{< code-toggle file=hugo >}} +[related] +includeNewer = true +threshold = 80 +toLower = true +[[related.indices]] +name = 'authors' +weight = 2 +[[related.indices]] +name = 'genres' +weight = 1 +{{< /code-toggle >}} + +We've configured the `authors` index with a weight of `2` and the `genres` index with a weight of `1`. This means Hugo prioritizes shared `authors` as twice as significant as shared `genres`. + +Then render a list of 5 related reviews with a _partial_ template like this: + +```go-html-template {file="layouts/_partials/related.html" copy=true} +{{ with site.RegularPages.Related . | first 5 }} +

Related content:

+ +{{ end }} +``` + +[related content]: /content-management/related-content/ diff --cc docs/content/en/configuration/roles.md index 9c5bfe62c,000000000..e5db3dcee mode 100644,000000..100644 --- a/docs/content/en/configuration/roles.md +++ b/docs/content/en/configuration/roles.md @@@ -1,24 -1,0 +1,35 @@@ +--- +title: Configure roles +linkTitle: Roles +description: Configure roles. +categories: [] +keywords: [] +--- + +{{< new-in 0.153.0 />}} + +This is the default configuration: + +{{< code-toggle config=roles />}} + - To define "guest" and "member" roles: ++## Settings ++ ++Use the following setting to define how Hugo orders roles. ++ ++weight ++: (`int`) The role [weight](g). ++ ++## Sort order ++ ++Hugo sorts roles by weight in ascending order, then lexicographically in ascending order. This affects build order and complement selection. ++ ++## Example ++ ++The following configuration demonstrates how to define multiple roles with specific weights. + +{{< code-toggle >}} +[roles.guest] +weight = 20 +[roles.member] +weight = 10 +{{< /code-toggle >}} - - Roles are sorted by their [weight](g) in descending order, then by their name in descending order. This affects build order and complement selection. diff --cc docs/content/en/configuration/security.md index f9eb91bd9,000000000..54342ad51 mode 100644,000000..100644 --- a/docs/content/en/configuration/security.md +++ b/docs/content/en/configuration/security.md @@@ -1,50 -1,0 +1,50 @@@ +--- +title: Configure security +linkTitle: Security +description: Configure security. +categories: [] +keywords: [] +--- + +Hugo's built-in security policy, which restricts access to `os/exec`, remote communication, and similar operations, is configured via allowlists. By default, access is restricted. If a build attempts to use a feature not included in the allowlist, it will fail, providing a detailed message. + +This is the default security configuration: + +{{< code-toggle config=security />}} + +enableInlineShortcodes +: (`bool`) Whether to enable [inline shortcodes]. Default is `false`. + +exec.allow +: (`[]string`) A slice of [regular expressions](g) matching the names of external executables that Hugo is allowed to run. + +exec.osEnv +: (`[]string`) A slice of [regular expressions](g) matching the names of operating system environment variables that Hugo is allowed to access. + +funcs.getenv +: (`[]string`) A slice of [regular expressions](g) matching the names of operating system environment variables that Hugo is allowed to access with the [`os.Getenv`] function. + +http.methods +: (`[]string`) A slice of [regular expressions](g) matching the HTTP methods that the [`resources.GetRemote`] function is allowed to use. + +http.mediaTypes +: (`[]string`) Applicable to the `resources.GetRemote` function, a slice of [regular expressions](g) matching the `Content-Type` in HTTP responses that Hugo trusts, bypassing file content analysis for media type detection. + +http.urls +: (`[]string`) A slice of [regular expressions](g) matching the URLs that the `resources.GetRemote` function is allowed to access. + +> [!note] +> Setting an allowlist to the string `none` will completely disable the associated feature. + - You can also override the site configuration with environment variables. For example, to block `resources.GetRemote` from accessing any URL: ++You can also override your project configuration with environment variables. For example, to block `resources.GetRemote` from accessing any URL: + +```txt +export HUGO_SECURITY_HTTP_URLS=none +``` + +Learn more about [using environment variables] to configure your site. + +[`os.Getenv`]: /functions/os/getenv +[`resources.GetRemote`]: /functions/resources/getremote +[inline shortcodes]: /content-management/shortcodes/#inline +[using environment variables]: /configuration/introduction/#environment-variables diff --cc docs/content/en/configuration/segments.md index a5e3f1c2a,000000000..77caa567e mode 100644,000000..100644 --- a/docs/content/en/configuration/segments.md +++ b/docs/content/en/configuration/segments.md @@@ -1,75 -1,0 +1,75 @@@ +--- +title: Configure segments +linkTitle: Segments +description: Configure your site for segmented rendering. +categories: [] +keywords: [] +--- + +> [!note] +> The `segments` configuration applies only to segmented rendering. While it controls when content is rendered, it doesn't restrict access to Hugo's complete object graph (sites and pages), which remains fully available. + +Segmented rendering offers several advantages: + +- Faster builds: Process large sites more efficiently. +- Rapid development: Render only a subset of your site for quicker iteration. +- Scheduled rebuilds: Rebuild specific sections at different frequencies (e.g., home page and news hourly, full site weekly). +- Targeted output: Generate specific output formats (like JSON for search indexes). + +## Segment definition + +Each segment is defined by include and exclude filters: + +- Filters: Each segment has zero or more exclude filters and zero or more include filters. +- Matchers: Each filter contains one or more field [glob pattern](g) matchers. +- Logic: Matchers within a filter use AND logic. Filters within a section (include or exclude) use OR logic. + +## Filter fields + +Available fields for filtering: + +kind +: (`string`) A [glob pattern](g) matching the [page kind](g). For example: `{taxonomy,term}`. + +sites +: {{< new-in 0.153.0 />}} +: (`map`) A map to define [sites matrix](g). + +output +: (`string`) A [glob pattern](g) matching the [output format](g) of the page. For example: `{html,json}`. + +path +: (`string`) A [glob pattern](g) matching the page's [logical path](g). For example: `{/books,/books/**}`. + +## Example + +Place broad filters, such as those for language or output format, in the excludes section. For example: + +{{< code-toggle file=hugo >}} +[segments.segment1] + [[segments.segment1.excludes]] + lang = "n*" + [[segments.segment1.excludes]] + lang = "en" + output = "rss" + [[segments.segment1.includes]] + kind = "{home,term,taxonomy}" + [[segments.segment1.includes]] + path = "{/docs,/docs/**}" +{{< /code-toggle >}} + +## Rendering segments + +Render specific segments using the [`renderSegments`] configuration or the `--renderSegments` flag: + - ```bash - hugo --renderSegments segment1 ++```sh ++hugo build --renderSegments segment1 +``` + +You can configure multiple segments and use a comma-separated list with `--renderSegments` to render them all. + - ```bash - hugo --renderSegments segment1,segment2 ++```sh ++hugo build --renderSegments segment1,segment2 +``` + +[`renderSegments`]: /configuration/all/#rendersegments diff --cc docs/content/en/configuration/taxonomies.md index fed1d4c5e,000000000..5da0f7f4c mode 100644,000000..100644 --- a/docs/content/en/configuration/taxonomies.md +++ b/docs/content/en/configuration/taxonomies.md @@@ -1,69 -1,0 +1,69 @@@ +--- +title: Configure taxonomies +linkTitle: Taxonomies +description: Configure taxonomies. +categories: [] +keywords: [] +--- + +The default configuration defines two [taxonomies](g), `categories` and `tags`. + +{{< code-toggle config=taxonomies />}} + +When creating a taxonomy: + +- Use the singular form for the key (e.g., `category`). +- Use the plural form for the value (e.g., `categories`). + +Then use the value as the key in front matter: + + +{{< code-toggle file=content/example.md fm=true >}} +title: Example +categories: + - vegetarian + - gluten-free +tags: + - appetizer + - main course +{{< /code-toggle >}} + +If you do not expect to assign more than one [term](g) from a given taxonomy to a content page, you may use the singular form for both key and value: + +{{< code-toggle file=hugo >}} +taxonomies: + author: author +{{< /code-toggle >}} + +Then in front matter: + + +{{< code-toggle file=content/example.md fm=true >}} +title: Example +author: + - Robert Smith +{{< /code-toggle >}} + + +The example above illustrates that even with a single term, the value is still provided as an array. + +You must explicitly define the default taxonomies to maintain them when adding a new one: + +{{< code-toggle file=hugo >}} +taxonomies: + author: author + category: categories + tag: tags +{{< /code-toggle >}} + - To disable the taxonomy system, use the [`disableKinds`] setting in the root of your site configuration to disable the `taxonomy` and `term` page [kinds](g). ++To disable the taxonomy system, use the [`disableKinds`] setting in the root of your project configuration to disable the `taxonomy` and `term` page [kinds](g). + +{{< code-toggle file=hugo >}} +disableKinds = ['taxonomy','term'] +{{< /code-toggle >}} + +[`disableKinds`]: /configuration/all/#disablekinds + +See the [taxonomies] section for more information. + +[taxonomies]: /content-management/taxonomies/ diff --cc docs/content/en/configuration/versions.md index e6902b643,000000000..7c0e91e59 mode 100644,000000..100644 --- a/docs/content/en/configuration/versions.md +++ b/docs/content/en/configuration/versions.md @@@ -1,26 -1,0 +1,37 @@@ +--- +title: Configure versions +linkTitle: Versions +description: Configure versions. +categories: [] +keywords: [] +--- + +{{< new-in 0.153.0 />}} + +This is the default configuration: + +{{< code-toggle config=versions />}} + - To define "v1.0.0" and "v2.0.0" versions: ++## Settings ++ ++Use the following setting to define how Hugo orders versions. ++ ++weight ++: (`int`) The language [weight](g). ++ ++## Sort order ++ ++Hugo sorts versions by weight in ascending order, then by their [semantic version][] in descending order. This affects build order and complement selection. ++ ++## Example ++ ++The following configuration demonstrates how to define multiple versions with specific weights. + +{{< code-toggle >}} +[versions."v1.0.0"] - weight = 0 ++weight = 20 +[versions."v2.0.0"] - weight = 0 ++weight = 10 +{{< /code-toggle >}} + - Versions are sorted by their [weight](g) in ascending order, then by their [semantic version] in descending order. This affects build order and complement selection. - +[semantic version]: https://semver.org/ diff --cc docs/content/en/content-management/comments.md index f4ab7d8be,000000000..ce7f43841 mode 100644,000000..100644 --- a/docs/content/en/content-management/comments.md +++ b/docs/content/en/content-management/comments.md @@@ -1,69 -1,0 +1,69 @@@ +--- +title: Comments +description: Hugo ships with an internal Disqus template, but this isn't the only commenting system that will work with your new Hugo website. +categories: [] +keywords: [] +aliases: [/extras/comments/] +--- + +Hugo ships with support for [Disqus](https://disqus.com/), a third-party service that provides comment and community capabilities to websites via JavaScript. + +Your theme may already support Disqus, but if not, it is easy to add to your templates via [Hugo's built-in Disqus partial][disquspartial]. + +## Add Disqus + +Hugo comes with all the code you need to load Disqus into your templates. Before adding Disqus to your site, you'll need to [set up an account][disqussetup]. + +### Configure Disqus + - Disqus comments require you set a single value in your [site's configuration file][configuration] like so: ++Disqus comments require you set a single value in your [project configuration][configuration]: + +{{< code-toggle file=hugo >}} +[services.disqus] +shortname = 'your-disqus-shortname' +{{}} + +For many websites, this is enough configuration. However, you also have the option to set the following in the [front matter] of a single content file: + +- `disqus_identifier` +- `disqus_title` +- `disqus_url` + +### Render Hugo's built-in Disqus partial template + +Disqus has its own [internal template](/templates/embedded/#disqus) available, to render it add the following code where you want comments to appear: + +```go-html-template +{{ partial "disqus.html" . }} +``` + +## Alternatives + +Commercial commenting systems: + +- [Commentix](https://www.commentix.com/) +- [Emote](https://emote.com/) +- [Graph Comment](https://graphcomment.com/) +- [Hyvor Talk](https://talk.hyvor.com/) +- [IntenseDebate](https://intensedebate.com/) +- [ReplyBox](https://getreplybox.com/) + +Open-source commenting systems: + +- [Cactus Comments](https://cactus.chat/docs/integrations/hugo/) +- [Comentario](https://gitlab.com/comentario/comentario/) +- [Comma](https://github.com/Dieterbe/comma/) +- [Commento](https://commento.io/) +- [Discourse](https://meta.discourse.org/t/embed-discourse-comments-on-another-website-via-javascript/31963) +- [Giscus](https://giscus.app/) +- [Isso](https://isso-comments.de/) +- [Remark42](https://remark42.com/) +- [Staticman](https://staticman.net/) +- [Talkyard](https://blog-comments.talkyard.io/) +- [Utterances](https://utteranc.es/) +- [Zoomment](https://zoomment.com/) + +[configuration]: /configuration/ +[disquspartial]: /templates/embedded/#disqus +[disqussetup]: https://disqus.com/profile/signup/ +[front matter]: /content-management/front-matter/ diff --cc docs/content/en/content-management/content-adapters.md index f586311b3,000000000..0af08d732 mode 100644,000000..100644 --- a/docs/content/en/content-management/content-adapters.md +++ b/docs/content/en/content-management/content-adapters.md @@@ -1,356 -1,0 +1,354 @@@ +--- +title: Content adapters - description: Create content adapters to dynamically add content when building your site. ++description: Create content adapters to dynamically add content when building your project. +categories: [] +keywords: [] +--- + - {{< new-in 0.126.0 />}} - +## Overview + +A content adapter is a template that dynamically creates pages when building a site. For example, use a content adapter to create pages from a remote data source such as JSON, TOML, YAML, or XML. + +Unlike templates that reside in the `layouts` directory, content adapters reside in the `content` directory, no more than one per directory per language. When a content adapter creates a page, the page's [logical path](g) will be relative to the content adapter. + +```text +content/ +├── articles/ +│ ├── _index.md +│ ├── article-1.md +│ └── article-2.md +├── books/ +│ ├── _content.gotmpl <-- content adapter +│ └── _index.md +└── films/ + ├── _content.gotmpl <-- content adapter + └── _index.md +``` + +Each content adapter is named `_content.gotmpl` and uses the same [syntax] as templates in the `layouts` directory. You can use any of the [template functions] within a content adapter, as well as the methods described below. + +## Methods + +Use these methods within a content adapter. + +### AddPage + +Adds a page to the site. + +```go-html-template {file="content/books/_content.gotmpl"} +{{ $content := dict + "mediaType" "text/markdown" + "value" "The _Hunchback of Notre Dame_ was written by Victor Hugo." +}} +{{ $page := dict + "content" $content + "kind" "page" + "path" "the-hunchback-of-notre-dame" + "title" "The Hunchback of Notre Dame" +}} +{{ .AddPage $page }} +``` + +### AddResource + +Adds a page resource to the site. + +```go-html-template {file="content/books/_content.gotmpl"} +{{ with resources.Get "images/a.jpg" }} + {{ $content := dict + "mediaType" .MediaType.Type + "value" . + }} + {{ $resource := dict + "content" $content + "path" "the-hunchback-of-notre-dame/cover.jpg" + }} + {{ $.AddResource $resource }} +{{ end }} +``` + +Then retrieve the new page resource with something like: + +```go-html-template {file="layouts/page.html"} +{{ with .Resources.Get "cover.jpg" }} + +{{ end }} +``` + +### Site + +Returns the `Site` to which the pages will be added. + +```go-html-template {file="content/books/_content.gotmpl"} +{{ .Site.Title }} +``` + +> [!note] +> Note that the `Site` returned isn't fully built when invoked from the content adapters; if you try to call methods that depends on pages, e.g. `.Site.Pages`, you will get an error saying "this method cannot be called before the site is fully initialized". + +### Store + +Returns a persistent "scratch pad" to store and manipulate data. The main use case for this is to transfer values between executions when [EnableAllLanguages](#enablealllanguages) is set. See [examples](/methods/page/store/). + +```go-html-template {file="content/books/_content.gotmpl"} +{{ .Store.Set "key" "value" }} +{{ .Store.Get "key" }} +``` + +### EnableAllLanguages + +By default, Hugo executes the content adapter only once for the first matching site in the [sites matrix](g). Use this method to expand execution to all languages while maintaining the current role and version. + +For more fine-grained control, define a `sites.matrix` in front matter or in a content mount. + +```go-html-template {file="content/books/_content.gotmpl"} +{{ .EnableAllLanguages }} +{{ $content := dict + "mediaType" "text/markdown" + "value" "The _Hunchback of Notre Dame_ was written by Victor Hugo." +}} +{{ $page := dict + "content" $content + "kind" "page" + "path" "the-hunchback-of-notre-dame" + "title" "The Hunchback of Notre Dame" +}} +{{ .AddPage $page }} +``` + +### EnableAllDimensions + - By default, Hugo executes the content adapter only once for the first matching site in the [sites matrix](g). Use this method to expand execution to every possible combination of language, role, and version. ++By default, Hugo executes the content adapter only once for the first matching site in the [sites matrix](g). Use this method to expand execution to every possible combination of language, version, and role. + +For more fine-grained control, define a `sites.matrix` in front matter or in a content mount. + +{{< new-in v0.153.0 />}} + +## Page map + +Set any [front matter field] in the map passed to the [`AddPage`](#addpage) method, excluding `markup`. Instead of setting the `markup` field, specify the `content.mediaType` as described below. + +This table describes the fields most commonly passed to the `AddPage` method. + +Key|Description|Required +:--|:--|:-: +`content.mediaType`|The content [media type]. Default is `text/markdown`. See [content formats] for examples.|  +`content.value`|The content value as a string.|  +`dates.date`|The page creation date as a `time.Time` value.|  +`dates.expiryDate`|The page expiry date as a `time.Time` value.|  +`dates.lastmod`|The page last modification date as a `time.Time` value.|  +`dates.publishDate`|The page publication date as a `time.Time` value.|  +`params`|A map of page parameters.|  +`path`|The page's [logical path](g) relative to the content adapter. Do not include a leading slash or file extension.|:heavy_check_mark: +`title`|The page title.|  + +> [!note] +> While `path` is the only required field, we recommend setting `title` as well. +> +> When setting the `path`, Hugo transforms the given string to a logical path. For example, setting `path` to `A B C` produces a logical path of `/section/a-b-c`. + +## Resource map + +Construct the map passed to the [`AddResource`](#addresource) method using the fields below. + +Key|Description|Required +:--|:--|:-: +`content.mediaType`|The content [media type].|:heavy_check_mark: +`content.value`|The content value as a string or resource.|:heavy_check_mark: +`name`|The resource name.|  +`params`|A map of resource parameters.|  +`path`|The resources's [logical path](g) relative to the content adapter. Do not include a leading slash.|:heavy_check_mark: +`title`|The resource title.|  + +> [!note] +> When `content.value` is a string, Hugo generates a new resource with a publication path relative to the page. However, if `content.value` is already a resource, Hugo directly uses its value and publishes it relative to the site root. This latter method is more efficient. +> +> When setting the `path`, Hugo transforms the given string to a logical path. For example, setting `path` to `A B C/cover.jpg` produces a logical path of `/section/a-b-c/cover.jpg`. + +## Example + +Create pages from remote data, where each page represents a book review. + +Step 1 +: Create the content structure. + + ```text + content/ + └── books/ + ├── _content.gotmpl <-- content adapter + └── _index.md + ``` + +Step 2 +: Inspect the remote data to determine how to map key-value pairs to front matter fields.\ + + +Step 3 +: Create the content adapter. + + ```go-html-template {file="content/books/_content.gotmpl" copy=true} + {{/* Get remote data. */}} + {{ $data := dict }} + {{ $url := "https://gohugo.io/shared/examples/data/books.json" }} + {{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "Unable to get remote resource %s: %s" $url . }} + {{ else with .Value }} + {{ $data = . | transform.Unmarshal }} + {{ else }} + {{ errorf "Unable to get remote resource %s" $url }} + {{ end }} + {{ end }} + + {{/* Add pages and page resources. */}} + {{ range $data }} + + {{/* Add page. */}} + {{ $content := dict "mediaType" "text/markdown" "value" .summary }} + {{ $dates := dict "date" (time.AsTime .date) }} + {{ $params := dict "author" .author "isbn" .isbn "rating" .rating "tags" .tags }} + {{ $page := dict + "content" $content + "dates" $dates + "kind" "page" + "params" $params + "path" .title + "title" .title + }} + {{ $.AddPage $page }} + + {{/* Add page resource. */}} + {{ $item := . }} + {{ with $url := $item.cover }} + {{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "Unable to get remote resource %s: %s" $url . }} + {{ else with .Value }} + {{ $content := dict "mediaType" .MediaType.Type "value" .Content }} + {{ $params := dict "alt" $item.title }} + {{ $resource := dict + "content" $content + "params" $params + "path" (printf "%s/cover.%s" $item.title .MediaType.SubType) + }} + {{ $.AddResource $resource }} + {{ else }} + {{ errorf "Unable to get remote resource %s" $url }} + {{ end }} + {{ end }} + {{ end }} + + {{ end }} + ``` + +Step 4 +: Create a _page_ template to render each book review. + + ```go-html-template {file="layouts/books/page.html" copy=true} + {{ define "main" }} +

{{ .Title }}

+ + {{ with .Resources.GetMatch "cover.*" }} + {{ .Params.alt }} + {{ end }} + +

Author: {{ .Params.author }}

+ +

+ ISBN: {{ .Params.isbn }}
+ Rating: {{ .Params.rating }}
+ Review date: {{ .Date | time.Format ":date_long" }} +

+ + {{ with .GetTerms "tags" }} +

Tags:

+ + {{ end }} + + {{ .Content }} + {{ end }} + ``` + +## Multilingual sites + +With multilingual sites you can: + +1. Create one content adapter for all languages using the [`EnableAllLanguages`](#enablealllanguages) method as described above. +1. Create content adapters unique to each language. See the examples below. + +### Translations by file name + - With this site configuration: ++With this project configuration: + +{{< code-toggle file=hugo >}} +[languages.en] +weight = 1 + +[languages.de] +weight = 2 +{{< /code-toggle >}} + +Include a language designator in the content adapter's file name. + +```text +content/ +└── books/ + ├── _content.de.gotmpl + ├── _content.en.gotmpl + ├── _index.de.md + └── _index.en.md +``` + +### Translations by content directory + - With this site configuration: ++With this project configuration: + +{{< code-toggle file=hugo >}} +[languages.en] +contentDir = 'content/en' +weight = 1 + +[languages.de] +contentDir = 'content/de' +weight = 2 +{{< /code-toggle >}} + +Create a single content adapter in each directory: + +```text +content/ +├── de/ +│ └── books/ +│ ├── _content.gotmpl +│ └── _index.md +└── en/ + └── books/ + ├── _content.gotmpl + └── _index.md +``` + +## Page collisions + +Two or more pages collide when they have the same publication path. Due to concurrency, the content of the published page is indeterminate. Consider this example: + +```text +content/ +└── books/ + ├── _content.gotmpl <-- content adapter + ├── _index.md + └── the-hunchback-of-notre-dame.md +``` + +If the content adapter also creates `books/the-hunchback-of-notre-dame`, the content of the published page is indeterminate. You can not define the processing order. + - To detect page collisions, use the `--printPathWarnings` flag when building your site. ++To detect page collisions, use the `--printPathWarnings` flag when building your project. + +[content formats]: /content-management/formats/#classification +[front matter field]: /content-management/front-matter/#fields +[media type]: https://en.wikipedia.org/wiki/Media_type +[syntax]: /templates/introduction/ +[template functions]: /functions/ diff --cc docs/content/en/content-management/formats.md index 65fb3d04d,000000000..0f9fe7f1c mode 100644,000000..100644 --- a/docs/content/en/content-management/formats.md +++ b/docs/content/en/content-management/formats.md @@@ -1,133 -1,0 +1,133 @@@ +--- +title: Content formats +description: Create your content using Markdown, HTML, Emacs Org Mode, AsciiDoc, Pandoc, or reStructuredText. +categories: [] +keywords: [] +aliases: [/content/markdown-extras/,/content/supported-formats/,/doc/supported-formats/] +--- + +## Introduction + +You may mix content formats throughout your site. For example: + +```text +content/ +└── posts/ + ├── post-1.md + ├── post-2.adoc + ├── post-3.org + ├── post-4.pandoc + ├── post-5.rst + └── post-6.html +``` + +Regardless of content format, all content must have [front matter], preferably including both `title` and `date`. + +Hugo selects the content renderer based on the `markup` identifier in front matter, falling back to the file extension. See the [classification] table below for a list of markup identifiers and recognized file extensions. + +[classification]: #classification +[front matter]: /content-management/front-matter/ + +## Formats + +### Markdown + +Create your content in [Markdown] preceded by front matter. + - Markdown is Hugo's default content format. Hugo natively renders Markdown to HTML using [Goldmark]. Goldmark is fast and conforms to the [CommonMark] and [GitHub Flavored Markdown] specifications. You can configure Goldmark in your [site configuration][configure goldmark]. ++Markdown is Hugo's default content format. Hugo natively renders Markdown to HTML using [Goldmark]. Goldmark is fast and conforms to the [CommonMark] and [GitHub Flavored Markdown] specifications. You can configure Goldmark in your [project configuration][configure goldmark]. + +Hugo provides custom Markdown features including: + +[Attributes] +: Apply HTML attributes such as `class` and `id` to Markdown images and block elements including blockquotes, fenced code blocks, headings, horizontal rules, lists, paragraphs, and tables. + +[Extensions] +: Leverage the embedded Markdown extensions to create tables, definition lists, footnotes, task lists, inserted text, mark text, subscripts, superscripts, and more. + +[Mathematics] +: Include mathematical equations and expressions in Markdown using LaTeX markup. + +[Render hooks] +: Override the conversion of Markdown to HTML when rendering fenced code blocks, headings, images, and links. For example, render every standalone image as an HTML `figure` element. + +[Attributes]: /content-management/markdown-attributes/ +[CommonMark]: https://spec.commonmark.org/current/ +[Extensions]: /configuration/markup/#extensions +[GitHub Flavored Markdown]: https://github.github.com/gfm/ +[Goldmark]: https://github.com/yuin/goldmark +[Markdown]: https://daringfireball.net/projects/markdown/ +[Mathematics]: /content-management/mathematics/ +[Render hooks]: /render-hooks/introduction/ +[configure goldmark]: /configuration/markup/#goldmark + +### HTML + +Create your content in [HTML] preceded by front matter. The content is typically what you would place within an HTML document's `body` or `main` element. + +[HTML]: https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Creating_the_content + +### Emacs Org Mode + +Create your content in the [Emacs Org Mode] format preceded by front matter. You can use Org Mode keywords for front matter. See [details]. + +[details]: /content-management/front-matter/#emacs-org-mode +[Emacs Org Mode]: https://orgmode.org/ + +### AsciiDoc + +Create your content in the [AsciiDoc] format preceded by front matter. Hugo renders AsciiDoc content to HTML using the Asciidoctor executable. You must install Asciidoctor and its dependencies (Ruby) to render the AsciiDoc content format. + - You can configure the AsciiDoc renderer in your [site configuration][configure asciidoc]. ++You can configure the AsciiDoc renderer in your [project configuration][configure asciidoc]. + +In its default configuration, Hugo passes these CLI flags when calling the Asciidoctor executable: + +```text +--no-header-footer +``` + - The CLI flags passed to the Asciidoctor executable depend on configuration. You may inspect the flags when building your site: ++The CLI flags passed to the Asciidoctor executable depend on configuration. You may inspect the flags when building your project: + +```text - hugo --logLevel info ++hugo build --logLevel info +``` + +[AsciiDoc]: https://asciidoc.org/ +[configure asciidoc]: /configuration/markup/#asciidoc + +### Pandoc + +Create your content in the [Pandoc] format[^1] preceded by front matter. Hugo renders Pandoc content to HTML using the Pandoc executable. You must install Pandoc to render the Pandoc content format. + +[^1]: This is a derivation of the Markdown format as described by the CommonMark specification. + +Hugo passes these CLI flags when calling the Pandoc executable: + +```text +--mathjax +``` + +[Pandoc]: https://pandoc.org/MANUAL.html#pandocs-markdown + +### reStructuredText + +Create your content in the [reStructuredText] format preceded by front matter. Hugo renders reStructuredText content to HTML using [Docutils], specifically rst2html. You must install Docutils and its dependencies (Python) to render the reStructuredText content format. + +Hugo passes these CLI flags when calling the rst2html executable: + +```text +--leave-comments --initial-header-level=2 +``` + +[Docutils]: https://docutils.sourceforge.io/ +[reStructuredText]: https://docutils.sourceforge.io/rst.html + +## Classification + +{{% include "/_common/content-format-table.md" %}} + +When converting content to HTML, Hugo uses: + +- Native renderers for Markdown, HTML, and Emacs Org mode +- External renderers for AsciiDoc, Pandoc, and reStructuredText + +Native renderers are faster than external renderers. diff --cc docs/content/en/content-management/front-matter.md index 9b2a434b8,000000000..c734789df mode 100644,000000..100644 --- a/docs/content/en/content-management/front-matter.md +++ b/docs/content/en/content-management/front-matter.md @@@ -1,381 -1,0 +1,379 @@@ +--- +title: Front matter +description: Use front matter to add metadata to your content. +categories: [] +keywords: [] +aliases: [/content/front-matter/] +--- + +## Overview + +The front matter at the top of each content file is metadata that: + +- Describes the content +- Augments the content +- Establishes relationships with other content +- Controls the published structure of your site +- Determines template selection + +Provide front matter using a serialization format, one of [JSON], [TOML], or [YAML]. Hugo determines the front matter format by examining the delimiters that separate the front matter from the page content. + +See examples of front matter delimiters by toggling between the serialization formats below. + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +date = 2024-02-02T04:14:54-08:00 +draft = false +weight = 10 +[params] +author = 'John Smith' +{{< /code-toggle >}} + +Front matter fields may be [boolean](g), [integer](g), [float](g), [string](g), [arrays](g), or [maps](g). Note that the TOML format also supports unquoted date/time values. + +## Fields + +The most common front matter fields are `date`, `draft`, `title`, and `weight`, but you can specify metadata using any of fields below. + +> [!note] +> The field names below are reserved. For example, you cannot create a custom field named `type`. Create custom fields under the `params` key. See the [parameters] section for details. + +[parameters]: #parameters + +aliases +: (`[]string`) An array of one or more [page-relative](g) or [site-relative](g) paths that should redirect to the current page. Hugo resolves these to [server-relative](g) URLs during the build process. Access these values from a template using the [`Aliases`] method on a `Page` object. See the [aliases] section for details. + +build +: (`map`) A map of [build options]. + +cascade +: (`map`) A map (or a slice of maps) of front matter keys whose values are passed down to the page's descendants unless overwritten by self or a closer ancestor's cascade. See the [cascade] section for details. + +date +: (`string`) The date associated with the page, typically the creation date. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Date`] method on a `Page` object. + +description +: (`string`) Conceptually different than the page `summary`, the description is typically rendered within a `meta` element within the `head` element of the published HTML file. Access this value from a template using the [`Description`] method on a `Page` object. + +draft +: (`bool`) Whether to disable rendering unless you pass the `--buildDrafts` flag to the `hugo` command. Access this value from a template using the [`Draft`] method on a `Page` object. + +expiryDate +: (`string`) The page expiration date. On or after the expiration date, the page will not be rendered unless you pass the `--buildExpired` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`ExpiryDate`] method on a `Page` object. + +headless +: (`bool`) Applicable to [leaf bundles], whether to set the `render` and `list` [build options] to `never`, creating a headless bundle of [page resources]. + +isCJKLanguage +: (`bool`) Whether the content language is in the [CJK](g) family. This value determines how Hugo calculates word count, and affects the values returned by the [`WordCount`], [`FuzzyWordCount`], [`ReadingTime`], and [`Summary`] methods on a `Page` object. + +keywords +: (`[]string`) An array of keywords, typically rendered within a `meta` element within the `head` element of the published HTML file, or used as a [taxonomy](g) to classify content. Access these values from a template using the [`Keywords`] method on a `Page` object. + +lastmod +: (`string`) The date that the page was last modified. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`Lastmod`] method on a `Page` object. + +layout +: (`string`) Provide a template name to [target a specific template], overriding the default [template lookup order]. Set the value to the base file name of the template, excluding its extension. Access this value from a template using the [`Layout`] method on a `Page` object. + +linkTitle +: (`string`) Typically a shorter version of the `title`. Access this value from a template using the [`LinkTitle`] method on a `Page` object. + +markup +: (`string`) An identifier corresponding to one of the supported [content formats]. If not provided, Hugo determines the content renderer based on the file extension. + +menus +: (`string`, `[]string`, or `map`) If set, Hugo adds the page to the given menu or menus. See the [menus] page for details. + +modified +: Alias to [lastmod](#lastmod). + +outputs +: (`[]string`) The [output formats] to render. See [configure outputs] for more information. + +params +: (`map`) A map of custom [page parameters]. + +pubdate +: Alias to [publishDate](#publishdate). + +publishDate +: (`string`) The page publication date. Before the publication date, the page will not be rendered unless you pass the `--buildFuture` flag to the `hugo` command. Note that the TOML format also supports unquoted date/time values. See the [dates](#dates) section for examples. Access this value from a template using the [`PublishDate`] method on a `Page` object. + +published +: Alias to [publishDate](#publishdate). + +resources +: (`map array`) An array of maps to provide metadata for [page resources]. + +sitemap +: (`map`) A map of sitemap options. See the [sitemap templates] page for details. Access these values from a template using the [`Sitemap`] method on a `Page` object. + +sites +: {{< new-in 0.153.0 />}} +: (`map`) A map to define [sites matrix](g) and [sites complements](g) for the page. + + + + {{< code-toggle file=content/_index.md fm=true >}} + title = 'Home' + [sites.matrix] + languages = ["en","fr"] + versions = ["v1.2.*","v2.*.*"] + roles = ["**"] + [sites.complements] + versions = ["v3.*.*"] + {{< /code-toggle >}} + + + +slug +: (`string`) Overrides the last segment of the URL path. Not applicable to `home`, `section`, `taxonomy`, or `term` pages. See the [URL management] page for details. Access this value from a template using the [`Slug`] method on a `Page` object. + +summary +: (`string`) Conceptually different than the page `description`, the summary either summarizes the content or serves as a teaser to encourage readers to visit the page. Access this value from a template using the [`Summary`] method on a `Page` object. + +title +: (`string`) The page title. Access this value from a template using the [`Title`] method on a `Page` object. + +translationKey +: (`string`) An arbitrary value used to relate two or more translations of the same page, useful when the translated pages do not share a common path. Access this value from a template using the [`TranslationKey`] method on a `Page` object. + +type +: (`string`) The [content type](g), overriding the value derived from the top-level section in which the page resides. Access this value from a template using the [`Type`] method on a `Page` object. + +unpublishdate +: Alias to [expirydate](#expirydate). + +url +: (`string`) Overrides the entire URL path. Applicable to regular pages and section pages. See the [URL management] page for details. + +weight +: (`int`) The page [weight](g), used to order the page within a [page collection](g). Access this value from a template using the [`Weight`] method on a `Page` object. + +## Parameters + +Specify custom page parameters under the `params` key in front matter: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +date = 2024-02-02T04:14:54-08:00 +draft = false +weight = 10 +[params] +author = 'John Smith' +{{< /code-toggle >}} + +Access these values from a template using the [`Params`] or [`Param`] method on a `Page` object. + +Hugo provides [embedded templates] to optionally insert meta data within the `head` element of your rendered pages. These embedded templates expect the following front matter parameters: + +Parameter|Data type|Used by these embedded templates +:--|:--|:-- +`audio`|`[]string`|[`opengraph.html`] +`images`|`[]string`|[`opengraph.html`], [`schema.html`], [`twitter_cards.html`] +`videos`|`[]string`|[`opengraph.html`] + +The embedded templates will skip a parameter if not provided in front matter, but will throw an error if the data type is unexpected. + +## Taxonomies + - Classify content by adding taxonomy terms to front matter. For example, with this site configuration: ++Classify content by adding taxonomy terms to front matter. For example, with this project configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +tag = 'tags' +genre = 'genres' +{{< /code-toggle >}} + +Add taxonomy terms as shown below: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +date = 2024-02-02T04:14:54-08:00 +draft = false +weight = 10 +tags = ['red','blue'] +genres = ['mystery','romance'] +[params] +author = 'John Smith' +{{< /code-toggle >}} + +You can add taxonomy terms to the front matter of any these [page kinds](g): + +- `home` +- `page` +- `section` +- `taxonomy` +- `term` + +Access taxonomy terms from a template using the [`Params`] or [`GetTerms`] method on a `Page` object. For example: + +```go-html-template {file="layouts/page.html"} +{{ with .GetTerms "tags" }} +

Tags

+ +{{ end }} +``` + +[`GetTerms`]: /methods/page/getterms/ + +## Cascade + +A [node](g) can cascade front matter values to its descendants. However, this cascading will be prevented if the descendant already defines the field, or if a closer ancestor node has already cascaded a value for that same field. + +For example, to cascade a "color" parameter from the home page to all its descendants: + +{{< code-toggle file=content/_index.md fm=true >}} +title = 'Home' +[cascade.params] +color = 'red' +{{< /code-toggle >}} + +{{< new-in 0.153.0 />}} +From Hugo 0.153.0, you can also set the [sites](#sites) front matter as cascade front matter values, which means that you can e.g. apply one or more languages to the `target` pages. + +### Target + + + +The `target`[^1] keyword allows you to target specific pages or [environments](g). For example, to cascade a "color" parameter from the home page only to pages within the "articles" section, including the "articles" section page itself: + +[^1]: The `_target` alias for `target` is deprecated and will be removed in a future release. + +{{< code-toggle file=content/_index.md fm=true >}} +title = 'Home' +[cascade.params] +color = 'red' +[cascade.target] +path = '{/articles,/articles/**}' +[cascade.target.sites.matrix] +languages = ['en','fr'] +{{< /code-toggle >}} + +Use any combination of these keywords to target pages and/or environments: + +environment +: (`string`) A [glob pattern](g) matching the build [environment](g). For example: `{staging,production}`. + +kind +: (`string`) A [glob pattern](g) matching the [page kind](g). For example: `{taxonomy,term}`. + +path +: (`string`) A [glob pattern](g) matching the page's [logical path](g). For example: `{/books,/books/**}`. + +sites +: {{< new-in 0.153.0 />}} +: (`map`) A map to define [sites matrix](g) for the target, as in: Which sites should receive the cascaded values. + +### Array + +Define an array of cascade parameters to apply different values to different targets. For example: + +{{< code-toggle file=content/_index.md fm=true >}} +title = 'Home' +[[cascade]] +[cascade.params] +color = 'red' +[cascade.target] +path = '{/books/**}' +kind = 'page' +[[cascade]] +[cascade.params] +color = 'blue' +[cascade.target] +path = '{/films/**}' +kind = 'page' +{{< /code-toggle >}} + +> [!note] - > For multilingual sites, defining cascade values in your site configuration is often more efficient. This avoids repeating the same cascade values on the home, section, taxonomy, or term page for each language. See [details](/configuration/cascade/). ++> For multilingual sites, defining cascade values in your project configuration is often more efficient. This avoids repeating the same cascade values on the home, section, taxonomy, or term page for each language. See [details](/configuration/cascade/). +> +> If you choose to define cascade values in front matter for a multilingual site, you must create a corresponding home, section, taxonomy, or term page for every language. + +## Emacs Org Mode + +If your [content format] is [Emacs Org Mode], you may provide front matter using Org Mode keywords. For example: + +```text {file="content/example.org"} +#+TITLE: Example +#+DATE: 2024-02-02T04:14:54-08:00 +#+DRAFT: false +#+AUTHOR: John Smith +#+GENRES: mystery +#+GENRES: romance +#+TAGS: red +#+TAGS: blue +#+WEIGHT: 10 +``` + +Note that you can also specify array elements on a single line: + +```text {file="content/example.org"} +#+TAGS[]: red blue +``` + +[content format]: /content-management/formats/ +[emacs org mode]: https://orgmode.org/ + +## Dates + +When populating a date field, whether a [custom page parameter](#parameters) or one of the four predefined fields ([`date`](#date), [`expiryDate`](#expirydate), [`lastmod`](#lastmod), [`publishDate`](#publishdate)), use one of these parsable formats: + +{{% include "/_common/parsable-date-time-strings.md" %}} + - To override the default time zone, set the [`timeZone`](/configuration/all/#timezone) in your site configuration. The order of precedence for determining the time zone is: ++To override the default time zone, set the [`timeZone`](/configuration/all/#timezone) in your project configuration. The order of precedence for determining the time zone is: + +1. The time zone offset in the date/time string - 1. The time zone specified in your site configuration ++1. The time zone specified in your project configuration +1. The `Etc/UTC` time zone + +[`aliases`]: /methods/page/aliases/ +[`date`]: /methods/page/date/ +[`description`]: /methods/page/description/ +[`draft`]: /methods/page/draft/ +[`expirydate`]: /methods/page/expirydate/ +[`fuzzywordcount`]: /methods/page/wordcount/ +[`keywords`]: /methods/page/keywords/ +[`lastmod`]: /methods/page/date/ +[`layout`]: /methods/page/layout/ +[`linktitle`]: /methods/page/linktitle/ +[`opengraph.html`]: <{{% eturl opengraph %}}> +[`Param`]: /methods/page/param/ +[`Params`]: /methods/page/params/ +[`publishdate`]: /methods/page/publishdate/ +[`readingtime`]: /methods/page/readingtime/ +[`schema.html`]: <{{% eturl schema %}}> +[`sitemap`]: /methods/page/sitemap/ +[`slug`]: /methods/page/slug/ +[`Summary`]: /methods/page/summary/ +[`title`]: /methods/page/title/ +[`translationkey`]: /methods/page/translationkey/ +[`twitter_cards.html`]: <{{% eturl twitter_cards %}}> +[`type`]: /methods/page/type/ +[`weight`]: /methods/page/weight/ +[`wordcount`]: /methods/page/wordcount/ +[aliases]: /content-management/urls/#aliases +[build options]: /content-management/build-options/ +[cascade]: #cascade-1 +[configure outputs]: /configuration/outputs/#outputs-per-page +[content formats]: /content-management/formats/#classification +[embedded templates]: /templates/embedded/ +[json]: https://www.json.org/ +[leaf bundles]: /content-management/page-bundles/#leaf-bundles +[menus]: /content-management/menus/#define-in-front-matter +[output formats]: /configuration/output-formats/ +[page parameters]: #parameters +[page resources]: /content-management/page-resources/#metadata +[sitemap templates]: /templates/sitemap/ +[target a specific template]: /templates/lookup-order/#target-a-template +[template lookup order]: /templates/lookup-order/ +[toml]: https://toml.io/ +[URL management]: /content-management/urls/#slug +[yaml]: https://yaml.org/ diff --cc docs/content/en/content-management/image-processing/index.md index fca742048,000000000..9df622265 mode 100644,000000..100644 --- a/docs/content/en/content-management/image-processing/index.md +++ b/docs/content/en/content-management/image-processing/index.md @@@ -1,177 -1,0 +1,178 @@@ +--- +title: Image processing +description: Process, transform, and analyze images. +categories: [] +keywords: [] +--- + +Hugo provides methods to transform and analyze images during the build process. The results are cached to ensure subsequent builds remain fast. + +## Resources + +To process an image you must capture the file as a page resource, a global resource, or a remote resource. + +### Page + +{{% glossary-term "page resource" %}} + +```text +content/ +└── posts/ + └── post-1/ <-- page bundle + ├── index.md + └── sunset.jpg <-- page resource +``` + +To capture an image as a page resource: + +```go-html-template +{{ $image := .Resources.Get "sunset.jpg" }} +``` + +### Global + +{{% glossary-term "global resource" %}} + +```text +assets/ +└── images/ + └── sunset.jpg <-- global resource +``` + +To capture an image as a global resource: + +```go-html-template +{{ $image := resources.Get "images/sunset.jpg" }} +``` + +### Remote + +{{% glossary-term "remote resource" %}} + +To capture an image as a remote resource: + +```go-html-template +{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }} +``` + +## Rendering + +Once you have captured an image as a resource, render it in your templates using the [`Permalink`][], [`RelPermalink`][], [`Width`][], and [`Height`][] methods. + +Example 1: Throw an error if the resource is not found. + +```go-html-template +{{ $image := .Resources.GetMatch "sunset.jpg" }} + +``` + +Example 2: Skip image rendering if the resource is not found. + +```go-html-template +{{ $image := .Resources.GetMatch "sunset.jpg" }} +{{ with $image }} + +{{ end }} +``` + +Example 3: A more concise way to skip image rendering if the resource is not found. + +```go-html-template +{{ with .Resources.GetMatch "sunset.jpg" }} + +{{ end }} +``` + +Example 4: Skip rendering if there's problem accessing a remote resource. + +```go-html-template +{{ $url := "https://gohugo.io/img/hugo-logo.png" }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else with .Value }} + + {{ else }} + {{ errorf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +## Processing + +To transform an image, apply a processing method to the image resource. Hugo generates the processed image on demand, caches the result, and returns a new resource object. + +```go-html-template +{{ with .Resources.Get "sunset.jpg" }} + {{ with .Resize "400x" }} + + {{ end }} +{{ end }} +``` + +> [!note] +> Metadata is not preserved during image transformation. Use the `Exif` or `Meta` methods with the _original_ image resource to extract metadata from JPEG, PNG, TIFF, and WebP images. + +Each method serves a specific transformation or metadata requirement: + +Method|Description +:--|:-- +[`Colors`]|Returns a slice of the most dominant colors using a simple histogram method. +[`Crop`]|Returns a new image resource cropped according to the given processing specification. +[`Exif`]|Applicable to JPEG, PNG, TIFF, and WebP images, returns an object containing Exif metadata. +[`Fill`]|Returns a new image resource cropped and resized according to the given processing specification. +[`Filter`]|Applies one or more image filters to the given image resource. +[`Fit`]|Returns a new image resource downscaled to fit according to the given processing specification. +[`Meta`]|Applicable to JPEG, PNG, TIFF, and WebP images, returns an object containing Exif, IPTC, and XMP metadata. +[`Process`]|Returns a new image resource processed according to the given processing specification. +[`Resize`]|Returns a new image resource resized according to the given processing specification. +{class="!mt-0"} + +Select a method from the table above for syntax and usage examples. + +## Performance + +### Caching + - Hugo processes images on demand and returns a new resource object. To ensure subsequent builds remain fast, Hugo caches the results in the directory specified in the [file cache] section of your site configuration. ++Hugo processes images on demand and returns a new resource object. To ensure subsequent builds remain fast, Hugo caches the results in the directory specified in the [file cache][] section of your project configuration. + - If you host your site with Netlify, include the following in your site configuration to persist the image cache between builds: ++If you host your site with Netlify, include the following in your project configuration to persist the image cache between builds: + +```toml +[caches] + [caches.images] + dir = ':cacheDir/images' +``` + +### Garbage collection + +If you change image processing methods, or rename/remove images, the cache will eventually contain unused files. To remove them and reclaim disk space, run Hugo's garbage collection: + +```text - hugo --gc ++hugo build --gc +``` + +### Resource usage + +The time and memory required to process an image increase with the image's dimensions. For example, a `4032x2268` image requires significantly more memory and processing time than a `1920x1080` image. + +If your source images are much larger than the maximum size you intend to publish, consider scaling them down before the build to optimize performance. + +## Configuration + +See [configure imaging](/configuration/imaging). + +[`Colors`]: /methods/resource/colors/ +[`Crop`]: /methods/resource/crop/ +[`Exif`]: /methods/resource/exif/ +[`Fill`]: /methods/resource/fill/ +[`Filter`]: /methods/resource/filter/ +[`Fit`]: /methods/resource/fit/ +[`Height`]: /methods/resource/height/ +[`Meta`]: /methods/resource/meta/ +[`Permalink`]: /methods/resource/permalink/ +[`Process`]: /methods/resource/process/ +[`RelPermalink`]: /methods/resource/relpermalink/ +[`Resize`]: /methods/resource/resize/ +[`Width`]: /methods/resource/width/ ++[file cache]: /configuration/caches/ diff --cc docs/content/en/content-management/markdown-attributes.md index a27edc012,000000000..42e7bcf94 mode 100644,000000..100644 --- a/docs/content/en/content-management/markdown-attributes.md +++ b/docs/content/en/content-management/markdown-attributes.md @@@ -1,117 -1,0 +1,117 @@@ +--- +title: Markdown attributes +description: Use Markdown attributes to add HTML attributes when rendering Markdown to HTML. +categories: [] +keywords: [] +--- + +## Overview + +Hugo supports Markdown attributes on images and block elements including blockquotes, fenced code blocks, headings, horizontal rules, lists, paragraphs, and tables. + +For example: + +```text +This is a paragraph. +{class="foo bar" id="baz"} +``` + +With `class` and `id` attributes you can also use short-form notation: + +```text +This is a paragraph. +{.foo .bar #baz} +``` + +Hugo renders both of the examples above to: + +```html +

This is a paragraph.

+``` + +With `class` and `id` attributes, whether you use long-form or short-form notation, the resulting values are available in [render hook templates][] via the `Attributes` method. For example: + +```go-html-template +{{ .Attributes.class }} → foo bar +{{ .Attributes.id }} → baz +``` + +## Block elements + - Update your site configuration to enable Markdown attributes for block-level elements. ++Update your project configuration to enable Markdown attributes for block-level elements. + +{{< code-toggle file=hugo >}} +[markup.goldmark.parser.attribute] +title = true # default is true +block = true # default is false +{{< /code-toggle >}} + +## Standalone images + +By default, when the [Goldmark] Markdown renderer encounters a standalone image element (no other elements or text on the same line), it wraps the image element within a paragraph element per the [CommonMark specification]. + +[CommonMark specification]: https://spec.commonmark.org/current/ +[Goldmark]: https://github.com/yuin/goldmark + +If you were to place an attribute list beneath an image element, Hugo would apply the attributes to the surrounding paragraph, not the image. + +To apply attributes to a standalone image element, you must disable the default wrapping behavior: + +{{< code-toggle file=hugo >}} +[markup.goldmark.parser] +wrapStandAloneImageWithinParagraph = false # default is true +{{< /code-toggle >}} + +## Usage + +You may add [global HTML attributes], or HTML attributes specific to the current element type. Consistent with its content security model, Hugo removes HTML event attributes such as `onclick` and `onmouseover`. + +[global HTML attributes]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes + +The attribute list consists of one or more key-value pairs, separated by spaces or commas, wrapped by braces. You must quote string values that contain spaces. Unlike HTML, boolean attributes must have both key and value. + +For example: + +```text +> This is a blockquote. +{class="foo bar" hidden=hidden} +``` + +Hugo renders this to: + +```html + +``` + +In most cases, place the attribute list beneath the markup element. For headings and fenced code blocks, place the attribute list on the right. + +Element|Position of attribute list +:--|:-- +blockquote|bottom +fenced code block|right +heading|right +horizontal rule|bottom +image|bottom +list|bottom +paragraph|bottom +table|bottom + +For example: + +````text +## Section 1 {class=foo} + - ```bash {class=foo linenos=inline} ++```sh {class=foo linenos=inline} +declare a=1 +echo "${a}" +``` + +This is a paragraph. +{class=foo} +```` + +As shown above, the attribute list for fenced code blocks is not limited to HTML attributes. You can also configure syntax highlighting by passing one or more of [these options](/functions/transform/highlight/#options). + +[render hook templates]: /render-hooks/introduction/ diff --cc docs/content/en/content-management/mathematics.md index 5414a00f9,000000000..6b86cac1c mode 100644,000000..100644 --- a/docs/content/en/content-management/mathematics.md +++ b/docs/content/en/content-management/mathematics.md @@@ -1,237 -1,0 +1,237 @@@ +--- +title: Mathematics in Markdown +linkTitle: Mathematics +description: Include mathematical equations and expressions in Markdown using LaTeX markup. +categories: [] +keywords: [] +--- + +## Overview + +Mathematical equations and expressions written in [LaTeX][] are common in academic and scientific publications. Your browser typically renders this mathematical markup using an open-source JavaScript display engine such as [MathJax][] or [KaTeX][]. + +For example, this LaTeX markup: + +```text +\[ +\begin{aligned} +KL(\hat{y} || y) &= \sum_{c=1}^{M}\hat{y}_c \log{\frac{\hat{y}_c}{y_c}} \\ +JS(\hat{y} || y) &= \frac{1}{2}(KL(y||\frac{y+\hat{y}}{2}) + KL(\hat{y}||\frac{y+\hat{y}}{2})) +\end{aligned} +\] +``` + +Is rendered to: + +\[ +\begin{aligned} +KL(\hat{y} || y) &= \sum_{c=1}^{M}\hat{y}_c \log{\frac{\hat{y}_c}{y_c}} \\ +JS(\hat{y} || y) &= \frac{1}{2}(KL(y||\frac{y+\hat{y}}{2}) + KL(\hat{y}||\frac{y+\hat{y}}{2})) +\end{aligned} +\] + +Equations and expressions can be displayed inline with other text, or as standalone blocks. Block presentation is also known as "display" mode. + +Whether an equation or expression appears inline, or as a block, depends on the delimiters that surround the mathematical markup. Delimiters are defined in pairs, where each pair consists of an opening and closing delimiter. The opening and closing delimiters may be the same, or different. + +> [!note] - > You can configure Hugo to render mathematical markup on the client side using the MathJax or KaTeX display engine, or you can render the markup with the [`transform.ToMath`][] function while building your site. ++> You can configure Hugo to render mathematical markup on the client side using the MathJax or KaTeX display engine, or you can render the markup with the [`transform.ToMath`][] function while building your project. +> +> The first approach is described below. + +## Setup + +Follow these instructions to include mathematical equations and expressions in your Markdown using LaTeX markup. + +Step 1 - : Enable and configure the Goldmark [passthrough extension][] in your site configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves. ++: Enable and configure the Goldmark [passthrough extension][] in your project configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves. + + {{< code-toggle file=hugo copy=true >}} + [markup.goldmark.extensions.passthrough] + enable = true + + [markup.goldmark.extensions.passthrough.delimiters] + block = [['\[', '\]'], ['$$', '$$']] + inline = [['\(', '\)']] + + [params] + math = true + {{< /code-toggle >}} + - The configuration above enables mathematical rendering on every page unless you set the `math` parameter to `false` in front matter. To enable mathematical rendering as needed, set the `math` parameter to `false` in your site configuration, and set the `math` parameter to `true` in front matter. Use this parameter in your base template as shown in [Step 3][]. ++ The configuration above enables mathematical rendering on every page unless you set the `math` parameter to `false` in front matter. To enable mathematical rendering as needed, set the `math` parameter to `false` in your project configuration, and set the `math` parameter to `true` in front matter. Use this parameter in your base template as shown in [Step 3][]. + + > [!note] + > The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration and JavaScript, you must double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting. + > + > See the [inline delimiters][] section for details. + + To disable passthrough of inline snippets, omit the `inline` key from the configuration: + + {{< code-toggle file=hugo >}} + [markup.goldmark.extensions.passthrough.delimiters] + block = [['\[', '\]'], ['$$', '$$']] + {{< /code-toggle >}} + + You can define your own opening and closing delimiters, provided they match the delimiters that you set in [Step 2][]. + + {{< code-toggle file=hugo >}} + [markup.goldmark.extensions.passthrough.delimiters] + block = [['@@', '@@']] + inline = [['@', '@']] + {{< /code-toggle >}} + +Step 2 +: Create a _partial_ template to load MathJax or KaTeX. The example below loads MathJax, or you can use KaTeX as described in the [engines][] section. + + ```go-html-template {file="layouts/_partials/math.html" copy=true} + + + + ``` + - The delimiters above must match the delimiters in your site configuration. ++ The delimiters above must match the delimiters in your project configuration. + +Step 3 +: Conditionally call the _partial_ template from the base template. + + ```go-html-template {file="layouts/baseof.html"} + + ... + {{ if .Param "math" }} + {{ partialCached "math.html" . }} + {{ end }} + ... + + ``` + - The example above loads the _partial_ template if you have set the `math` parameter in front matter to `true`. If you have not set the `math` parameter in front matter, the conditional statement falls back to the `math` parameter in your site configuration. ++ The example above loads the _partial_ template if you have set the `math` parameter in front matter to `true`. If you have not set the `math` parameter in front matter, the conditional statement falls back to the `math` parameter in your project configuration. + +Step 4 - : If you set the `math` parameter to `false` in your site configuration, you must set the `math` parameter to `true` in front matter. For example: ++: If you set the `math` parameter to `false` in your project configuration, you must set the `math` parameter to `true` in front matter. For example: + + {{< code-toggle file=content/math-examples.md fm=true >}} + title = 'Math examples' + date = 2024-01-24T18:09:49-08:00 + [params] + math = true + {{< /code-toggle >}} + +Step 5 +: Include mathematical equations and expressions in Markdown using LaTeX markup. + + ```text {file="content/math-examples.md" copy=true} + This is an inline \(a^*=x-b^*\) equation. + + These are block equations: + + \[a^*=x-b^*\] + + \[ a^*=x-b^* \] + + \[ + a^*=x-b^* + \] + + These are also block equations: + + $$a^*=x-b^*$$ + + $$ a^*=x-b^* $$ + + $$ + a^*=x-b^* + $$ + ``` + +## Inline delimiters + +The configuration, JavaScript, and examples above use the `\(...\)` delimiter pair for inline equations. The `$...$` delimiter pair is a common alternative, but using it may result in unintended formatting if you use the `$` symbol outside of math contexts. + +If you add the `$...$` delimiter pair to your configuration and JavaScript, you must double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting. For example: + +```text +I will give you \\$2 if you can solve $y = x^2$. +``` + +> [!note] +> If you use the `$...$` delimiter pair for inline equations, and occasionally use the `$` symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation][]. + +## Engines + +MathJax and KaTeX are open-source JavaScript display engines. + +> [!note] +> If you use the `$...$` delimiter pair for inline equations, and occasionally use the `$` symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation][]. +> +>See the [inline delimiters][] section for details. + +To use KaTeX instead of MathJax, replace the _partial_ template from [Step 2][] with this: + +```go-html-template {file="layouts/_partials/math.html" copy=true} + + + + +``` + - The delimiters above must match the delimiters in your site configuration. ++The delimiters above must match the delimiters in your project configuration. + +## Chemistry + +Both MathJax and KaTeX provide support for chemical equations. For example: + +```text +$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$ +``` + +$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$ + +As shown in [Step 2][] above, MathJax supports chemical equations without additional configuration. To add chemistry support to KaTeX, enable the mhchem extension as described in the KaTeX [documentation](https://katex.org/docs/libs). + +[`transform.ToMath`]: /functions/transform/tomath/ +[engines]: #engines +[inline delimiters]: #inline-delimiters +[KaTeX]: https://katex.org/ +[LaTeX]: https://www.latex-project.org/ +[MathJax]: https://www.mathjax.org/ +[passthrough extension]: /configuration/markup/#passthrough +[Step 2]: #step-2 +[Step 3]: #step-3 +[this KaTeX limitation]: https://github.com/KaTeX/KaTeX/issues/437 diff --cc docs/content/en/content-management/menus.md index 8ff0597b3,000000000..50920eefa mode 100644,000000..100644 --- a/docs/content/en/content-management/menus.md +++ b/docs/content/en/content-management/menus.md @@@ -1,99 -1,0 +1,99 @@@ +--- +title: Menus +description: Create menus by defining entries, localizing each entry, and rendering the resulting data structure. +categories: [] +keywords: [] +aliases: [/extras/menus/] +--- + +## Overview + +To create a menu for your site: + +1. Define the menu entries +1. [Localize](multilingual/#menus) each entry +1. Render the menu with a [template] + +Create multiple menus, either flat or nested. For example, create a main menu for the header, and a separate menu for the footer. + +There are three ways to define menu entries: + +1. Automatically +1. In front matter - 1. In site configuration ++1. In your project configuration + +> [!note] +> Although you can use these methods in combination when defining a menu, the menu will be easier to conceptualize and maintain if you use one method throughout the site. + +## Define automatically + - To automatically define a menu entry for each top-level [section](g) of your site, enable the section pages menu in your site configuration. ++To automatically define a menu entry for each top-level [section](g) of your site, enable the section pages menu in your project configuration. + +{{< code-toggle file=hugo >}} +sectionPagesMenu = "main" +{{< /code-toggle >}} + +This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details. + +## Define in front matter + +To add a page to the "main" menu: + +{{< code-toggle file=content/about.md fm=true >}} +title = 'About' +menus = 'main' +{{< /code-toggle >}} + +Access the entry with `site.Menus.main` in your templates. See [menu templates] for details. + +To add a page to the "main" and "footer" menus: + +{{< code-toggle file=content/contact.md fm=true >}} +title = 'Contact' +menus = ['main','footer'] +{{< /code-toggle >}} + +Access the entry with `site.Menus.main` and `site.Menus.footer` in your templates. See [menu templates] for details. + +> [!note] +> The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`. + +### Properties + +Use these properties when defining menu entries in front matter: + +{{% include "/_common/menu-entry-properties.md" %}} + +### Example + +This front matter menu entry demonstrates some of the available properties: + + +{{< code-toggle file=content/products/software.md fm=true >}} +title = 'Software' +[menus.main] +parent = 'Products' +weight = 20 +pre = '' +[menus.main.params] +class = 'center' +{{< /code-toggle >}} + + +Access the entry with `site.Menus.main` in your templates. See [menu templates] for details. + - ## Define in site configuration ++## Define in project configuration + +See [configure menus](/configuration/menus/). + +## Localize + +Hugo provides two methods to localize your menu entries. See [multilingual]. + +## Render + +See [menu templates]. + +[menu templates]: /templates/menu/ +[multilingual]: /content-management/multilingual/#menus +[template]: /templates/menu/ diff --cc docs/content/en/content-management/multilingual.md index 5a5cd2307,000000000..ec31204c2 mode 100644,000000..100644 --- a/docs/content/en/content-management/multilingual.md +++ b/docs/content/en/content-management/multilingual.md @@@ -1,429 -1,0 +1,429 @@@ +--- +title: Multilingual mode +linkTitle: Multilingual +description: Localize your project for each language and region, including translations, images, dates, currencies, numbers, percentages, and collation sequence. Hugo's multilingual framework supports single-host and multihost configurations. +categories: [] +keywords: [] +aliases: [/content/multilingual/,/tutorials/create-a-multilingual-site/] +--- + +## Configuration + +See [configure languages](/configuration/languages/). + +## Translate your content + +There are two ways to manage your content translations. Both ensure each page is assigned a language and is linked to its counterpart translations. + +### Translation by file name + +Considering the following example: + +1. `/content/about.en.md` +1. `/content/about.fr.md` + +The first file is assigned the English language and is linked to the second. +The second file is assigned the French language and is linked to the first. + +Their language is assigned according to the language code added as a suffix to the file name. + +By having the same path and base file name, the content pieces are linked together as translated pages. + +> [!note] +> If a file has no language code, it will be assigned the default language. + +### Translation by content directory + +This system uses different content directories for each of the languages. Each language's `content` directory is set using the `contentDir` parameter. + +{{< code-toggle file=hugo >}} +languages: + en: + weight: 10 + languageName: "English" + contentDir: "content/english" + fr: + weight: 20 + languageName: "Français" + contentDir: "content/french" +{{< /code-toggle >}} + +The value of `contentDir` can be any valid path -- even absolute path references. The only restriction is that the content directories cannot overlap. + +Considering the following example in conjunction with the configuration above: + +1. `/content/english/about.md` +1. `/content/french/about.md` + +The first file is assigned the English language and is linked to the second. +The second file is assigned the French language and is linked to the first. + +Their language is assigned according to the `content` directory they are placed in. + +By having the same path and basename (relative to their language `content` directory), the content pieces are linked together as translated pages. + +### Bypassing default linking + +Any pages sharing the same `translationKey` set in front matter will be linked as translated pages regardless of basename or location. + +Considering the following example: + +1. `/content/about-us.en.md` +1. `/content/om.nn.md` +1. `/content/presentation/a-propos.fr.md` + +{{< code-toggle file=hugo >}} +translationKey: "about" +{{< /code-toggle >}} + +By setting the `translationKey` front matter parameter to `about` in all three pages, they will be linked as translated pages. + +### Localizing permalinks + +Because paths and file names are used to handle linking, all translated pages will share the same URL (apart from the language subdirectory). + +To localize URLs: + +- For a regular page, set either [`slug`] or [`url`] in front matter +- For a section page, set [`url`] in front matter + +For example, a French translation can have its own localized slug. + +{{< code-toggle file=content/about.fr.md fm=true >}} +title: A Propos +slug: "a-propos" +{{< /code-toggle >}} + +At render, Hugo will build both `/about/` and `/fr/a-propos/` without affecting the translation link. + +### Page bundles + +To avoid the burden of having to duplicate files, each Page Bundle inherits the resources of its linked translated pages' bundles except for the content files (Markdown files, HTML files etc.). + +Therefore, from within a template, the page will have access to the files from all linked pages' bundles. + +If, across the linked bundles, two or more files share the same basename, only one will be included and chosen as follows: + +- File from current language bundle, if present. +- First file found across bundles by order of language `Weight`. + +> [!note] +> Page Bundle resources follow the same language assignment logic as content files, both by file name (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`). + +## Reference translated content + +To create a list of links to translated content, use a template similar to the following: + +```go-html-template {file="layouts/_partials/i18nlist.html"} +{{ if .IsTranslated }} +

{{ i18n "translations" }}

+ +{{ end }} +``` + +The above can be put in a _partial_ template then included in any template. It will not print anything if there are no translations for a given page. + +The above also uses the [`i18n` function][i18func] described in the next section. + +### List all available languages + +`.AllTranslations` on a `Page` can be used to list all translations, including the page itself. On the home page it can be used to build a language navigator: + +```go-html-template {file="layouts/_partials/allLanguages.html"} + +``` + +## Translation of strings + +See the [`lang.Translate`] template function. + +## Localization + +The following localization examples assume your site's primary language is English, with translations to French and German. + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages] +[languages.en] +contentDir = 'content/en' +languageName = 'English' +weight = 1 +[languages.fr] +contentDir = 'content/fr' +languageName = 'Français' +weight = 2 +[languages.de] +contentDir = 'content/de' +languageName = 'Deutsch' +weight = 3 + +{{< /code-toggle >}} + +### Dates + +With this front matter: + +{{< code-toggle file=hugo >}} +date = 2021-11-03T12:34:56+01:00 +{{< /code-toggle >}} + +And this template code: + +```go-html-template +{{ .Date | time.Format ":date_full" }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|Wednesday, November 3, 2021 +Français|mercredi 3 novembre 2021 +Deutsch|Mittwoch, 3. November 2021 + +See [`time.Format`] for details. + +### Currency + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatCurrency 2 "USD" }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|$512.50 +Français|512,50 $US +Deutsch|512,50 $ + +See [lang.FormatCurrency] and [lang.FormatAccounting] for details. + +### Numbers + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatNumber 2 }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|512.50 +Français|512,50 +Deutsch|512,50 + +See [lang.FormatNumber] and [lang.FormatNumberCustom] for details. + +### Percentages + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatPercent 2 }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|512.50% +Français|512,50 % +Deutsch|512,50 % + +See [lang.FormatPercent] for details. + +## Menus + +Localization of menu entries depends on how you define them: + +- When you define menu entries [automatically] using the section pages menu, you must use translation tables to localize each entry. - - When you define menu entries [in front matter], they are already localized based on the front matter itself. If the front matter values are insufficient, use translation tables to localize each entry. - - When you define menu entries [in site configuration], you must create language-specific menu entries under each language key. If the names of the menu entries are insufficient, use translation tables to localize each entry. ++- When you define menu entries in [front matter], they are already localized based on the front matter itself. If the front matter values are insufficient, use translation tables to localize each entry. ++- When you define menu entries in your [project configuration], you must create language-specific menu entries under each language key. If the names of the menu entries are insufficient, use translation tables to localize each entry. + +### Create language-specific menu entries + +#### Method 1 -- Use a single configuration file + +For a simple menu with a small number of entries, use a single configuration file. For example: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 1 + +[[languages.de.menus.main]] +name = 'Produkte' +pageRef = '/products' +weight = 10 + +[[languages.de.menus.main]] +name = 'Leistungen' +pageRef = '/services' +weight = 20 + +[languages.en] +languageCode = 'en-US' +languageName = 'English' +weight = 2 + +[[languages.en.menus.main]] +name = 'Products' +pageRef = '/products' +weight = 10 + +[[languages.en.menus.main]] +name = 'Services' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +#### Method 2 -- Use a configuration directory + +With a more complex menu structure, create a [configuration directory] and split the menu entries into multiple files, one file per language. For example: + +```text +config/ +└── _default/ + ├── menus.de.toml + ├── menus.en.toml + └── hugo.toml +``` + +{{< code-toggle file=config/_default/menus.de >}} +[[main]] +name = 'Produkte' +pageRef = '/products' +weight = 10 +[[main]] +name = 'Leistungen' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +{{< code-toggle file=config/_default/menus.en >}} +[[main]] +name = 'Products' +pageRef = '/products' +weight = 10 +[[main]] +name = 'Services' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +### Use translation tables + +When rendering the text that appears in menu each entry, the [example menu template] does this: + +```go-html-template +{{ or (T .Identifier) .Name | safeHTML }} +``` + +It queries the translation table for the current language using the menu entry's `identifier` and returns the translated string. If the translation table does not exist, or if the `identifier` key is not present in the translation table, it falls back to `name`. + +The `identifier` depends on how you define menu entries: + +- If you define the menu entry [automatically] using the section pages menu, the `identifier` is the page's `.Section`. - - If you define the menu entry [in site configuration] or [in front matter], set the `identifier` property to the desired value. ++- If you define the menu entry in your [project configuration] or in [front matter], set the `identifier` property to the desired value. + - For example, if you define menu entries in site configuration: ++For example, if you define menu entries in project configuration: + +{{< code-toggle file=hugo >}} +[[menus.main]] + identifier = 'products' + name = 'Products' + pageRef = '/products' + weight = 10 +[[menus.main]] + identifier = 'services' + name = 'Services' + pageRef = '/services' + weight = 20 +{{< / code-toggle >}} + +Create corresponding entries in the translation tables: + +{{< code-toggle file=i18n/de >}} +products = 'Produkte' +services = 'Leistungen' +{{< / code-toggle >}} + +## Missing translations + +If a string does not have a translation for the current language, Hugo will use the value from the default language. If no default value is set, an empty string will be shown. + +While translating a Hugo website, it can be handy to have a visual indicator of missing translations. The [`enableMissingTranslationPlaceholders` configuration option][config] will flag all untranslated strings with the placeholder `[i18n] identifier`, where `identifier` is the id of the missing translation. + +> [!note] +> Hugo will generate your website with these missing translation placeholders. It might not be suitable for production environments. + +For merging of content from other languages (i.e. missing content translations), see [lang.Merge]. + +To track down missing translation strings, run Hugo with the `--printI18nWarnings` flag: + +```sh - hugo --printI18nWarnings | grep i18n ++hugo build --printI18nWarnings | grep i18n +i18n|MISSING_TRANSLATION|en|wordCount +``` + +## Multilingual themes support + +To support Multilingual mode in your themes, some considerations must be taken for the URLs in the templates. If there is more than one language, URLs must meet the following criteria: + +- Come from the built-in `.Permalink` or `.RelPermalink` +- Be constructed with the [`relLangURL`] or [`absLangURL`] template function, or be prefixed with `{{ .LanguagePrefix }}` + +If there is more than one language defined, the `LanguagePrefix` method will return `/en` (or whatever the current language is). If not enabled, it will be an empty string (and is therefore harmless for single-language Hugo websites). + +## Generate multilingual content with `hugo new content` + +If you organize content with translations in the same directory: + +```sh +hugo new content post/test.en.md +hugo new content post/test.de.md +``` + +If you organize content with translations in different directories: + +```sh +hugo new content content/en/post/test.md +hugo new content content/de/post/test.md +``` + +[`absLangURL`]: /functions/urls/abslangurl/ +[`lang.Translate`]: /functions/lang/translate +[`relLangURL`]: /functions/urls/rellangurl/ +[`slug`]: /content-management/urls/#slug +[`time.Format`]: /functions/time/format/ +[`url`]: /content-management/urls/#url +[automatically]: /content-management/menus/#define-automatically +[config]: /configuration/ +[configuration directory]: /configuration/introduction/#configuration-directory +[example menu template]: /templates/menu/#example ++[front matter]: /content-management/menus/#define-in-front-matter +[i18func]: /functions/lang/translate/ - [in front matter]: /content-management/menus/#define-in-front-matter - [in site configuration]: /content-management/menus/#define-in-site-configuration +[lang.FormatAccounting]: /functions/lang/formataccounting/ +[lang.FormatCurrency]: /functions/lang/formatcurrency/ +[lang.FormatNumber]: /functions/lang/formatnumber/ +[lang.FormatNumberCustom]: /functions/lang/formatnumbercustom/ +[lang.FormatPercent]: /functions/lang/formatpercent/ +[lang.Merge]: /functions/lang/merge/ ++[project configuration]: /content-management/menus/#define-in-project-configuration diff --cc docs/content/en/content-management/organization/index.md index e1f6d8acd,000000000..5762e0d4e mode 100644,000000..100644 --- a/docs/content/en/content-management/organization/index.md +++ b/docs/content/en/content-management/organization/index.md @@@ -1,151 -1,0 +1,151 @@@ +--- +title: Content organization +linkTitle: Organization +description: Hugo assumes that the same structure that works to organize your source content is used to organize the rendered site. +categories: [] +keywords: [] +aliases: [/content/sections/] +--- + +## Page bundles + +Hugo supports page-relative images and other resources packaged into `Page Bundles`. + +These terms are connected, and you also need to read about [Page Resources](/content-management/page-resources) and [Image Processing](/content-management/image-processing) to get the full picture. + +```text +content/ +├── blog/ +│ ├── hugo-is-cool/ +│ │ ├── images/ +│ │ │ ├── funnier-cat.jpg +│ │ │ └── funny-cat.jpg +│ │ ├── cats-info.md +│ │ └── index.md +│ ├── posts/ +│ │ ├── post1.md +│ │ └── post2.md +│ ├── 1-landscape.jpg +│ ├── 2-sunset.jpg +│ ├── _index.md +│ ├── content-1.md +│ └── content-2.md +├── 1-logo.png +└── _index.md +``` + +The file tree above shows three bundles. Note that the home page bundle cannot contain other content pages, although other files (images etc.) are allowed. + +## Organization of content source + +In Hugo, your content should be organized in a manner that reflects the rendered website. + +While Hugo supports content nested at any level, the top levels (i.e. `content/`) are special in Hugo and are considered the content type used to determine layouts etc. To read more about sections, including how to nest them, see [sections]. + +Without any additional configuration, the following will automatically work: + +```txt +. +└── content + └── about + | └── index.md // <- https://example.org/about/ + ├── posts + | ├── firstpost.md // <- https://example.org/posts/firstpost/ + | ├── happy + | | └── ness.md // <- https://example.org/posts/happy/ness/ + | └── secondpost.md // <- https://example.org/posts/secondpost/ + └── quote + ├── first.md // <- https://example.org/quote/first/ + └── second.md // <- https://example.org/quote/second/ +``` + +## Path breakdown in Hugo + - The following demonstrates the relationships between your content organization and the output URL structure for your Hugo website when it renders. These examples assume you are [using pretty URLs][pretty], which is the default behavior for Hugo. The examples also assume a key-value of `baseURL = "https://example.org/"` in your [site's configuration file][config]. ++The following demonstrates the relationships between your content organization and the output URL structure for your Hugo website when it renders. These examples assume you are [using pretty URLs][pretty], which is the default behavior for Hugo. The examples also assume a key-value of `baseURL = "https://example.org/"` in your [project configuration][config]. + +### Index pages: `_index.md` + +`_index.md` has a special role in Hugo. It allows you to add front matter and content to `home`, `section`, `taxonomy`, and `term` pages. + +> [!note] +> Access the content and metadata within an `_index.md` file by invoking the `GetPage` method on a `Site` or `Page` object. + +You can create one `_index.md` for your home page and one in each of your content sections, taxonomies, and terms. The following shows typical placement of an `_index.md` that would contain content and front matter for a `posts` section list page on a Hugo website: + +```txt +. url +. ⊢--^-⊣ +. path slug +. ⊢--^-⊣⊢---^---⊣ +. file path +. ⊢------^------⊣ +content/posts/_index.md +``` + +At build, this will output to the following destination with the associated values: + +```txt + + url ("/posts/") + ⊢-^-⊣ + baseurl section ("posts") +⊢--------^---------⊣⊢-^-⊣ + permalink +⊢----------^-------------⊣ +https://example.org/posts/index.html +``` + +The [sections] can be nested as deeply as you want. The important thing to understand is that to make the section tree fully navigational, at least the lower-most section must include a content file. (i.e. `_index.md`). + +### Single pages in sections + +Single content files in each of your sections will be rendered by a [page template]. Here is an example of a single `post` within `posts`: + +```txt + path ("posts/my-first-hugo-post.md") +. ⊢-----------^------------⊣ +. section slug +. ⊢-^-⊣⊢--------^----------⊣ +content/posts/my-first-hugo-post.md +``` + +When Hugo builds your site, the content will be output to the following destination: + +```txt + + url ("/posts/my-first-hugo-post/") + ⊢------------^----------⊣ + baseurl section slug +⊢--------^--------⊣⊢-^--⊣⊢-------^---------⊣ + permalink +⊢--------------------^---------------------⊣ +https://example.org/posts/my-first-hugo-post/index.html +``` + +## Paths explained + +The following concepts provide more insight into the relationship between your project's organization and the default Hugo behavior when building output for the website. + +### `section` + +A default content type is determined by the section in which a content item is stored. `section` is determined by the location within the project's `content` directory. `section` cannot be specified or overridden in front matter. + +### `slug` + +The `slug` is the last segment of the URL path, defined by the file name and optionally overridden by a `slug` value in front matter. See [URL Management](/content-management/urls/#slug) for details. + +### `path` + +A content's `path` is determined by the section's path to the file. The file `path`: + +- Is based on the path to the content's location AND +- Does not include the slug + +### `url` + +The `url` is the entire URL path, defined by the file path and optionally overridden by a `url` value in front matter. See [URL Management](/content-management/urls/#slug) for details. + +[config]: /configuration/ +[pretty]: /content-management/urls/#appearance +[sections]: /content-management/sections/ +[page template]: /templates/types/#page diff --cc docs/content/en/content-management/page-resources.md index c429d8af5,000000000..a915b5f74 mode 100644,000000..100644 --- a/docs/content/en/content-management/page-resources.md +++ b/docs/content/en/content-management/page-resources.md @@@ -1,297 -1,0 +1,297 @@@ +--- +title: Page resources +description: Use page resources to logically associate assets with a page. +categories: [] +keywords: [] +--- + +Page resources are only accessible from [page bundles](/content-management/page-bundles), those directories with `index.md` or +`_index.md` files at their root. Page resources are only available to the +page with which they are bundled. + +In this example, `first-post` is a page bundle with access to 10 page resources including audio, data, documents, images, and video. Although `second-post` is also a page bundle, it has no page resources and is unable to directly access the page resources associated with `first-post`. + +```text +content +└── post + ├── first-post + │ ├── images + │ │ ├── a.jpg + │ │ ├── b.jpg + │ │ └── c.jpg + │ ├── index.md (root of page bundle) + │ ├── latest.html + │ ├── manual.json + │ ├── notice.md + │ ├── office.mp3 + │ ├── pocket.mp4 + │ ├── rating.pdf + │ └── safety.txt + └── second-post + └── index.md (root of page bundle) +``` + +## Examples + +Use any of these methods on a `Page` object to capture page resources: + +- [`Resources.ByType`] +- [`Resources.Get`] +- [`Resources.GetMatch`] +- [`Resources.Match`] + + Once you have captured a resource, use any of the applicable [`Resource`] methods to return a value or perform an action. + +The following examples assume this content structure: + +```text +content/ +└── example/ + ├── data/ + │ └── books.json <-- page resource + ├── images/ + │ ├── a.jpg <-- page resource + │ └── b.jpg <-- page resource + ├── snippets/ + │ └── text.md <-- page resource + └── index.md +``` + +Render a single image, and throw an error if the file does not exist: + +```go-html-template +{{ $path := "images/a.jpg" }} +{{ with .Resources.Get $path }} + +{{ else }} + {{ errorf "Unable to get page resource %q" $path }} +{{ end }} +``` + +Render all images, resized to 300 px wide: + +```go-html-template +{{ range .Resources.ByType "image" }} + {{ with .Resize "300x" }} + + {{ end }} +{{ end }} +``` + +Render the markdown snippet: + +```go-html-template +{{ with .Resources.Get "snippets/text.md" }} + {{ .Content }} +{{ end }} +``` + +List the titles in the data file, and throw an error if the file does not exist. + +```go-html-template +{{ $path := "data/books.json" }} +{{ with .Resources.Get $path }} + {{ with . | transform.Unmarshal }} +

Books:

+
    + {{ range . }} +
  • {{ .title }}
  • + {{ end }} +
+ {{ end }} +{{ else }} + {{ errorf "Unable to get page resource %q" $path }} +{{ end }} +``` + +## Metadata + +The page resources' metadata is managed from the corresponding page's front matter with an array/table parameter named `resources`. You can batch assign values using [wildcards](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). + +> [!note] +> Resources of type `page` get `Title` etc. from their own front matter. + +name +: (`string`) Sets the value returned in `Name`. + +> [!note] +> The methods `Match`, `Get` and `GetMatch` use `Name` to match the resources. + +title +: (`string`) Sets the value returned in `Title` + +params +: (`map`) A map of custom key-value pairs. + +### Resources metadata example + + +{{< code-toggle file=content/example.md fm=true >}} +title: Application +date: 2018-01-25 +resources: + - src: images/sunset.jpg + name: header + - src: documents/photo_specs.pdf + title: Photo Specifications + params: + icon: photo + - src: documents/guide.pdf + title: Instruction Guide + - src: documents/checklist.pdf + title: Document Checklist + - src: documents/payment.docx + title: Proof of Payment + - src: "**.pdf" + name: pdf-file-:counter + params: + icon: pdf + - src: "**.docx" + params: + icon: word +{{}} + + +From the example above: + +- `sunset.jpg` will receive a new `Name` and can now be found with `.GetMatch "header"`. +- `documents/photo_specs.pdf` will get the `photo` icon. +- `documents/checklist.pdf`, `documents/guide.pdf` and `documents/payment.docx` will get `Title` as set by `title`. +- Every `PDF` in the bundle except `documents/photo_specs.pdf` will get the `pdf` icon. +- All `PDF` files will get a new `Name`. The `name` parameter contains a special placeholder [`:counter`](#the-counter-placeholder-in-name-and-title), so the `Name` will be `pdf-file-1`, `pdf-file-2`, `pdf-file-3`. +- Every docx in the bundle will receive the `word` icon. + +> [!note] +> The order matters; only the first set values of the `title`, `name` and `params` keys will be used. Consecutive parameters will be set only for the ones not already set. In the above example, `.Params.icon` is first set to `"photo"` in `src = "documents/photo_specs.pdf"`. So that would not get overridden to `"pdf"` by the later set `src = "**.pdf"` rule. + +### The `:counter` placeholder in `name` and `title` + +The `:counter` is a special placeholder recognized in `name` and `title` parameters `resources`. + +The counter starts at 1 the first time they are used in either `name` or `title`. + +For example, if a bundle has the resources `photo_specs.pdf`, `other_specs.pdf`, `guide.pdf` and `checklist.pdf`, and the front matter has specified the `resources` as: + +{{< code-toggle file=content/inspections/engine/index.md fm=true >}} +title = 'Engine inspections' +[[resources]] + src = "*specs.pdf" + title = "Specification #:counter" +[[resources]] + src = "**.pdf" + name = "pdf-file-:counter" +{{}} + +the `Name` and `Title` will be assigned to the resource files as follows: + +| Resource file | `Name` | `Title` | +|-------------------|-------------------|-----------------------| +| checklist.pdf | `"pdf-file-1.pdf` | `"checklist.pdf"` | +| guide.pdf | `"pdf-file-2.pdf` | `"guide.pdf"` | +| other\_specs.pdf | `"pdf-file-3.pdf` | `"Specification #1"` | +| photo\_specs.pdf | `"pdf-file-4.pdf` | `"Specification #2"` | + +## Multilingual + +By default, with a multilingual single-host site, Hugo does not duplicate shared page resources when building the site. + +> [!note] +> This behavior is limited to Markdown content. Shared page resources for other [content formats] are copied into each language bundle. + - Consider this site configuration: ++Consider this project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true + +[languages.de] +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 1 + +[languages.en] +languageCode = 'en-US' +languageName = 'English' +weight = 2 +{{< /code-toggle >}} + +And this content: + +```text +content/ +└── my-bundle/ + ├── a.jpg <-- shared page resource + ├── b.jpg <-- shared page resource + ├── c.de.jpg + ├── c.en.jpg + ├── index.de.md + └── index.en.md +``` + +With v0.122.0 and earlier, Hugo duplicated the shared page resources, creating copies for each language: + +```text +public/ +├── de/ +│ ├── my-bundle/ +│ │ ├── a.jpg <-- shared page resource +│ │ ├── b.jpg <-- shared page resource +│ │ ├── c.de.jpg +│ │ └── index.html +│ └── index.html +├── en/ +│ ├── my-bundle/ +│ │ ├── a.jpg <-- shared page resource (duplicate) +│ │ ├── b.jpg <-- shared page resource (duplicate) +│ │ ├── c.en.jpg +│ │ └── index.html +│ └── index.html +└── index.html + +``` + +With v0.123.0 and later, Hugo places the shared resources in the page bundle for the default content language: + +```text +public/ +├── de/ +│ ├── my-bundle/ +│ │ ├── a.jpg <-- shared page resource +│ │ ├── b.jpg <-- shared page resource +│ │ ├── c.de.jpg +│ │ └── index.html +│ └── index.html +├── en/ +│ ├── my-bundle/ +│ │ ├── c.en.jpg +│ │ └── index.html +│ └── index.html +└── index.html +``` + +This approach reduces build times, storage requirements, bandwidth consumption, and deployment times, ultimately reducing cost. + +> [!important] +> To resolve Markdown link and image destinations to the correct location, you must use link and image render hooks that capture the page resource with the [`Resources.Get`] method, and then invoke its [`RelPermalink`] method. +> +> In its default configuration, Hugo automatically uses the [embedded link render hook] and the [embedded image render hook] for multilingual single-host sites, specifically when the [duplication of shared page resources] feature is disabled. This is the default behavior for such sites. If custom link or image render hooks are defined by your project, modules, or themes, these will be used instead. +> +> You can also configure Hugo to `always` use the embedded link or image render hook, use it only as a `fallback`, or `never` use it. See [details](/configuration/markup/#renderhookslinkuseembedded). + - Although duplicating shared page resources is inefficient, you can enable this feature in your site configuration if desired: ++Although duplicating shared page resources is inefficient, you can enable this feature in your project configuration if desired: + +{{< code-toggle file=hugo >}} +[markup.goldmark] +duplicateResourceFiles = true +{{< /code-toggle >}} + +[`RelPermalink`]: /methods/resource/relpermalink/ +[`Resource`]: /methods/resource +[`Resources.ByType`]: /methods/page/resources#bytype +[`Resources.Get`]: /methods/page/resources/#get +[`Resources.GetMatch`]: /methods/page/resources#getmatch +[`Resources.Match`]: /methods/page/resources#match +[content formats]: /content-management/formats/ +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[embedded image render hook]: /render-hooks/images/#embedded +[embedded link render hook]: /render-hooks/links/#embedded diff --cc docs/content/en/content-management/shortcodes.md index 59ac4d651,000000000..777364423 mode 100644,000000..100644 --- a/docs/content/en/content-management/shortcodes.md +++ b/docs/content/en/content-management/shortcodes.md @@@ -1,231 -1,0 +1,231 @@@ +--- +title: Shortcodes +description: Use embedded, custom, or inline shortcodes to insert elements such as videos, images, and social media embeds into your content. +categories: [] +keywords: [] +aliases: [/extras/shortcodes/] +--- + +## Introduction + +{{% glossary-term shortcode %}} + +There are three types of shortcodes: embedded, custom, and inline. + +## Embedded + +Hugo's embedded shortcodes are pre-defined templates within the application. Refer to each shortcode's documentation for specific usage instructions and available arguments. + +{{% list-pages-in-section path=/shortcodes %}} + +## Custom + +Create custom shortcodes to simplify and standardize content creation. For example, the following _shortcode_ template generates an audio player using a [global resource](g): + +```go-html-template {file="layouts/_shortcodes/audio.html"} +{{ with resources.Get (.Get "src") }} + +{{ end }} +``` + +Then call the shortcode from within markup: + +```text {file="content/example.md"} +{{}} +``` + +Learn more about creating shortcodes in the [shortcode templates] section. + +## Inline + +An inline shortcode is a _shortcode_ template defined within content. + +Hugo's security model is based on the premise that template and configuration authors are trusted, but content authors are not. This model enables generation of HTML output safe against code injection. + - To conform with this security model, creating _shortcode_ templates within content is disabled by default. If you trust your content authors, you can enable this functionality in your site's configuration: ++To conform with this security model, creating _shortcode_ templates within content is disabled by default. If you trust your content authors, you can enable this functionality in your project configuration: + +{{< code-toggle file=hugo >}} +[security] +enableInlineShortcodes = true +{{< /code-toggle >}} + +For more information see [configure security](/configuration/security). + +The following example demonstrates an inline shortcode, `date.inline`, that accepts a single positional argument: a date/time [layout string]. + +```text {file="content/example.md"} +Today is +{{}} + {{- now | time.Format (.Get 0) -}} +{{}}. + +Today is {{}}. +``` + +In the example above, the inline shortcode is executed twice: once upon definition and again when subsequently called. Hugo renders this to: + +```html +

Today is Jan 30, 2025.

+

Today is Thursday, January 30, 2025

+``` + +Inline shortcodes process their inner content within the same context as regular _shortcode_ templates, allowing you to use any available [shortcode method]. + +> [!note] +> You cannot [nest](#nesting) inline shortcodes. + +Learn more about creating shortcodes in the [shortcode templates] section. + +## Calling + +Shortcode calls involve three syntactical elements: tags, arguments, and notation. + +### Tags + +Some shortcodes expect content between opening and closing tags. For example, the embedded [`details`] shortcode requires an opening and closing tag: + +```text +{{}} +This is a **bold** word. +{{}} +``` + +Some shortcodes do not accept content. For example, the embedded [`instagram`] shortcode requires a single _positional_ argument: + +```text +{{}} +``` + +Some shortcodes optionally accept content. For example, you can call the embedded [`qr`] shortcode with content: + +```text +{{}} +https://gohugo.io +{{}} +``` + +Or use the self-closing syntax with a trailing slash to pass the text as an argument: + +```text +{{}} +``` + +Refer to each shortcode's documentation for specific usage instructions and available arguments. + +### Arguments + +Shortcode arguments can be either _named_ or _positional_. + +Named arguments are passed as case-sensitive key-value pairs, as seen in this example with the embedded [`figure`] shortcode. The `src` argument, for instance, is required. + +```text +{{}} +``` + +Positional arguments, on the other hand, are determined by their position. The embedded `instagram` shortcode, for example, expects the first argument to be the Instagram post ID. + +```text +{{}} +``` + +Shortcode arguments are space-delimited, and arguments with internal spaces must be quoted. + +```text +{{}} +``` + +Shortcodes accept [scalar](g) arguments, one of [string](g), [integer](g), [floating point](g), or [boolean](g). + +```text +{{}} +``` + +You can optionally use multiple lines when providing several arguments to a shortcode for better readability: + +```text +{{}} +``` + +Use a [raw string literal](g) if you need to pass a multiline string: + +```text +{{HTML, +and a new line with a "quoted string".` */>}} +``` + +Shortcodes can accept named arguments, positional arguments, or both, but you must use either named or positional arguments exclusively within a single shortcode call; mixing them is not allowed. + +Refer to each shortcode's documentation for specific usage instructions and available arguments. + +### Notation + +Shortcodes can be called using two different notations, distinguished by their tag delimiters. + +Notation|Example +:--|:-- +Markdown|`{{%/* foo */%}} ## Section 1 {{%/* /foo */%}}` +Standard|`{{}} ## Section 2 {{}}` + +#### Markdown notation + +Hugo processes the shortcode before the page content is rendered by the Markdown renderer. This means, for instance, that Markdown headings inside a Markdown-notation shortcode will be included when invoking the [`TableOfContents`] method on the `Page` object. + +#### Standard notation + +With standard notation, Hugo processes the shortcode separately, merging the output into the page content after Markdown rendering. This means, for instance, that Markdown headings inside a standard-notation shortcode will be excluded when invoking the `TableOfContents` method on the `Page` object. + +By way of example, with this _shortcode_ template: + +```go-html-template {file="layouts/_shortcodes/foo.html"} +{{ .Inner }} +``` + +And this markdown: + +```text {file="content/example.md"} +{{%/* foo */%}} ## Section 1 {{%/* /foo */%}} + +{{}} ## Section 2 {{}} +``` + +Hugo renders this HTML: + +```html +

Section 1

+ +## Section 2 +``` + +In the above, "Section 1" will be included when invoking the `TableOfContents` method, while "Section 2" will not. + +> [!note] +> The shortcode author determines which notation to use. Consult each shortcode's documentation for specific usage instructions and available arguments. + +## Nesting + +Shortcodes (excluding [inline](#inline) shortcodes) can be nested, creating parent-child relationships. For example, a gallery shortcode might contain several image shortcodes: + +```text {file="content/example.md"} +{{}} + {{}} + {{}} + {{}} +{{}} +``` + +The [shortcode templates][nesting] section provides a detailed explanation and examples. + +[`details`]: /shortcodes/details +[`figure`]: /shortcodes/figure +[`instagram`]: /shortcodes/instagram +[`qr`]: /shortcodes/qr +[`TableOfContents`]: /methods/page/tableofcontents/ +[layout string]: /functions/time/format/#layout-string +[nesting]: /templates/shortcode/#nesting +[shortcode method]: /templates/shortcode/#methods +[shortcode templates]: /templates/shortcode/ diff --cc docs/content/en/content-management/summaries.md index 93386eec2,000000000..cd9eaa836 mode 100644,000000..100644 --- a/docs/content/en/content-management/summaries.md +++ b/docs/content/en/content-management/summaries.md @@@ -1,157 -1,0 +1,157 @@@ +--- +title: Content summaries +linkTitle: Summaries +description: Create and render content summaries. +categories: [] +keywords: [] +aliases: [/content/summaries/,/content-management/content-summaries/] +--- + + + + + + +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. + +Review the [comparison table](#comparison) below to understand the characteristics of each summary type. + +## Manual summary + +Use a `` divider to indicate the end of the summary. Hugo will not render the summary divider itself. + +```text {file="content/example.md"} ++++ +title: 'Example' +date: 2024-05-26T09:10:33-07:00 ++++ + +This is the first paragraph. + + + +This is the second paragraph. +``` + +> [!NOTE] +> Place the summary divider on its own line. Do not place it inline with other content. + +Correct placement: + +```text {file="content/example.md"} +--- +title: 'Example' +--- + +This is an example of **strong text** in a sentence. This is another sentence. + + + +This is another paragraph. +``` + +Incorrect placement: + +```text {file="content/example.md"} +--- +title: 'Example' +--- + +This is an example of **strong text** in a sentence. This is another sentence. + +This is another paragraph. +``` + +When using the Emacs Org Mode [content format], use a `# more` divider to indicate the end of the summary. + +[content format]: /content-management/formats/ + +## Front matter summary + +Use front matter to define a summary independent of content. + +```text {file="content/example.md"} ++++ +title: 'Example' +date: 2024-05-26T09:10:33-07:00 +summary: 'This summary is independent of the content.' ++++ + +This is the first paragraph. + +This is the second paragraph. +``` + +## Automatic summary + - If you do not define the summary manually or in front matter, Hugo automatically defines the summary based on the [`summaryLength`] in your site configuration. ++If you do not define the summary manually or in front matter, Hugo automatically defines the summary based on the [`summaryLength`] in your project configuration. + +[`summaryLength`]: /configuration/all/#summarylength + +```text {file="content/example.md"} ++++ +title: 'Example' +date: 2024-05-26T09:10:33-07:00 ++++ + +This is the first paragraph. + +This is the second paragraph. + +This is the third paragraph. +``` + +For example, with a `summaryLength` of 7, the automatic summary will be: + +```html +

This is the first paragraph.

+

This is the second paragraph.

+``` + +> [!warning] +> Automatic `.Summary` may cut block tags (e.g., `blockquote`) in the middle when `summaryLength` is reached, causing the browser to recover the end tag (the end tag will be inserted before the parent's end tag), resulting in unexpected rendering behavior. To avoid this, wrap `.Summary` in a `
`; alternatively, wrap it together with the heading tag using `
`. You can avoid this entirely by using a manual summary. See issue [#14044] for details. + +## Comparison + +Each summary type has different characteristics: + +Type|Precedence|Renders markdown|Renders shortcodes|Wraps single lines with `

` +:--|:-:|:-:|:-:|:-: +Manual|1|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: +Front matter|2|:heavy_check_mark:|:x:|:x: +Automatic|3|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: + +## Rendering + +Render the summary in a template by calling the [`Summary`] method on a `Page` object. + +[`Summary`]: /methods/page/summary + +```go-html-template +{{ range site.RegularPages }} +

{{ .LinkTitle }}

+
+ {{ .Summary }} + {{ if .Truncated }} + More ... + {{ end }} +
+{{ end }} +``` + +## Alternative + +Instead of calling the `Summary` method on a `Page` object, use the [`strings.Truncate`] function for granular control of the summary length. For example: + +[`strings.Truncate`]: /functions/strings/truncate/ + +```go-html-template +{{ range site.RegularPages }} +

{{ .LinkTitle }}

+
+ {{ .Content | strings.Truncate 42 }} +
+{{ end }} +``` + +[#14044]: https://github.com/gohugoio/hugo/issues/14044 diff --cc docs/content/en/content-management/syntax-highlighting.md index 7e87efa49,000000000..57735b0ab mode 100644,000000..100644 --- a/docs/content/en/content-management/syntax-highlighting.md +++ b/docs/content/en/content-management/syntax-highlighting.md @@@ -1,102 -1,0 +1,102 @@@ +--- +title: Syntax highlighting +description: Add syntax highlighting to code examples. +categories: [] +keywords: [highlight] +aliases: [/extras/highlighting/,/extras/highlight/,/tools/syntax-highlighting/] +--- + +Hugo provides several methods to add syntax highlighting to code examples: + +- Use the [`transform.Highlight`] function within your templates +- Use the [`highlight`] shortcode with any [content format](g) +- Use fenced code blocks with the Markdown content format + +[`transform.Highlight`]: /functions/transform/highlight/ +[`highlight`]: /shortcodes/highlight/ + +## Fenced code blocks + +In its default configuration, Hugo highlights code examples within fenced code blocks, following this form: + +````text {file="content/example.md"} +```LANG [OPTIONS] +CODE +``` +```` + +CODE +: The code to highlight. + +LANG +: The language of the code to highlight. Choose from one of the [supported languages]. This value is case-insensitive. + +OPTIONS - : One or more space-separated or comma-separated key-value pairs wrapped in braces. Set default values for each option in your [site configuration]. The key names are case-insensitive. ++: One or more space-separated or comma-separated key-value pairs wrapped in braces. Set default values for each option in your [project configuration]. The key names are case-insensitive. + +[supported languages]: #languages - [site configuration]: /configuration/markup/#highlight ++[project configuration]: /configuration/markup/#highlight + +For example, with this Markdown: + +````text {file="content/example.md"} +```go {linenos=inline hl_lines=[3,"6-8"] style=emacs} +package main + +import "fmt" + +func main() { + for i := 0; i < 3; i++ { + fmt.Println("Value of i:", i) + } +} +``` +```` + +Hugo renders this: + +```go {linenos=inline, hl_lines=[3, "6-8"], style=emacs} +package main + +import "fmt" + +func main() { + for i := 0; i < 3; i++ { + fmt.Println("Value of i:", i) + } +} +``` + +## Options + +{{% include "_common/syntax-highlighting-options.md" %}} + +## Escaping + +When documenting shortcode usage, escape the tag delimiters: + +````text {file="content/example.md"} +```text {linenos=inline} +{{}} + +{{%/*/* shortcode-2 */*/%}} +``` +```` + +Hugo renders this to: + +```text {linenos=inline} +{{}} + +{{%/* shortcode-2 */%}} +``` + +## Languages + +These are the supported languages. Use one of the identifiers, not the language name, when specifying a language for: + +- The [`transform.Highlight`] function +- The [`highlight`] shortcode +- Fenced code blocks + +{{< chroma-lexers >}} diff --cc docs/content/en/content-management/urls.md index 737d23367,000000000..c1b4979e7 mode 100644,000000..100644 --- a/docs/content/en/content-management/urls.md +++ b/docs/content/en/content-management/urls.md @@@ -1,260 -1,0 +1,260 @@@ +--- +title: URL management - description: Control the structure and appearance of URLs through front matter entries and settings in your site configuration. ++description: Control the structure and appearance of URLs through front matter entries and settings in your project configuration. +categories: [] +keywords: [] +aliases: [/extras/permalinks/,/extras/aliases/,/extras/urls/,/doc/redirects/,/doc/alias/,/doc/aliases/] +--- + +## Overview + +By default, when Hugo renders a page, the resulting URL matches the file path within the `content` directory. For example: + +```text +content/posts/post-1.md → https://example.org/posts/post-1/ +``` + - You can change the structure and appearance of URLs with front matter values and site configuration options. ++You can change the structure and appearance of URLs with front matter values and project configuration options. + +## Front matter + +### `slug` + +Set the `slug` in front matter to override the last segment of the path. This front matter field is not applicable to `home`, `section`, `taxonomy`, or `term` pages. + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'My First Post' +slug = 'my-first-post' +{{< /code-toggle >}} + +The resulting URL will be: + +```text +https://example.org/posts/my-first-post/ +``` + +### `url` + +Set the `url` in front matter to override the entire path. Use this with either regular pages or section pages. + +> [!note] +> Hugo does not sanitize the `url` front matter field, allowing you to generate: +> +> - File paths that contain characters reserved by the operating system. For example, file paths on Windows may not contain any of these [reserved characters][]. Hugo throws an error if a file path includes a character reserved by the current operating system. +> - URLs that contain disallowed characters. For example, the less than sign (`<`) is not allowed in a URL. + +If you set both `slug` and `url` in front matter, the `url` value takes precedence. + +#### Include a colon + +{{< new-in 0.136.0 />}} + +If you need to include a colon in the `url` front matter field, escape it with backslash characters. Use one backslash if you wrap the string within single quotes, or use two backslashes if you wrap the string within double quotes. With YAML front matter, use a single backslash if you omit quotation marks. + +For example, with this front matter: + +{{< code-toggle file=content/example.md fm=true >}} +title: Example +url: "my\\:example" +{{< /code-toggle >}} + +The resulting URL will be: + +```text +https://example.org/my:example/ +``` + +As described above, this will fail on Windows because the colon (`:`) is a reserved character. + +#### File extensions + +With this front matter: + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'My First Article' +url = 'articles/my-first-article' +{{< /code-toggle >}} + +The resulting URL will be: + +```text +https://example.org/articles/my-first-article/ +``` + +If you include a file extension: + +{{< code-toggle file=content/posts/post-1.md fm=true >}} +title = 'My First Article' +url = 'articles/my-first-article.html' +{{< /code-toggle >}} + +The resulting URL will be: + +```text +https://example.org/articles/my-first-article.html +``` + +#### Leading slashes + +With monolingual sites, `url` values with or without a leading slash are relative to the [`baseURL`][]. With multilingual sites, `url` values with a leading slash are relative to the `baseURL`, and `url` values without a leading slash are relative to the `baseURL` plus the language prefix. + +Site type|Front matter `url`|Resulting URL +:--|:--|:-- +monolingual|`/about`|`https://example.org/about/` +monolingual|`about`|`https://example.org/about/` +multilingual|`/about`|`https://example.org/about/` +multilingual|`about`|`https://example.org/de/about/` + +#### Permalinks tokens in front matter + +{{< new-in 0.131.0 />}} + +You can also use tokens when setting the `url` value. This is typically used in `cascade` sections: + +{{< code-toggle file=content/foo/bar/_index.md fm=true >}} +title ="Bar" +[[cascade]] + url = "/:sections[last]/:slug" +{{< /code-toggle >}} + +Use any of these tokens: + +{{% include "/_common/permalink-tokens.md" %}} + - ## Site configuration ++## Project configuration + +### Permalinks + +See [configure permalinks](/configuration/permalinks). + +### Appearance + +See [configure ugly URLs](/configuration/ugly-urls/). + +### Post-processing + +Hugo provides two mutually exclusive configuration options to alter URLs _after_ it renders a page. + +#### Canonical URLs + +> [!caution] +> This is a legacy configuration option, superseded by template functions and Markdown render hooks, and will likely be [removed in a future release][]. +{class="!mt-6"} + +If enabled, Hugo performs a search and replace _after_ it renders the page. It searches for site-relative URLs (those with a leading slash) associated with `action`, `href`, `src`, `srcset`, and `url` attributes. It then prepends the `baseURL` to create absolute URLs. + +```html + → + → +``` + +This is an imperfect, brute force approach that can affect content as well as HTML attributes. As noted above, this is a legacy configuration option that will likely be removed in a future release. + +To enable: + +{{< code-toggle file=hugo >}} +canonifyURLs = true +{{< /code-toggle >}} + +#### Relative URLs + +> [!caution] +> Do not enable this option unless you are creating a serverless site, navigable via the file system. +{class="!mt-6"} + +If enabled, Hugo performs a search and replace _after_ it renders the page. It searches for site-relative URLs (those with a leading slash) associated with `action`, `href`, `src`, `srcset`, and `url` attributes. It then transforms the URL to be relative to the current page. + +For example, when rendering `content/posts/post-1`: + +```html + → + → +``` + +This is an imperfect, brute force approach that can affect content as well as HTML attributes. As noted above, do not enable this option unless you are creating a serverless site. + +To enable: + +{{< code-toggle file=hugo >}} +relativeURLs = true +{{< /code-toggle >}} + +## Aliases + +Aliases allow you to redirect old URLs to new URLs. This is essential for preventing broken links and ensuring that existing bookmarks or external links continue to function when you rename or move content. + +### Defining aliases + - To add redirects to a page, list the previous paths in the [`aliases`][aliases_field] field in your front matter. Hugo resolves these to [server-relative](g) paths during the build process, accounting for the [`baseURL`][] and [content dimension](g) prefixes such as language, role, or version. ++To add redirects to a page, list the previous paths in the [`aliases`][aliases_field] field in your front matter. Hugo resolves these to [server-relative](g) paths during the build process, accounting for the [`baseURL`][] and [content dimension](g) prefixes such as language, version, or role. + +{{< code-toggle file=content/examples/example-1.en.md fm=true >}} +title = 'Example 1' +date = 2025-02-02 +aliases = ['/old-url', 'old-name', '../old/path'] +{{< /code-toggle >}} + +As shown in the example above, you can use [site-relative](g) paths or [page-relative](g) paths. Page-relative paths can also include directory traversal. Using the file `content/examples/example-1.en.md` as a reference point, here is how Hugo interprets those different path types: + +Path type|Alias|Server-relative path +:--|:--|:-- +site-relative|`/old-url`|`/en/old-url/` +page-relative|`old-name`|`/en/examples/old-name/` +page-relative|`../old/path`|`/en/old/path/` + +### Redirection methods + +There are two ways to implement aliases depending on your hosting environment and preferences: client-side redirection and server-side redirection. + +> [!note] +> Alias data is only generated for [output formats](g) where both [`isHTML`][] and [`permalinkable`][] are `true`. This affects both the creation of client-side redirect files and the results returned by the [`Aliases`][aliases_method] method used in server-side redirection. + +#### Client-side redirection + +By default, Hugo uses client-side redirection, generating a small HTML file for every alias. This file contains a `meta http-equiv="refresh"` tag that instructs the browser to navigate to the new URL. This approach is portable across all hosting providers. + +When using this method, Hugo creates a physical directory and an `index.html` file at each alias location. For example, if a page at `content/posts/new.md` has a page-relative alias of `old-path`, a file is generated at `public/posts/old-path/index.html`. + +Unless you provide a custom layout, Hugo uses its [embedded alias template][] to generate the redirect files: + +```go-html-template + + + + {{ .Permalink }} + {{ with .OutputFormats.Canonical }}{{ end }} + + + + +``` + +To override this, create a file named `alias.html` in your `layouts` directory. This custom template has access to the following context: + +`Permalink` +: (`string`) The absolute URL of the destination page. + +`Page` +: (`page.Page`) The full `Page` object of the destination. + +#### Server-side redirection + +Alternatively, you can implement server-side redirection by using the [`Aliases`][aliases_method] method on a `Page` object to generate a single configuration file that the web server processes. This method is more efficient because the redirect happens at the HTTP header level before any page content is processed, whereas a meta refresh requires the browser to download and parse the HTML body before acting. Additionally, server-side redirection improves build and deployment times because Hugo doesn't need to write a physical directory and HTML file for every alias. + +To implement this, you typically create a single template to generate the necessary rules for your specific host or server. Common examples include: + +- A `_redirects` file for hosting services such as Cloudflare, GitLab Pages, and Netlify. +- An `.htaccess` file for web servers such as Apache and LiteSpeed. + +See the [`Aliases`][aliases_method] method page for a complete example of how to iterate through pages to generate these rules. + - If you implement server-side redirects, you should disable the generation of individual HTML files by setting [`disableAliases`][] to `true` in your site configuration. This setting only prevents the generation of the physical HTML files; the `Aliases` method on a `Page` object remains available for use in your configuration templates. ++If you implement server-side redirects, you should disable the generation of individual HTML files by setting [`disableAliases`][] to `true` in your project configuration. This setting only prevents the generation of the physical HTML files; the `Aliases` method on a `Page` object remains available for use in your configuration templates. + +[`baseURL`]: /configuration/all/#baseurl +[`disableAliases`]: /configuration/all/#disablealiases +[`isHTML`]: /configuration/output-formats/#ishtml +[`permalinkable`]: /configuration/output-formats/#permalinkable +[aliases_field]: /content-management/front-matter/#aliases +[aliases_method]: /methods/page/aliases/ +[embedded alias template]: <{{% eturl alias %}}> +[removed in a future release]: https://github.com/gohugoio/hugo/issues/4733 +[reserved characters]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions diff --cc docs/content/en/contribute/development.md index 1269c8509,000000000..e19bd304e mode 100644,000000..100644 --- a/docs/content/en/contribute/development.md +++ b/docs/content/en/contribute/development.md @@@ -1,176 -1,0 +1,176 @@@ +--- +title: Development +description: Contribute to the development of Hugo. +categories: [] +keywords: [] +--- + +## Introduction + +You can contribute to the Hugo project by: + +- Answering questions on the [forum] +- Improving the [documentation] +- Monitoring the [issue queue] +- Creating or improving [themes] +- Squashing [bugs] + +Please submit documentation issues and pull requests to the [documentation repository]. + +If you have an idea for an enhancement or new feature, create a new topic on the [forum] in the "Feature" category. This will help you to: + +- Determine if the capability already exists +- Measure interest +- Refine the concept + +If there is sufficient interest, [create a proposal]. Do not submit a pull request until the project lead accepts the proposal. + +For a complete guide to contributing to Hugo, see the [Contribution Guide]. + +## Prerequisites + +To build the extended or extended/deploy edition from source you must: + +1. Install [Git] +1. Install [Go] version 1.24.0 or later +1. Install a C compiler, either [GCC] or [Clang] +1. Update your `PATH` environment variable as described in the [Go documentation] + +> [!note] +> See these [detailed instructions](https://discourse.gohugo.io/t/41370) to install GCC on Windows. + +## GitHub workflow + +> [!note] +> This section assumes that you have a working knowledge of Go, Git and GitHub, and are comfortable working on the command line. + +Use this workflow to create and submit pull requests. + +Step 1 +: Fork the [project repository]. + +Step 2 +: Clone your fork. + +Step 3 +: Create a new branch with a descriptive name that includes the corresponding issue number. + + For a new feature: + + ```sh + git checkout -b feat/implement-some-feature-99999 + ``` + + For a bug fix: + + ```sh + git checkout -b fix/fix-some-bug-99999 + ``` + +Step 4 +: Make changes. + +Step 5 +: Compile and install. + + To compile and install the standard edition: + + ```text + go install + ``` + + To compile and install the extended edition: + + ```text + CGO_ENABLED=1 go install -tags extended + ``` + + To compile and install the extended/deploy edition: + + ```text + CGO_ENABLED=1 go install -tags extended,withdeploy + ``` + +Step 6 +: Test your changes: + + ```text + go test ./... + ``` + +Step 7 +: Commit your changes with a descriptive commit message: + + - Provide a summary on the first line, typically 50 characters or less, followed by a blank line. + - Begin the summary with the name of the package, followed by a colon, a space, and a brief description of the change beginning with a capital letter + - Use imperative present tense + - See the [commit message guidelines] for requirements + - Optionally, provide a detailed description where each line is 72 characters or less, followed by a blank line. + - Add one or more "Fixes" or "Closes" keywords, each on its own line, referencing the [issues] addressed by this change. + + For example: + + ```sh + git commit -m "tpl/strings: Create wrap function + + The strings.Wrap function wraps a string into one or more lines, + splitting the string after the given number of characters, but not + splitting in the middle of a word. + + Fixes #99998 + Closes #99999" + ``` + +Step 8 +: Push the new branch to your fork of the documentation repository. + +Step 9 +: Visit the [project repository] and create a pull request (PR). + +Step 10 +: A project maintainer will review your PR and may request changes. You may delete your branch after the maintainer merges your PR. + +## Building from source + +You can build, install, and test Hugo at any point in its development history. The examples below build and install the extended edition of Hugo. + +To build and install the latest release: + +```sh +CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@latest +``` + +To build and install a specific release: + +```sh - CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@v0.155.3 ++CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@v0.156.0 +``` + +To build and install at the latest commit on the master branch: + +```sh +CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@master +``` + +To build and install at a specific commit: + +```sh +CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@c0d9beb +``` + +[bugs]: https://github.com/gohugoio/hugo/issues?q=is%3Aopen+is%3Aissue+label%3ABug +[Clang]: https://clang.llvm.org/ +[commit message guidelines]: https://github.com/gohugoio/hugo/blob/master/CONTRIBUTING.md#git-commit-message-guidelines +[Contribution Guide]: https://github.com/gohugoio/hugo/blob/master/CONTRIBUTING.md +[create a proposal]: https://github.com/gohugoio/hugo/issues/new?labels=Proposal%2C+NeedsTriage&template=feature_request.md +[documentation]: /documentation +[documentation repository]: https://github.com/gohugoio/hugoDocs +[forum]: https://discourse.gohugo.io +[GCC]: https://gcc.gnu.org/ +[Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[Go]: https://go.dev/doc/install +[Go documentation]: https://go.dev/doc/code#Command +[issue queue]: https://github.com/gohugoio/hugo/issues +[issues]: https://github.com/gohugoio/hugo/issues +[project repository]: https://github.com/gohugoio/hugo/ +[themes]: https://themes.gohugo.io/ diff --cc docs/content/en/contribute/documentation.md index 33f1e8a89,000000000..2d878b020 mode 100644,000000..100644 --- a/docs/content/en/contribute/documentation.md +++ b/docs/content/en/contribute/documentation.md @@@ -1,556 -1,0 +1,556 @@@ +--- +title: Documentation +description: Help us to improve the documentation by identifying issues and suggesting changes. +categories: [] +keywords: [] +aliases: [/contribute/docs/] +--- + +## Introduction + +We welcome corrections and improvements to the documentation. The documentation lives in a separate repository from the main project. To contribute: + +- For corrections and improvements to existing documentation, submit issues and pull requests to the [documentation repository]. +- For documentation of new features, include the documentation changes in your pull request to the [project repository]. + +## Guidelines + +### Style + +Follow Google's [developer documentation style guide]. + +### Markdown + +Adhere to these Markdown conventions: + +- Use [ATX] headings (levels 2-4), not [setext] headings. +- Use [collapsed link references][] instead of full or shortcut references. For example: + + ```text + This is a [link][]. + + [link]: https://example.org + ``` + +- Use [fenced code blocks] instead of [indented code blocks]. +- Use hyphens, not asterisks, for unordered [list items]. +- Use [callouts](#callouts) instead of bold text for emphasis. +- Do not mix [raw HTML] within Markdown. +- Do not use bold text in place of a heading or description term (`dt`). +- Remove consecutive blank lines. +- Remove trailing spaces. + +### Glossary + +[Glossary] terms are defined on individual pages, providing a central repository for definitions, though these pages are not directly linked from the site. + +Definitions must be complete sentences, with the first sentence defining the term. Italicize the first occurrence of the term and any referenced glossary terms for consistency. + +Link to glossary terms using this syntax: `[term](g)` + +Term lookups are case-insensitive, ignore formatting, and support singular and plural forms. For example, all of these variations will link to the same glossary term: + +```text +[global resource](g) +[Global Resource](g) +[Global Resources](g) +[`Global Resources`](g) +``` + +Use the [glossary-term shortcode](#glossary-term) to insert a term definition: + +```text +{{%/* glossary-term "global resource" */%}} +``` + +### Terminology + +Link to the [glossary] as needed and use terms consistently. Pay particular attention to: + +- "front matter" (two words, except when referring to the configuration key) +- "home page" (two words) +- "website" (one word) +- "standalone" (one word, no hyphen) +- "map" (instead of "dictionary") +- "flag" (instead of "option" for command-line flags) +- "client side" (noun), "client-side" (adjective) +- "server side" (noun), "server-side" (adjective) +- "Markdown" (capitalized) +- "open-source" (hyphenated adjective) + +### Template types + +When you refer to a template type, italicize it: + +```text +When creating a _taxonomy_ template, do this... +``` + +However, if the template type is also a link, do not italicize it to avoid distracting formatting: + +```text +When creating a [taxonomy] template, do this... +``` + +Do not italicize the template type in a title, heading, or front matter description. + +### Titles and headings + +- Use sentence-style capitalization. +- Avoid formatted strings. +- Keep them concise. + +### Page descriptions + +When writing the page `description` use imperative present tense when possible. For example: + +{{< code-toggle file=content/en/functions/data/_index.md" fm=true >}} +title: Data functions +linkTitle: data +description: Use these functions to read local or remote data files. +{{< /code-toggle >}} + +### Writing style + +Use active voice and present tense wherever possible. + +No → With Hugo you can build a static site.\ +Yes → Build a static site with Hugo. + +No → This will cause Hugo to generate HTML files in the `public` directory.\ +Yes → Hugo generates HTML files in the `public` directory. + +Use second person instead of third person. + +No → Users should exercise caution when deleting files.\ +Better → You must be cautious when deleting files.\ +Best → Be cautious when deleting files. + +Minimize adverbs. + +No → Hugo is extremely fast.\ +Yes → Hugo is fast. + +> [!note] +> "It's an adverb, Sam. It's a lazy tool of a weak mind." (Outbreak, 1995). + +### Function and method descriptions + +Start descriptions in the functions and methods sections with "Returns", or for boolean values, "Reports whether". + +### File paths and names + +Enclose directory names, file names, and file paths in backticks, except when used in: + +- Page titles +- Section headings (h1-h6) +- Definition list terms +- The `description` field in front matter + +### Miscellaneous + +Other best practices: + +- Introduce lists with a sentence or phrase, not directly under a heading. +- Avoid bold text; use [callouts](#callouts) for emphasis. +- Do not put description terms (`dt`) in backticks unless syntactically necessary. +- Do not use Hugo's `ref` or `relref` shortcodes. +- Prioritize current best practices over multiple options or historical information. +- Use short, focused code examples. +- Use [basic english] where possible for a global audience. + +## Front matter fields + +This site uses the front matter fields listed in the table below. + +Of the four required fields, only `title` and `description` require data. + +```text +title: The title +description: The description +categories: [] +keywords: [] +``` + +This example demonstrates the minimum required front matter fields. + +If quotation marks are required, prefer single quotes to double quotes when possible. + +Field|Description|Required +:--|:--|:-- +`title`|The page title|:heavy_check_mark: +`linkTitle`|A short version of the page title|  +`description`|A complete sentence describing the page|:heavy_check_mark: +`categories`|An array of terms in the categories taxonomy|:heavy_check_mark: [^1] +`keywords`|An array of keywords used to identify related content|:heavy_check_mark: [^1] +`publishDate`|Applicable to news items: the publication date|  +`params.alt_title`|An alternate title: used in the "see also" panel if provided|  +`params.functions_and_methods.aliases`|Applicable to function and method pages: an array of alias names|  +`params.functions_and_methods.returnType`|Applicable to function and method pages: the data type returned|  +`params.functions_and_methods.signatures`|Applicable to function and method pages: an array of signatures|  +`params.hide_in_this_section`|Whether to hide the "in this section" panel|  +`params.minversion`|Applicable to the quick start page: the minimum Hugo version required|  +`params.permalink`|Reserved for use by the news content adapter|  +`params.reference (used in glossary term)`|Applicable to glossary entries: a URL for additional information|  - `params.searchable`|Whether to add the content of this page to the search index. The default value is cascaded down from the site configuration; `true` if the page kind is `page`, and `false` if the page kind is one of `home`, `section`, `taxonomy`, or `term`. Add this field to override the default value.|  ++`params.searchable`|Whether to add the content of this page to the search index. The default value is cascaded down from the project configuration; `true` if the page kind is `page`, and `false` if the page kind is one of `home`, `section`, `taxonomy`, or `term`. Add this field to override the default value.|  +`params.show_publish_date`|Whether to show the `publishDate` when rendering the page|  +`weight`|The page weight|  +`aliases`|Previous URLs used to access this page|  +`expirydate`|The expiration date|  + +[^1]: The field is required, but its data is not. + +## Related content + +When available, the "See also" sidebar displays related pages using Hugo's [related content] feature, based on front matter keywords. We ensure consistent keyword usage by validating them against `data/keywords.yaml` during the build process. If a keyword is not found, you'll be alerted and must either modify the keyword or update the data file. This validation process helps to refine the related content for better results. + +If the title in the "See also" sidebar is ambiguous or the same as another page, you can define an alternate title in the front matter: + +{{< code-toggle file=hugo >}} +title = "Long descriptive title" +linkTitle = "Short title" +[params] +alt_title = "Whatever you want" +{{< /code-toggle >}} + +Use of the alternate title is limited to the "See also" sidebar. + +> [!note] +> Think carefully before setting the `alt_title`. Use it only when absolutely necessary. + +## Code examples + +With examples of template code: + +- Indent with two spaces. +- Insert a space after an opening action delimiter. +- Insert a space before a closing action delimiter. +- Do not add white space removal syntax to action delimiters unless required. For example, inline elements like `img` and `a` require whitespace removal on both sides. + +```go-html-template +{{ if eq $foo $bar }} + {{ fmt.Printf "%s is %s" $foo $bar }} +{{ end }} +``` + +### Fenced code blocks + +Always specify the language. + +When providing a Mardown example, set the code language to "text" to prevent +erroneous lexing/highlighting of shortcode calls. + +````text +```go-html-template +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} +``` +```` + +To include a file name header and copy-to-clipboard button: + +````text +```go-html-template {file="layouts/_partials/foo.html" copy=true} +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} +``` +```` + +To wrap the code block within an initially-opened `details` element using a non-default summary: + +````text +```go-html-template {details=true open=true summary="layouts/_partials/foo.html" copy=true} +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} +``` +```` + +Whitespace trimming is enabled by default. To override this behavior and preserve leading and trailing spaces: + +````text +```go-html-template {trim=false} + +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} + +``` +```` + +### Shortcode calls + +Use this syntax : + +````text +```text +{{}} +{{%/*/* foo */*/%}} +``` +```` + - ### Site configuration ++### Project configuration + - Use the [code-toggle shortcode](#code-toggle) to include site configuration examples: ++Use the [code-toggle shortcode](#code-toggle) to include project configuration examples: + +```text +{{}} +baseURL = 'https://example.org/' +languageCode = 'en-US' +title = 'My Site' +{{}} +``` + +### Front matter + +Use the [code-toggle shortcode](#code-toggle) to include front matter examples: + +```text +{{}} +title = 'My first post' +date = 2023-11-09T12:56:07-08:00 +draft = false +{{}} +``` + +## Callouts + +To visually emphasize important information, use callouts (admonitions). Callout types are case-insensitive. Effective March 8, 2025, we utilize only three of the five available types. + +- note (272 instances) +- warning (2 instances) +- caution (1 instance) + +Limiting the number of callout types helps us to use them consistently. + +```text +> [!note] +> Useful information that users should know, even when skimming content. +``` + +> [!note] +> Useful information that users should know, even when skimming content. + +```text +> [!warning] +> Urgent info that needs immediate user attention to avoid problems. +``` + +> [!warning] +> Urgent info that needs immediate user attention to avoid problems. + +```text +> [!caution] +> Advises about risks or negative outcomes of certain actions. +``` + +> [!caution] +> Advises about risks or negative outcomes of certain actions. + +```text +> [!tip] +> Helpful advice for doing things better or more easily. +``` + +> [!tip] +> Helpful advice for doing things better or more easily. + +```text +> [!important] +> Key information users need to know to achieve their goal. +``` + +> [!important] +> Key information users need to know to achieve their goal. + +## Shortcodes + +These shortcodes are commonly used throughout the documentation. Other shortcodes are available for specialized use. + +### code-toggle + - Use the `code-toggle` shortcode to display examples of site configuration, front matter, or data files. This shortcode takes these arguments: ++Use the `code-toggle` shortcode to display examples of project configuration, front matter, or data files. This shortcode takes these arguments: + +config - : (`string`) The section of `site.Data.docs.config` to render. ++: (`string`) The section of `hugo.Data.docs.config` to render. + +copy +: (`bool`) Whether to display a copy-to-clipboard button. Default is `false`. + +datakey: - : (`string`) The section of `site.Data.docs` to render. ++: (`string`) The section of `hugo.Data.docs` to render. + +file - : (`string`) The file name to display above the rendered code. Omit the file extension for site configuration examples. ++: (`string`) The file name to display above the rendered code. Omit the file extension for project configuration examples. + +fm +: (`bool`) Whether to render the code as front matter. Default is `false`. + +skipHeader - : (`bool`) Whether to omit top-level key(s) when rendering a section of `site.Data.docs.config`. ++: (`bool`) Whether to omit top-level key(s) when rendering a section of `hugo.Data.docs.config`. + +```text +{{}} +baseURL = 'https://example.org/' +languageCode = 'en-US' +title = 'My Site' +{{}} +``` + +### deprecated-in + +Use the `deprecated-in` shortcode to indicate that a feature is deprecated: + +```text +{{}} + +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver/ +{{}} +``` + +### eturl + +Use the embedded template URL (`eturl`) shortcode to insert an absolute URL to the source code for an embedded template. The shortcode takes a single argument, the base file name of the template (omit the file extension). + +```text +This is a link to the [embedded alias template]. + +[embedded alias template]: <{{%/* eturl alias */%}}> +``` + +### glossary-term + +Use the `glossary-term` shortcode to insert the definition of the given glossary term. + +```text +{{%/* glossary-term scalar */%}} +``` + +### include + +Use the `include` shortcode to include content from another page. + +```text +{{%/* include "_common/glob-patterns.md" */%}} +``` + +### new-in + +Use the `new-in` shortcode to indicate a new feature: + +```text +{{}} +``` + +You can also include details: + +```text +{{}} +This is a new feature. +{{}} +``` + +## New features + +Use the [new-in shortcode](#new-in) to indicate a new feature: + +```text +{{}} +``` + +The "new in" label will be hidden if the specified version is older than a predefined threshold, based on differences in major and minor versions. See [details](https://github.com/gohugoio/hugoDocs/blob/master/_vendor/github.com/gohugoio/gohugoioTheme/layouts/_shortcodes/new-in.html). + +## Deprecated features + +Use the [deprecated-in shorcode](#deprecated-in) shortcode to indicate that a feature is deprecated: + +```text +{{}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver/ +{{}} +``` + +When deprecating a function or method, add something like this to front matter: + +{{< code-toggle file=content/something/foo.md fm=true >}} +expiryDate: 2027-02-17 # deprecated 2025-02-17 in v0.144.0 +{{< /code-toggle >}} + +Set the `expiryDate` to two years from the date of deprecation, and add a brief front matter comment to explain the setting. + +## GitHub workflow + +> [!note] +> This section assumes that you have a working knowledge of Git and GitHub, and are comfortable working on the command line. + +Use this workflow to create and submit pull requests. + +Step 1 +: Fork the [documentation repository]. + +Step 2 +: Clone your fork. + +Step 3 +: Create a new branch with a descriptive name that includes the corresponding issue number, if any: + + ```sh + git checkout -b restructure-foo-page-99999 + ``` + +Step 4 +: Make changes. + +Step 5 +: Build the site locally to preview your changes. + +Step 6 +: Commit your changes with a descriptive commit message: + + - Provide a summary on the first line, typically 50 characters or less, followed by a blank line. + - Begin the summary with one of `content`, `theme`, `config`, `all`, or `misc`, followed by a colon, a space, and a brief description of the change beginning with a capital letter + - Use imperative present tense + - Optionally, provide a detailed description where each line is 72 characters or less, followed by a blank line. + - Optionally, add one or more "Fixes" or "Closes" keywords, each on its own line, referencing the [issues] addressed by this change. + + For example: + + ```text + git commit -m "content: Restructure the taxonomy page + + This restructures the taxonomy page by splitting topics into logical + sections, each with one or more examples. + + Fixes #9999 + Closes #9998" + ``` + +Step 7 +: Push the new branch to your fork of the documentation repository. + +Step 8 +: Visit the [documentation repository] and create a pull request (PR). + +Step 9 +: A project maintainer will review your PR and may request changes. You may delete your branch after the maintainer merges your PR. + +[ATX]: https://spec.commonmark.org/current/#atx-headings +[basic english]: https://simple.wikipedia.org/wiki/Basic_English +[collapsed link references]: https://discourse.gohugo.io/t/55714 +[developer documentation style guide]: https://developers.google.com/style +[documentation repository]: https://github.com/gohugoio/hugoDocs/ +[fenced code blocks]: https://spec.commonmark.org/current/#fenced-code-blocks +[glossary]: /quick-reference/glossary/ +[indented code blocks]: https://spec.commonmark.org/current/#indented-code-blocks +[issues]: https://github.com/gohugoio/hugoDocs/issues +[list items]: https://spec.commonmark.org/current/#list-items +[project repository]: https://github.com/gohugoio/hugo +[raw HTML]: https://spec.commonmark.org/current/#raw-html +[related content]: /content-management/related-content/ +[setext]: https://spec.commonmark.org/current/#setext-heading diff --cc docs/content/en/functions/collections/IsSet.md index 405aa92af,000000000..9a37f355c mode 100644,000000..100644 --- a/docs/content/en/functions/collections/IsSet.md +++ b/docs/content/en/functions/collections/IsSet.md @@@ -1,42 -1,0 +1,42 @@@ +--- +title: collections.IsSet +description: Reports whether a specific key or index exists in the given map or slice. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [isset] + returnType: bool + signatures: [collections.IsSet MAP|SLICE KEY|INDEX] +aliases: [/functions/isset] +--- + - For example, consider this site configuration: ++For example, consider this project configuration: + +{{< code-toggle file=hugo >}} +[params] +showHeroImage = false +{{< /code-toggle >}} + +If the value of `showHeroImage` is `true`, we can detect that it exists using either `if` or `with`: + +```go-html-template +{{ if site.Params.showHeroImage }} + {{ site.Params.showHeroImage }} → true +{{ end }} + +{{ with site.Params.showHeroImage }} + {{ . }} → true +{{ end }} +``` + +But if the value of `showHeroImage` is `false`, we can't use either `if` or `with` to detect its existence. In this case, you must use the `isset` function: + +```go-html-template +{{ if isset site.Params "showheroimage" }} +

The showHeroImage parameter is set to {{ site.Params.showHeroImage }}.

+{{ end }} +``` + +> [!note] +> When using the `isset` function you must reference the key using lower case. See the previous example. diff --cc docs/content/en/functions/collections/Querify.md index a91393787,000000000..53a30f094 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Querify.md +++ b/docs/content/en/functions/collections/Querify.md @@@ -1,48 -1,0 +1,48 @@@ +--- +title: collections.Querify +description: Returns a URL query string from the given map, slice, or sequence of key-value pairs. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [querify] + returnType: string + signatures: [collections.Querify MAP|SLICE|KEY VALUE...] +aliases: [/functions/querify] +--- + +Specify the key-value pairs as a map, a slice, or a sequence of scalar values. For example, the following are equivalent: + +```go-html-template +{{ collections.Querify (dict "a" 1 "b" 2) }} +{{ collections.Querify (slice "a" 1 "b" 2) }} +{{ collections.Querify "a" 1 "b" 2 }} +``` + +To append a query string to a URL: + +```go-html-template +{{ $qs := collections.Querify (dict "a" 1 "b" 2) }} +{{ $href := printf "https://example.org?%s" $qs }} + +Link +``` + +Hugo renders this to: + +```html +Link +``` + - You can also pass in a map from your site configuration or front matter. For example: ++You can also pass in a map from your project configuration or front matter. For example: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +[params.query] +a = 1 +b = 2 +{{< /code-toggle >}} + +```go-html-template +{{ collections.Querify .Params.query }} +``` diff --cc docs/content/en/functions/collections/Sort.md index c48610923,000000000..9a9ed4ac1 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Sort.md +++ b/docs/content/en/functions/collections/Sort.md @@@ -1,150 -1,0 +1,150 @@@ +--- +title: collections.Sort +description: Returns a sorted map or slice by reordering the given collection by a key and order. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [sort] + returnType: any + signatures: ['collections.Sort MAP|SLICE [KEY] [ORDER]'] +aliases: [/functions/sort] +--- + +The `KEY` is optional when sorting slices in ascending order, otherwise it is required. When sorting slices, use the literal `value` in place of the `KEY`. See examples below. + +The `ORDER` may be either `asc` (ascending) or `desc` (descending). The default sort order is ascending. + +## Sort a slice + - The examples below assume this site configuration: ++The examples below assume this project configuration: + +{{< code-toggle file=hugo >}} +[params] +grades = ['b','a','c'] +{{< /code-toggle >}} + +### Ascending order {#slice-ascending-order} + +Sort slice elements in ascending order using either of these constructs: + +```go-html-template +{{ sort site.Params.grades }} → [a b c] +{{ sort site.Params.grades "value" "asc" }} → [a b c] +``` + +In the examples above, `value` is the `KEY` representing the value of the slice element. + +### Descending order {#slice-descending-order} + +Sort slice elements in descending order: + +```go-html-template +{{ sort site.Params.grades "value" "desc" }} → [c b a] +``` + +In the example above, `value` is the `KEY` representing the value of the slice element. + +## Sort a map + - The examples below assume this site configuration: ++The examples below assume this project configuration: + +{{< code-toggle file=hugo >}} +[params.authors.a] +firstName = "Marius" +lastName = "Pontmercy" +[params.authors.b] +firstName = "Victor" +lastName = "Hugo" +[params.authors.c] +firstName = "Jean" +lastName = "Valjean" +{{< /code-toggle >}} + +> [!note] +> When sorting maps, the `KEY` argument must be lowercase. + +### Ascending order {#map-ascending-order} + +Sort map objects in ascending order using either of these constructs: + +```go-html-template +{{ range sort site.Params.authors "firstname" }} + {{ .firstName }} +{{ end }} + +{{ range sort site.Params.authors "firstname" "asc" }} + {{ .firstName }} +{{ end }} +``` + +These produce: + +```text +Jean Marius Victor +``` + +### Descending order {#map-descending-order} + +Sort map objects in descending order: + +```go-html-template +{{ range sort site.Params.authors "firstname" "desc" }} + {{ .firstName }} +{{ end }} +``` + +This produces: + +```text +Victor Marius Jean +``` + +### First level key removal + +Hugo removes the first level keys when sorting a map. + +Original map: + +```json +{ + "felix": { + "breed": "malicious", + "type": "cat" + }, + "spot": { + "breed": "boxer", + "type": "dog" + } +} +``` + +After sorting: + +```json +[ + { + "breed": "malicious", + "type": "cat" + }, + { + "breed": "boxer", + "type": "dog" + } +] +``` + +## Sort a page collection + +> [!note] +> Although you can use the `sort` function to sort a page collection, Hugo provides [sorting and grouping methods] as well. + +In this contrived example, sort the site's regular pages by `.Type` in descending order: + +```go-html-template +{{ range sort site.RegularPages "Type" "desc" }} +

{{ .LinkTitle }}

+{{ end }} +``` + +[sorting and grouping methods]: /methods/pages/ diff --cc docs/content/en/functions/collections/Where.md index a08412621,000000000..3123b6a36 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Where.md +++ b/docs/content/en/functions/collections/Where.md @@@ -1,419 -1,0 +1,419 @@@ +--- +title: collections.Where +description: Returns a slice by filtering the given slice based on a key, operator, and value. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [where] + returnType: '[]any' + signatures: ['collections.Where SLICE KEY [OPERATOR] VALUE'] +aliases: [/functions/where] +--- + +The `where` function returns the given slice, removing elements that do not satisfy the comparison condition. The comparison condition is composed of the `KEY`, `OPERATOR`, and `VALUE` arguments: + +```text +collections.Where SLICE KEY [OPERATOR] VALUE + -------------------- + comparison condition +``` + +Hugo will test for equality if you do not provide an `OPERATOR` argument. For example: + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "books" }} - {{ $books := where .Site.Data.books "genres" "suspense" }} ++{{ $books := where hugo.Data.books "genres" "suspense" }} +``` + +## Arguments + +The where function takes three or four arguments. The `OPERATOR` argument is optional. + +SLICE +: (`[]any`) A [page collection](g) or a [slice](g) of [maps](g). + +KEY +: (`string`) The key of the page or map value to compare with `VALUE`. With page collections, commonly used comparison keys are `Section`, `Type`, and `Params`. To compare with a member of the page `Params` map, [chain](g) the subkey as shown below: + + ```go-html-template + {{ $result := where .Site.RegularPages "Params.foo" "bar" }} + ``` + +OPERATOR +: (`string`) The logical comparison [operator](#operators). + +VALUE +: (`any`) The value with which to compare. The values to compare must have comparable data types. For example: + +Comparison|Result +:--|:-- +`"123" "eq" "123"`|`true` +`"123" "eq" 123`|`false` +`false "eq" "false"`|`false` +`false "eq" false`|`true` + +When one or both of the values to compare is a slice, use the `in`, `not in`, or `intersect` operators as described below. + +## Operators + +Use any of the following logical operators: + +`=`, `==`, `eq` +: (`bool`) Reports whether the given field value is equal to `VALUE`. + +`!=`, `<>`, `ne` +: (`bool`) Reports whether the given field value is not equal to `VALUE`. + +`>=`, `ge` +: (`bool`) Reports whether the given field value is greater than or equal to `VALUE`. + +`>`, `gt` +: `true` Reports whether the given field value is greater than `VALUE`. + +`<=`, `le` +: (`bool`) Reports whether the given field value is less than or equal to `VALUE`. + +`<`, `lt` +: (`bool`) Reports whether the given field value is less than `VALUE`. + +`in` +: (`bool`) Reports whether the given field value is a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in). + +`not in` +: (`bool`) Reports whether the given field value is not a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in). + +`intersect` +: (`bool`) Reports whether the given field value (a slice) contains one or more elements in common with `VALUE`. See [details](/functions/collections/intersect). + +`like` +: (`bool`) Reports whether the given field value matches the [regular expression](g) specified in `VALUE`. Use the `like` operator to compare `string` values. The `like` operator returns `false` when comparing other data types to the regular expression. + +> [!note] +> The examples below perform comparisons within a page collection, but the same comparisons are applicable to a slice of maps. + +## String comparison + +Compare the value of the given field to a [`string`](g): + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "eq" "books" }} +{{ $pages := where .Site.RegularPages "Section" "ne" "books" }} +``` + +## Numeric comparison + +Compare the value of the given field to an [`int`](g) or [`float`](g): + +```go-html-template +{{ $books := where site.RegularPages "Section" "eq" "books" }} + +{{ $pages := where $books "Params.price" "eq" 42 }} +{{ $pages := where $books "Params.price" "ne" 42.67 }} +{{ $pages := where $books "Params.price" "ge" 42 }} +{{ $pages := where $books "Params.price" "gt" 42.67 }} +{{ $pages := where $books "Params.price" "le" 42 }} +{{ $pages := where $books "Params.price" "lt" 42.67 }} +``` + +## Boolean comparison + +Compare the value of the given field to a [`bool`](g): + +```go-html-template +{{ $books := where site.RegularPages "Section" "eq" "books" }} + +{{ $pages := where $books "Params.fiction" "eq" true }} +{{ $pages := where $books "Params.fiction" "eq" false }} +{{ $pages := where $books "Params.fiction" "ne" true }} +{{ $pages := where $books "Params.fiction" "ne" false }} +``` + +## Member comparison + +Compare a [`scalar`](g) to a [`slice`](g). + +For example, to return a slice of pages where the `color` page parameter is either "red" or "yellow": + +```go-html-template +{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }} + +{{ $colors := slice "red" "yellow" }} +{{ $pages := where $fruit "Params.color" "in" $colors }} +``` + +To return a slice of pages where the "color" page parameter is neither "red" nor "yellow": + +```go-html-template +{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }} + +{{ $colors := slice "red" "yellow" }} +{{ $pages := where $fruit "Params.color" "not in" $colors }} +``` + +## Intersection comparison + +Compare a `slice` to a `slice`, returning elements with common values. This is frequently used when comparing taxonomy terms. + +For example, to return a slice of pages where any of the terms in the "genres" taxonomy are "suspense" or "romance": + +```go-html-template +{{ $books := where site.RegularPages "Section" "eq" "books" }} + +{{ $genres := slice "suspense" "romance" }} +{{ $pages := where $books "Params.genres" "intersect" $genres }} +``` + +## Regular expression comparison + +To return a slice of pages where the "author" page parameter begins with either "victor" or "Victor": + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.author" "like" `(?i)^victor` }} +``` + +{{% include "/_common/functions/regular-expressions.md" %}} + +> [!note] +> Use the `like` operator to compare string values. Comparing other data types will result in an empty slice. + +## Date comparison + +### Predefined dates + +There are four predefined front matter dates: [`date`], [`publishDate`], [`lastmod`], and [`expiryDate`]. Regardless of the front matter data format (TOML, YAML, or JSON) these are [`time.Time`] values, allowing precise comparisons. + +For example, to return a slice of pages that were created before the current year: + +```go-html-template +{{ $startOfYear := time.AsTime (printf "%d-01-01" now.Year) }} +{{ $pages := where .Site.RegularPages "Date" "lt" $startOfYear }} +``` + +### Custom dates + +With custom front matter dates, the comparison depends on the front matter data format (TOML, YAML, or JSON). + +> [!note] +> Using TOML for pages with custom front matter dates enables precise date comparisons. + +With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. If you quote a TOML date, it is a string. If you do not quote a TOML date value, it is [`time.Time`] value, enabling precise comparisons. + +In the TOML example below, note that the event date is not quoted. + +```text {file="content/events/2024-user-conference.md"} ++++ +title = '2024 User Conference" +eventDate = 2024-04-01 ++++ +``` + +To return a slice of future events: + +```go-html-template +{{ $events := where .Site.RegularPages "Type" "events" }} +{{ $futureEvents := where $events "Params.eventDate" "gt" now }} +``` + +When working with YAML or JSON, or quoted TOML values, custom dates are strings; you cannot compare them with `time.Time` values. String comparisons may be possible if the custom date layout is consistent from one page to the next. To be safe, filter the pages by ranging over the slice: + +```go-html-template +{{ $events := where .Site.RegularPages "Type" "events" }} +{{ $futureEvents := slice }} +{{ range $events }} + {{ if gt (time.AsTime .Params.eventDate) now }} + {{ $futureEvents = $futureEvents | append . }} + {{ end }} +{{ end }} +``` + +## Nil comparison + +To return a slice of pages where the "color" parameter is present in front matter, compare to `nil`: + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }} +``` + +To return a slice of pages where the "color" parameter is not present in front matter, compare to `nil`: + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.color" "eq" nil }} +``` + +In both examples above, note that `nil` is not quoted. + +## Nested comparison + +These are equivalent: + +```go-html-template +{{ $pages := where .Site.RegularPages "Type" "tutorials" }} +{{ $pages = where $pages "Params.level" "eq" "beginner" }} +``` + +```go-html-template +{{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }} +``` + +## Portable section comparison + +Useful for theme authors, avoid hardcoding section names by using the `where` function with the [`MainSections`] method on a `Site` object. + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }} +``` + - With this construct, a theme author can instruct users to specify their main sections in the site configuration: ++With this construct, a theme author can instruct users to specify their main sections in their project configuration: + +{{< code-toggle file=hugo >}} +mainSections = ['blog','galleries'] +{{< /code-toggle >}} + - If `mainSections` is not defined in the site configuration, the `MainSections` method returns a slice with one element---the top-level section with the most pages. ++If `mainSections` is not defined in your project configuration, the `MainSections` method returns a slice with one element---the top-level section with the most pages. + +## Boolean/undefined comparison + +Consider this site content: + +```text +content/ +├── posts/ +│ ├── _index.md +│ ├── post-1.md <-- front matter: exclude = false +│ ├── post-2.md <-- front matter: exclude = true +│ └── post-3.md <-- front matter: exclude not defined +└── _index.md +``` + +The first two pages have an "exclude" field in front matter, but the last page does not. When testing for _equality_, the third page is _excluded_ from the result. When testing for _inequality_, the third page is _included_ in the result. + +### Equality test + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "eq" false }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "eq" true }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +### Inequality test + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "ne" false }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "ne" true }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +To exclude a page with an undefined field from a boolean _inequality_ test: + +1. Create a slice using a boolean comparison +1. Create a slice using a nil comparison +1. Subtract the second slice from the first slice using the [`collections.Complement`] function. + +This template: + +```go-html-template +{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" true }} +{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }} + +``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" false }} +{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }} + +``` + +Is rendered to: + +```html + +``` + +[`collections.Complement`]: /functions/collections/complement/ +[`date`]: /methods/page/date/ +[`lastmod`]: /methods/page/lastmod/ +[`MainSections`]: /methods/site/mainsections/ +[`time.Time`]: https://pkg.go.dev/time#Time diff --cc docs/content/en/functions/css/Sass.md index 407558c80,000000000..4acc706be mode 100644,000000..100644 --- a/docs/content/en/functions/css/Sass.md +++ b/docs/content/en/functions/css/Sass.md @@@ -1,168 -1,0 +1,168 @@@ +--- +title: css.Sass +description: Transpiles Sass to CSS. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [toCSS] + returnType: resource.Resource + signatures: ['css.Sass [OPTIONS] RESOURCE'] +--- + +Transpile Sass to CSS using the LibSass transpiler included in Hugo's extended and extended/deploy editions, or [install Dart Sass](#dart-sass) to use the latest features of the Sass language. + +> [!warning] +> The embedded LibSass transpiler was deprecated in [v0.153.0][] and will be removed in a future release. Use the Dart Sass transpiler instead. + +Sass has two forms of syntax: [SCSS][] and [indented][]. Hugo supports both. + +## Options + +enableSourceMap +: (`bool`) Whether to generate a source map. Default is `false`. + +includePaths +: (`slice`) A slice of paths, relative to the project root, that the transpiler will use when resolving `@use` and `@import` statements. + +outputStyle +: (`string`) The output style of the resulting CSS. With LibSass, one of `nested` (default), `expanded`, `compact`, or `compressed`. With Dart Sass, either `expanded` (default) or `compressed`. + +precision +: (`int`) The precision of floating point math. Applicable to LibSass. Default is `8`. + +silenceDeprecations +: {{< new-in 0.139.0 />}} +: (`slice`) A slice of deprecation IDs to silence. IDs are enclosed in brackets within Dart Sass warning messages (e.g., `import` in `WARN Dart Sass: DEPRECATED [import]`). Applicable to Dart Sass. Default is `false`. + +silenceDependencyDeprecations +: {{< new-in 0.146.0 />}} +: (`bool`) Whether to silence deprecation warnings from dependencies, where a dependency is considered any file transitively imported through a load path. This does not apply to `@warn` or `@debug` rules.Default is `false`. + +sourceMapIncludeSources +: (`bool`) Whether to embed sources in the generated source map. Applicable to Dart Sass. Default is `false`. + +targetPath +: (`string`) The publish path for the transformed resource, relative to the[`publishDir`][]. If unset, the target path defaults to the asset's original path with a `.css` extension. + +transpiler +: (`string`) The transpiler to use, either `libsass` or `dartsass`. Hugo's extended and extended/deploy editions include the LibSass transpiler. To use the Dart Sass transpiler, see the [installation instructions](#dart-sass). Default is `libsass`. + + > [!warning] + > The embedded LibSass transpiler was deprecated in [v0.153.0][] and will be removed in a future release. Use the Dart Sass transpiler instead. + +vars +: (`map`) A map of key-value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/). + + ```scss + // LibSass + @import "hugo:vars"; + + // Dart Sass + @use "hugo:vars" as v; + ``` + + When passing a `vars` map to the `css.Sass` function, Hugo detects common typed CSS values such as `24px` or `#FF0000` using regular expression matching. If necessary, you can bypass automatic type inference by using the [`css.Quoted`][] or [`css.Unquoted`][] function to explicitly indicate a value's type. + +## Example + +```go-html-template {copy=true} +{{ with resources.Get "sass/main.scss" }} + {{ $opts := dict + "enableSourceMap" hugo.IsDevelopment + "outputStyle" (cond hugo.IsDevelopment "expanded" "compressed") + "targetPath" "css/main.css" + "transpiler" "dartsass" + "vars" site.Params.styles + "includePaths" (slice "node_modules/bootstrap/scss") + }} + {{ with . | toCSS $opts }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | fingerprint }} + + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +## Dart Sass + +Hugo's extended and extended/deploy editions include [LibSass][] to transpile Sass to CSS. In 2020, the Sass team deprecated LibSass in favor of [Dart Sass][]. + +Use the latest features of the Sass language by installing Dart Sass in your development and production environments. + +### Installation overview + +Dart Sass is compatible with Hugo v0.114.0 and later. + +If you have been using Embedded Dart Sass[^1] with Hugo v0.113.0 and earlier, uninstall Embedded Dart Sass, then install Dart Sass. If you have installed both, Hugo will use Dart Sass. + +If you install Hugo as a [Snap package][] there is no need to install Dart Sass. The Hugo Snap package includes Dart Sass. + +[^1]: In 2023, the Sass team deprecated Embedded Dart Sass in favor of Dart Sass. + +### Installing in a development environment + +When you install Dart Sass somewhere in your PATH, Hugo will find it. + +OS|Package manager|Site|Installation +:--|:--|:--|:-- +Linux|Homebrew|[brew.sh]|`brew install sass/sass/sass` +Linux|Snap|[snapcraft.io]|`sudo snap install dart-sass` +macOS|Homebrew|[brew.sh]|`brew install sass/sass/sass` +Windows|Chocolatey|[chocolatey.org]|`choco install sass` +Windows|Scoop|[scoop.sh]|`scoop install sass` + +You may also install [prebuilt binaries][] for Linux, macOS, and Windows. You must install the prebuilt binary outside of your project directory and ensure its path is included in your system's PATH environment variable. + +Run `hugo env` to list the active transpilers. + +> [!note] +> If you build Hugo from source and run `mage test -v`, the test will fail if you install Dart Sass as a Snap package. This is due to the Snap package's strict confinement model. + +### Installing in a production environment + +To use Dart Sass with Hugo on a [CI/CD](g) platform, you typically must modify your build workflow to install Dart Sass before the Hugo site build begins. This is because these platforms don't have Dart Sass pre-installed, and Hugo needs it to process your Sass files. + +There's one key exception where you can skip this step: you have committed your `resources` directory to your repository. This is only possible if: + +- You have not changed Hugo's default asset cache location. - - You have not set [`useResourceCacheWhen`][] to never in your sites configuration. ++- You have not set [`useResourceCacheWhen`][] to never in your project configuration. + +By committing the `resources` directory, you're providing the pre-built CSS files directly to your CI/CD platform, so it doesn't need to run the Sass compilation itself. + +For examples of how to install Dart Sass in a production environment, see these hosting guides: + +- [Cloudflare][] +- [GitHub Pages][] +- [GitLab Pages][] +- [Netlify][] +- [Render][] +- [SourceHut][] +- [Vercel][] + +[`css.Quoted`]: /functions/css/quoted/ +[`css.Unquoted`]: /functions/css/unquoted/ +[`publishDir`]: /configuration/all/#publishdir +[`useResourceCacheWhen`]: /configuration/build/#useresourcecachewhen +[brew.sh]: https://brew.sh/ +[chocolatey.org]: https://community.chocolatey.org/packages/sass +[Cloudflare]: /host-and-deploy/host-on-cloudflare/ +[Dart Sass]: https://sass-lang.com/dart-sass/ +[GitHub Pages]: /host-and-deploy/host-on-github-pages/ +[GitLab Pages]: /host-and-deploy/host-on-gitlab-pages/ +[indented]: https://sass-lang.com/documentation/syntax#the-indented-syntax +[LibSass]: https://sass-lang.com/libsass +[Netlify]: /host-and-deploy/host-on-netlify/ +[prebuilt binaries]: https://github.com/sass/dart-sass/releases/latest +[Render]: /host-and-deploy/host-on-render/ +[scoop.sh]: https://scoop.sh/#/apps?q=sass +[SCSS]: https://sass-lang.com/documentation/syntax#scss +[Snap package]: https://snapcraft.io/hugo +[snapcraft.io]: https://snapcraft.io/dart-sass +[SourceHut]: /host-and-deploy/host-on-sourcehut-pages/ +[v0.153.0]: https://github.com/gohugoio/hugo/releases/tag/v0.153.0 +[Vercel]: /host-and-deploy/host-on-vercel/ diff --cc docs/content/en/functions/css/TailwindCSS.md index e8514679b,000000000..f6751a63a mode 100644,000000..100644 --- a/docs/content/en/functions/css/TailwindCSS.md +++ b/docs/content/en/functions/css/TailwindCSS.md @@@ -1,116 -1,0 +1,117 @@@ +--- +title: css.TailwindCSS +description: Processes the given resource with the Tailwind CSS CLI. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: resource.Resource + signatures: ['css.TailwindCSS [OPTIONS] RESOURCE'] +--- + +{{< new-in 0.128.0 />}} + +Use the `css.TailwindCSS` function to process your Tailwind CSS files. This function uses the Tailwind CSS CLI to: + +1. Scan your templates for Tailwind CSS utility class usage. +1. Compile those utility classes into standard CSS. +1. Generate an optimized CSS output file. + +> [!note] +> Use this function with Tailwind CSS v4.0 and later, which require a relatively [modern browser] to render correctly. + +[modern browser]: https://tailwindcss.com/docs/compatibility#browser-support + +## Setup + +Step 1 +: Install the Tailwind CSS CLI v4.0 or later: + + ```sh {copy=true} - npm install --save-dev tailwindcss @tailwindcss/cli ++ npm install --save-dev tailwindcss @tailwindcss/cli @tailwindcss/typography + ``` + + The Tailwind CSS CLI is also available as a [standalone executable]. You must install it outside of your project directory and ensure its path is included in your system's `PATH` environment variable. + + [standalone executable]: https://github.com/tailwindlabs/tailwindcss/releases/latest + +Step 2 - : Add this to your site configuration: ++: Add this to your project configuration: + + {{< code-toggle file=hugo copy=true >}} + [build] + [build.buildStats] + enable = true + [[build.cachebusters]] + source = 'assets/notwatching/hugo_stats\.json' + target = 'css' + [[build.cachebusters]] + source = '(postcss|tailwind)\.config\.js' + target = 'css' + [module] + [[module.mounts]] + source = 'assets' + target = 'assets' + [[module.mounts]] + disableWatch = true + source = 'hugo_stats.json' + target = 'assets/notwatching/hugo_stats.json' + {{< /code-toggle >}} + +Step 3 +: Create a CSS entry file: + + ```css {file="assets/css/main.css" copy=true} + @import "tailwindcss"; ++ @plugin "@tailwindcss/typography"; + @source "hugo_stats.json"; + ``` + + Tailwind CSS respects `.gitignore` files. This means that if `hugo_stats.json` is listed in your `.gitignore` file, Tailwind CSS will ignore it. To make `hugo_stats.json` available to Tailwind CSS you must explicitly source it as shown in the example above. + +Step 4 +: Create a _partial_ template to process the CSS with the Tailwind CSS CLI: + + ```go-html-template {file="layouts/_partials/css.html" copy=true} + {{ with resources.Get "css/main.css" }} + {{ $opts := dict "minify" (not hugo.IsDevelopment) }} + {{ with . | css.TailwindCSS $opts }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | fingerprint }} + + {{ end }} + {{ end }} + {{ end }} + {{ end }} + ``` + +Step 5 +: Call the _partial_ template from your base template, deferring template execution until after all sites and output formats have been rendered: + + ```go-html-template {file="layouts/baseof.html" copy=true} + + ... + {{ with (templates.Defer (dict "key" "global")) }} + {{ partial "css.html" . }} + {{ end }} + ... + + ``` + +## Options + +minify +: (`bool`) Whether to optimize and minify the output. Default is `false`. + +optimize +: (`bool`) Whether to optimize the output without minifying. Default is `false`. + +disableInlineImports +: {{< new-in 0.147.4 />}} +: (`bool`) Whether to disable inlining of `@import` statements. Inlining is performed recursively, but currently once only per file. It is not possible to import the same file in different scopes (root, media query, etc.). Note that this import routine does not care about the CSS specification, so you can have `@import` statements anywhere in the file. Default is `false`. + +skipInlineImportsNotFound +: (`bool`) Whether to allow the build process to continue despite unresolved import statements, preserving the original import declarations. It is important to note that the inline importer does not process URL-based imports or those with media queries, and these will remain unaltered even when this option is disabled. Default is `false`. diff --cc docs/content/en/functions/debug/Dump.md index df846ac3d,000000000..c06a49ad5 mode 100644,000000..100644 --- a/docs/content/en/functions/debug/Dump.md +++ b/docs/content/en/functions/debug/Dump.md @@@ -1,33 -1,0 +1,33 @@@ +--- +title: debug.Dump +description: Returns an object dump as a string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: string + signatures: [debug.Dump VALUE] +--- + +```go-html-template -
{{ debug.Dump site.Data.books }}
++
{{ debug.Dump hugo.Data.books }}
+``` + +```json +[ + { + "author": "Victor Hugo", + "rating": 4, + "title": "The Hunchback of Notre Dame" + }, + { + "author": "Victor Hugo", + "rating": 5, + "title": "Les Misérables" + } +] +``` + +> [!note] +> Output from this function may change from one release to the next. Use for debugging only. diff --cc docs/content/en/functions/debug/Timer.md index 4d4b02650,000000000..d72b79ed2 mode 100644,000000..100644 --- a/docs/content/en/functions/debug/Timer.md +++ b/docs/content/en/functions/debug/Timer.md @@@ -1,35 -1,0 +1,35 @@@ +--- +title: debug.Timer +description: Creates a named timer that reports elapsed time to the console. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: debug.Timer + signatures: [debug.Timer NAME] +--- + +Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottlenecks in templates. + +The timer starts when you instantiate it, and stops when you call its `Stop` method. + +```go-html-template +{{ $t := debug.Timer "TestSqrt" }} +{{ range 2000 }} + {{ $f := math.Sqrt . }} +{{ end }} +{{ $t.Stop }} +``` + +Use the `--logLevel info` command line flag when you build the site. + +```sh - hugo --logLevel info ++hugo build --logLevel info +``` + +The results are displayed in the console at the end of the build. You can have as many timers as you want and if you don't stop them, they will be stopped at the end of build. + +```text +INFO timer: name TestSqrt count 1002 duration 2.496017496s average 2.491035ms median 2.282291ms +``` diff --cc docs/content/en/functions/fmt/Erroridf.md index 97d628bac,000000000..d6af48fd0 mode 100644,000000..100644 --- a/docs/content/en/functions/fmt/Erroridf.md +++ b/docs/content/en/functions/fmt/Erroridf.md @@@ -1,38 -1,0 +1,38 @@@ +--- +title: fmt.Erroridf +description: Log a suppressible ERROR from a template. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [erroridf] + returnType: string + signatures: ['fmt.Erroridf ID FORMAT [INPUT]'] +aliases: [/functions/erroridf] +--- + +{{% include "/_common/functions/fmt/format-string.md" %}} + - The `erroridf` function evaluates the format string, then prints the result to the ERROR log and fails the build. Unlike the [`errorf`] function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreLogs` array in your site configuration. ++The `erroridf` function evaluates the format string, then prints the result to the ERROR log and fails the build. Unlike the [`errorf`] function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreLogs` array in your project configuration. + +This template code: + +```go-html-template +{{ erroridf "error-42" "You should consider fixing this." }} +``` + +Produces this console log: + +```text +ERROR You should consider fixing this. - You can suppress this error by adding the following to your site configuration: ++You can suppress this error by adding the following to your project configuration: +ignoreLogs = ['error-42'] +``` + +To suppress this message: + +{{< code-toggle file=hugo >}} +ignoreLogs = ["error-42"] +{{< /code-toggle >}} + +[`errorf`]: /functions/fmt/errorf/ diff --cc docs/content/en/functions/fmt/Warnidf.md index 7b68cd88b,000000000..21fee2993 mode 100644,000000..100644 --- a/docs/content/en/functions/fmt/Warnidf.md +++ b/docs/content/en/functions/fmt/Warnidf.md @@@ -1,38 -1,0 +1,38 @@@ +--- +title: fmt.Warnidf +description: Log a suppressible WARNING from a template. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [warnidf] + returnType: string + signatures: ['fmt.Warnidf ID FORMAT [INPUT]'] +aliases: [/functions/warnidf] +--- + +{{% include "/_common/functions/fmt/format-string.md" %}} + - The `warnidf` function evaluates the format string, then prints the result to the WARNING log. Unlike the [`warnf`] function, you may suppress warnings logged by the `warnidf` function by adding the message ID to the `ignoreLogs` array in your site configuration. ++The `warnidf` function evaluates the format string, then prints the result to the WARNING log. Unlike the [`warnf`] function, you may suppress warnings logged by the `warnidf` function by adding the message ID to the `ignoreLogs` array in your project configuration. + +This template code: + +```go-html-template +{{ warnidf "warning-42" "You should consider fixing this." }} +``` + +Produces this console log: + +```text +WARN You should consider fixing this. - You can suppress this warning by adding the following to your site configuration: ++You can suppress this warning by adding the following to your project configuration: +ignoreLogs = ['warning-42'] +``` + +To suppress this message: + +{{< code-toggle file=hugo >}} +ignoreLogs = ["warning-42"] +{{< /code-toggle >}} + +[`warnf`]: /functions/fmt/warnf/ diff --cc docs/content/en/functions/hugo/Data.md index 000000000,000000000..b8f8dbddf new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/hugo/Data.md @@@ -1,0 -1,0 +1,105 @@@ ++--- ++title: hugo.Data ++description: Returns a data structure composed from the files in the data directory. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ returnType: map ++ signatures: [hugo.Data] ++--- ++ ++{{< new-in 0.156.0 />}} ++ ++Use the `hugo.Data` function 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 := hugo.Data.books }} ++

{{ $category | title }}

++
    ++ {{ range $books }} ++
  • {{ .title }} ({{ .isbn }})
  • ++ {{ end }} ++
++{{ end }} ++``` ++ ++Hugo renders this to: ++ ++```html ++

Fiction

++
    ++
  • The Hunchback of Notre Dame (978-0140443530)
  • ++
  • Les Misérables (978-0451419439)
  • ++
++

Nonfiction

++
    ++
  • The Ancien Régime and the Revolution (978-0141441641)
  • ++
  • Interpreting the French Revolution (978-0521280495)
  • ++
++``` ++ ++To limit the listing to fiction, and sort by title: ++ ++```go-html-template ++
    ++ {{ range sort hugo.Data.books.fiction "title" }} ++
  • {{ .title }} ({{ .author }})
  • ++ {{ end }} ++
++``` ++ ++To find a fiction book by ISBN: ++ ++```go-html-template ++{{ range where hugo.Data.books.fiction "isbn" "978-0140443530" }} ++
  • {{ .title }} ({{ .author }})
  • ++{{ 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 hugo.Data.books "historical-fiction" }} ++``` ++ ++[`index`]: /functions/collections/indexfunction/ ++[`transform.Unmarshal`]: /functions/transform/unmarshal/ ++[mounted]: /configuration/module/#mounts diff --cc docs/content/en/functions/hugo/Environment.md index 551306255,000000000..6f69dd3a6 mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/Environment.md +++ b/docs/content/en/functions/hugo/Environment.md @@@ -1,26 -1,0 +1,26 @@@ +--- +title: hugo.Environment +description: Returns the current running environment. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: string + signatures: [hugo.Environment] +--- + +The `hugo.Environment` function returns the current running [environment](g) as defined through the `--environment` command line flag. + +```go-html-template +{{ hugo.Environment }} → production +``` + +Command line examples: + +Command|Environment +:--|:-- - `hugo`|`production` - `hugo --environment staging`|`staging` ++`hugo build`|`production` ++`hugo build --environment staging`|`staging` +`hugo server`|`development` +`hugo server --environment staging`|`staging` diff --cc docs/content/en/functions/hugo/Generator.md index de3b5d46a,000000000..a090152a3 mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/Generator.md +++ b/docs/content/en/functions/hugo/Generator.md @@@ -1,15 -1,0 +1,15 @@@ +--- +title: hugo.Generator +description: Renders an HTML meta element identifying the software that generated the site. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: template.HTML + signatures: [hugo.Generator] +--- + +```go-html-template - {{ hugo.Generator }} → ++{{ hugo.Generator }} → +``` diff --cc docs/content/en/functions/hugo/IsMultihost.md index a84ae4940,000000000..5820c8056 mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/IsMultihost.md +++ b/docs/content/en/functions/hugo/IsMultihost.md @@@ -1,37 -1,0 +1,37 @@@ +--- +title: hugo.IsMultihost +description: Reports whether each configured language has a unique base URL. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: bool + signatures: [hugo.IsMultihost] +--- + - Site configuration: ++Project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true +[languages] + [languages.de] + baseURL = 'https://de.example.org/' + languageCode = 'de-DE' + languageName = 'Deutsch' + title = 'Projekt Dokumentation' + weight = 1 + [languages.en] + baseURL = 'https://en.example.org/' + languageCode = 'en-US' + languageName = 'English' + title = 'Project Documentation' + weight = 2 +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ hugo.IsMultihost }} → true +``` diff --cc docs/content/en/functions/hugo/IsMultilingual.md index d8c73f7d5,000000000..30a65909a mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/IsMultilingual.md +++ b/docs/content/en/functions/hugo/IsMultilingual.md @@@ -1,35 -1,0 +1,35 @@@ +--- +title: hugo.IsMultilingual +description: Reports whether there are two or more configured languages. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: bool + signatures: [hugo.IsMultilingual] +--- + - Site configuration: ++Project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true +[languages] + [languages.de] + languageCode = 'de-DE' + languageName = 'Deutsch' + title = 'Projekt Dokumentation' + weight = 1 + [languages.en] + languageCode = 'en-US' + languageName = 'English' + title = 'Project Documentation' + weight = 2 +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ hugo.IsMultilingual }} → true +``` diff --cc docs/content/en/functions/hugo/Sites.md index 000000000,000000000..10a8e147e new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/hugo/Sites.md @@@ -1,0 -1,0 +1,82 @@@ ++--- ++title: hugo.Sites ++description: Returns a collection of all sites for all dimensions. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ aliases: [] ++ returnType: page.Sites ++ signatures: [hugo.Sites] ++--- ++ ++{{< new-in 0.156.0 />}} ++ ++{{% include "/_common/functions/hugo/sites-collection.md" %}} ++ ++With this project configuration: ++ ++{{< code-toggle file=hugo >}} ++defaultContentLanguage = 'de' ++defaultContentLanguageInSubdir = true ++defaultContentVersionInSubdir = true ++ ++[languages.de] ++contentDir = 'content/de' ++languageCode = 'de-DE' ++languageDirection = 'ltr' ++languageName = 'Deutsch' ++title = 'Projekt Dokumentation' ++weight = 1 ++ ++[languages.en] ++contentDir = 'content/en' ++languageCode = 'en-US' ++languageDirection = 'ltr' ++languageName = 'English' ++title = 'Project Documentation' ++weight = 2 ++ ++[versions.'v1.0.0'] ++[versions.'v2.0.0'] ++[versions.'v3.0.0'] ++{{< /code-toggle >}} ++ ++This template: ++ ++```go-html-template ++ ++``` ++ ++Produces a list of links to each home page: ++ ++```html ++ ++``` ++ ++To render a link to the home page of the [default site](g): ++ ++```go-html-template ++{{ with hugo.Sites.Default }} ++ {{ .Title }} ++{{ end }} ++``` ++ ++This is equivalent to: ++ ++```go-html-template ++{{ with index hugo.Sites 0 }} ++ {{ .Title }} ++{{ end }} ++``` diff --cc docs/content/en/functions/hugo/Version.md index 380b21eba,000000000..a8ba059c7 mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/Version.md +++ b/docs/content/en/functions/hugo/Version.md @@@ -1,15 -1,0 +1,15 @@@ +--- +title: hugo.Version +description: Returns the current version of the Hugo binary. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: hugo.VersionString + signatures: [hugo.Version] +--- + +```go-html-template - {{ hugo.Version }} → 0.155.3 ++{{ hugo.Version }} → 0.156.0 +``` diff --cc docs/content/en/functions/images/Mask.md index 4f3b4aa3f,000000000..ecc489d8a mode 100644,000000..100644 --- a/docs/content/en/functions/images/Mask.md +++ b/docs/content/en/functions/images/Mask.md @@@ -1,75 -1,0 +1,75 @@@ +--- +title: images.Mask +description: Returns an image filter that applies a mask to the source image. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: images.filter + signatures: [images.Mask RESOURCE] +--- + +{{< new-in 0.141.0 />}} + +The `images.Mask` filter applies a mask to an image. Black pixels in the mask make the corresponding areas of the base image transparent, while white pixels keep them opaque. Color images are converted to grayscale for masking purposes. The mask is automatically resized to match the dimensions of the base image. + +> [!note] +> Of the formats supported by Hugo's imaging pipeline, only PNG and WebP have an alpha channel to support transparency. If your source image has a different format and you require transparent masked areas, convert it to either PNG or WebP as shown in the example below. + - When applying a mask to a non-transparent image format such as JPEG, the masked areas will be filled with the color specified by the `bgColor` parameter in your [site configuration]. You can override that color with a `Process` image filter: ++When applying a mask to a non-transparent image format such as JPEG, the masked areas will be filled with the color specified by the `bgColor` parameter in your [project configuration]. You can override that color with a `Process` image filter: + +```go-html-template +{{ $filter := images.Process "#00ff00" }} +``` + +## Usage + +Create a slice of filters, one for WebP conversion and the other for mask application: + +```go-html-template +{{ $filter1 := images.Process "webp" }} +{{ $filter2 := images.Mask (resources.Get "images/mask.png") }} +{{ $filters := slice $filter1 $filter2 }} +``` + +Apply the filters using the [`images.Filter`] function: + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with . | images.Filter $filters }} + + {{ end }} +{{ end }} +``` + +You can also apply the filter using the [`Filter`] method on a 'Resource' object: + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ with .Filter $filters }} + + {{ end }} +{{ end }} +``` + +## Example + +Mask + +{{< img + src="images/examples/mask.png" + example=false +>}} + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="mask" + filterArgs="images/examples/mask.png" + example=true +>}} + +[`Filter`]: /methods/resource/filter/ +[`images.Filter`]: /functions/images/filter/ - [site configuration]: /configuration/imaging/ ++[project configuration]: /configuration/imaging/ diff --cc docs/content/en/functions/js/Babel.md index 488c80503,000000000..2d76b6718 mode 100644,000000..100644 --- a/docs/content/en/functions/js/Babel.md +++ b/docs/content/en/functions/js/Babel.md @@@ -1,96 -1,0 +1,96 @@@ +--- +title: js.Babel +description: Compile the given JavaScript resource with Babel. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [babel] + returnType: resource.Resource + signatures: ['js.Babel [OPTIONS] RESOURCE'] +--- + +```go-html-template +{{ with resources.Get "js/main.js" }} + {{ $opts := dict + "minified" hugo.IsProduction + "noComments" hugo.IsProduction + "sourceMap" (cond hugo.IsProduction "none" "external") + }} + {{ with . | js.Babel $opts }} + {{ if hugo.IsProduction }} + {{ with . | fingerprint }} + + {{ end }} + {{ else }} + + {{ end }} + {{ end }} +{{ end }} +``` + +## Setup + +Step 1 +: Install [Node.js](https://nodejs.org/en/download) + +Step 2 +: Install the required Node.js packages in the root of your project. + + ```sh + npm install --save-dev @babel/core @babel/cli + ``` + +Step 3 - : Add the babel executable to Hugo's `security.exec.allow` list in your site configuration: ++: Add the babel executable to Hugo's `security.exec.allow` list in your project configuration: + + {{< code-toggle file=hugo >}} + [security.exec] + allow = ['^(dart-)?sass(-embedded)?$', '^go$', '^npx$', '^postcss$', '^babel$'] + {{< /code-toggle >}} + +## Configuration + +We add the main project's `node_modules` to `NODE_PATH` when running Babel and similar tools. There are some known [issues](https://github.com/babel/babel/issues/5618) with Babel in this area, so if you have a `babel.config.js` living in a Hugo Module (and not in the project itself), we recommend using `require` to load the presets/plugins, e.g.: + +```js +module.exports = { + presets: [ + [ + require("@babel/preset-env"), + { + useBuiltIns: "entry", + corejs: 3, + }, + ], + ], +}; +``` + +## Options + +compact +: (`bool`) Whether to remove optional newlines and whitespace. Enabled when `minified` is `true`. Default is `false` + +config +: (`string`) Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` file in the root of your project. See [details](https://babeljs.io/docs/en/configuration). + +minified +: (`bool`) Whether to minify the compiled code. Enables the `compact` option. Default is `false`. + +noBabelrc +: (`string`) Whether to ignore `.babelrc` and `.babelignore` files. Default is `false`. + +noComments +: (`bool`) Whether to remove comments. Default is `false`. + +sourceMap +: (`string`) Whether to generate source maps, one of `external`, `inline`, or `none`. Default is `none`. + +verbose +: (`bool`) Whether to enable verbose logging. Default is `false` + + diff --cc docs/content/en/functions/js/Build.md index 79c52087d,000000000..d81ef2db3 mode 100644,000000..100644 --- a/docs/content/en/functions/js/Build.md +++ b/docs/content/en/functions/js/Build.md @@@ -1,122 -1,0 +1,122 @@@ +--- +title: js.Build +description: Bundle, transpile, tree shake, and minify JavaScript resources. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: resource.Resource + signatures: ['js.Build [OPTIONS] RESOURCE'] +--- + +The `js.Build` function uses the [evanw/esbuild] package to: + +- Bundle +- Transpile (TypeScript and JSX) +- Tree shake +- Minify +- Create source maps + +```go-html-template +{{ with resources.Get "js/main.js" }} + {{$opts := dict + "minify" (not hugo.IsDevelopment) + "sourceMap" (cond hugo.IsDevelopment "external" "") + "targetPath" "js/main.js" + }} + {{ with . | js.Build $opts }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | fingerprint }} + + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +## Options + +targetPath +: (`string`) If not set, the source path will be used as the base target path. Note that the target path's extension may change if the target MIME type is different, e.g. when the source is TypeScript. + +format +: (`string`) The output format. One of: `iife`, `cjs`, `esm`. Default is `iife`, a self-executing function, suitable for inclusion as a ` +``` + +[evanw/esbuild]: https://github.com/evanw/esbuild diff --cc docs/content/en/functions/lang/Translate.md index 29406bd1b,000000000..b73a760e1 mode 100644,000000..100644 --- a/docs/content/en/functions/lang/Translate.md +++ b/docs/content/en/functions/lang/Translate.md @@@ -1,247 -1,0 +1,247 @@@ +--- +title: lang.Translate +description: Translates a string using the translation tables in the i18n directory. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [T, i18n] + returnType: string + signatures: ['lang.Translate KEY [CONTEXT]'] +aliases: [/functions/i18n] +--- + +The `lang.Translate` function returns the value associated with given key as defined in the translation table for the current language. + +If the key is not found in the translation table for the current language, the `lang.Translate` function falls back to the translation table for the [`defaultContentLanguage`][]. + +If the key is not found in the translation table for the `defaultContentLanguage`, the `lang.Translate` function returns an empty string. + +> [!note] - > To list missing and fallback translations, set [`printI18nWarnings`][] to `true` in your site configuration, or use the `--printI18nWarnings` flag when building your site. ++> To list missing and fallback translations, set [`printI18nWarnings`][] to `true` in your project configuration, or use the `--printI18nWarnings` flag when building your project. +> - > To render placeholders for missing and fallback translations, set [`enableMissingTranslationPlaceholders`][] to `true` in your site configuration. ++> To render placeholders for missing and fallback translations, set [`enableMissingTranslationPlaceholders`][] to `true` in your project configuration. + +## Translation tables + +Create translation tables in the `i18n` directory, naming each file according to [RFC 5646][]. Translation tables may be JSON, TOML, or YAML. For example: + +```text +i18n/en.toml +i18n/pt-BR.toml +``` + - The base name must match the [`languageCode`][] or [language key][] as defined in your site configuration. Hugo selects the translation table based on the `languageCode`, falling back to the language key if a matching translation table does not exist. ++The base name must match the [`languageCode`][] or [language key][] as defined in your project configuration. Hugo selects the translation table based on the `languageCode`, falling back to the language key if a matching translation table does not exist. + +Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7][] are also supported. You may omit the `art-x-` prefix for brevity. For example: + +```text +i18n/art-x-hugolang.toml +i18n/hugolang.toml +``` + +> [!note] +> Private use subtags must not exceed 8 alphanumeric characters. + +## Simple translations + +Let's say your multilingual site supports two languages, English and Polish. Create a translation table for each language in the `i18n` directory. + +```text +i18n/ +├── en.toml +└── pl.toml +``` + +The English translation table: + +{{< code-toggle file=i18n/en >}} +privacy = 'privacy' +security = 'security' +{{< /code-toggle >}} + +The Polish translation table: + +{{< code-toggle file=i18n/pl >}} +privacy = 'prywatność' +security = 'bezpieczeństwo' +{{< /code-toggle >}} + +> [!note] +> The examples below use the `T` alias for brevity. + +When viewing the English language site: + +```go-html-template +{{ T "privacy" }} → privacy +{{ T "security" }} → security +```` + +When viewing the Polish language site: + +```go-html-template +{{ T "privacy" }} → prywatność +{{ T "security" }} → bezpieczeństwo +``` + +## Translations with pluralization + +Let's say your multilingual site supports two languages, English and Polish. Create a translation table for each language in the `i18n` directory. + +```text +i18n/ +├── en.toml +└── pl.toml +``` + +The Unicode [CLDR Plural Rules chart][CLDR] describes the pluralization categories for each language. + +The English translation table: + +{{< code-toggle file=i18n/en >}} +[day] +one = 'day' +other = 'days' + +[day_with_count] +one = '{{ . }} day' +other = '{{ . }} days' +{{< /code-toggle >}} + +The Polish translation table: + +{{< code-toggle file=i18n/pl >}} +[day] +one = 'miesiąc' +few = 'miesiące' +many = 'miesięcy' +other = 'miesiąca' + +[day_with_count] +one = '{{ . }} miesiąc' +few = '{{ . }} miesiące' +many = '{{ . }} miesięcy' +other = '{{ . }} miesiąca' +{{< /code-toggle >}} + +> [!note] +> The examples below use the `T` alias for brevity. + +When viewing the English language site: + +```go-html-template +{{ T "day" 0 }} → days +{{ T "day" 1 }} → day +{{ T "day" 2 }} → days +{{ T "day" 5 }} → days + +{{ T "day_with_count" 0 }} → 0 days +{{ T "day_with_count" 1 }} → 1 day +{{ T "day_with_count" 2 }} → 2 days +{{ T "day_with_count" 5 }} → 5 days +```` + +When viewing the Polish language site: + +```go-html-template +{{ T "day" 0 }} → miesięcy +{{ T "day" 1 }} → miesiąc +{{ T "day" 2 }} → miesiące +{{ T "day" 5 }} → miesięcy + +{{ T "day_with_count" 0 }} → 0 miesięcy +{{ T "day_with_count" 1 }} → 1 miesiąc +{{ T "day_with_count" 2 }} → 2 miesiące +{{ T "day_with_count" 5 }} → 5 miesięcy +``` + +In the pluralization examples above, we passed an integer in context (the second argument). You can also pass a map in context, providing a `count` key to control pluralization. + +Translation table: + +{{< code-toggle file=i18n/en >}} +[age] +one = '{{ .name }} is {{ .count }} year old.' +other = '{{ .name }} is {{ .count }} years old.' +{{< /code-toggle >}} + +Template code: + +```go-html-template +{{ T "age" (dict "name" "Will" "count" 1) }} → Will is 1 year old. +{{ T "age" (dict "name" "John" "count" 3) }} → John is 3 years old. +``` + +> [!note] +> Translation tables may contain both simple translations and translations with pluralization. + +## Reserved keys + +Hugo uses the [go-i18n][] package to look up values in translation tables. This package reserves the following keys for internal use: + +id +: (`string`) Uniquely identifies the message. + +description +: (`string`) Describes the message to give additional context to translators that may be relevant for translation. + +hash +: (`string`) Uniquely identifies the content of the message that this message was translated from. + +leftdelim +: (`string`) The left Go template delimiter. + +rightdelim +: (`string`) The right Go template delimiter. + +zero +: (`string`) The content of the message for the [CLDR][] plural form "zero". + +one +: (`string`) The content of the message for the [CLDR][] plural form "one". + +two +: (`string`) The content of the message for the [CLDR][] plural form "two". + +few +: (`string`) The content of the message for the [CLDR][] plural form "few". + +many +: (`string`) The content of the message for the [CLDR][] plural form "many". + +other +: (`string`) The content of the message for the [CLDR][] plural form "other". + +If you need to provide a translation for one of the reserved keys, you can prepend the word with an underscore. For example: + +{{< code-toggle file=i18n/es >}} +_description = 'descripción' +_few = 'pocos' +_many = 'muchos' +_one = 'uno' +_other = 'otro' +_two = 'dos' +_zero = 'cero' +{{< /code-toggle >}} + +Then in your templates: + +```go-html-template +{{ T "_description" }} → descripción +{{ T "_few" }} → pocos +{{ T "_many" }} → muchos +{{ T "_one" }} → uno +{{ T "_two" }} → dos +{{ T "_zero" }} → cero +{{ T "_other" }} → otro +``` + +[`defaultContentLanguage`]: /configuration/all/#defaultcontentlanguage +[`enableMissingTranslationPlaceholders`]: /configuration/all/#enablemissingtranslationplaceholders +[`languageCode`]: /configuration/languages/#languagecode +[`printI18nWarnings`]: /configuration/all/#printi18nwarnings +[CLDR]: https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html +[go-i18n]: https://github.com/nicksnyder/go-i18n +[language key]: /configuration/languages/#language-keys +[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7 +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 diff --cc docs/content/en/functions/os/Getenv.md index 04215e6c3,000000000..d9e6e08fe mode 100644,000000..100644 --- a/docs/content/en/functions/os/Getenv.md +++ b/docs/content/en/functions/os/Getenv.md @@@ -1,54 -1,0 +1,54 @@@ +--- +title: os.Getenv +description: Returns the value of an environment variable, or an empty string if the environment variable is not set. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [getenv] + returnType: string + signatures: [os.Getenv VARIABLE] +aliases: [/functions/getenv] +--- + +## Security + +By default, when using the `os.Getenv` function Hugo allows access to: + +- The `CI` environment variable +- Any environment variable beginning with `HUGO_` + - To access other environment variables, adjust your site configuration. For example, to allow access to the `HOME` and `USER` environment variables: ++To access other environment variables, adjust your project configuration. For example, to allow access to the `HOME` and `USER` environment variables: + +{{< code-toggle file=hugo >}} +[security.funcs] +getenv = ['^HUGO_', '^CI$', '^USER$', '^HOME$'] +{{< /code-toggle >}} + +For more information see [configure security](/configuration/security). + +## Examples + +```go-html-template +{{ getenv "HOME" }} → /home/victor +{{ getenv "USER" }} → victor +``` + - You can pass values when building your site: ++You can pass values when building your project: + +```sh +MY_VAR1=foo MY_VAR2=bar hugo + +OR + +export MY_VAR1=foo +export MY_VAR2=bar +hugo +``` + +And then retrieve the values within a template: + +```go-html-template +{{ getenv "MY_VAR1" }} → foo +{{ getenv "MY_VAR2" }} → bar +``` diff --cc docs/content/en/functions/resources/ExecuteAsTemplate.md index bff83832e,000000000..2ffb9dff7 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/ExecuteAsTemplate.md +++ b/docs/content/en/functions/resources/ExecuteAsTemplate.md @@@ -1,61 -1,0 +1,61 @@@ +--- +title: resources.ExecuteAsTemplate +description: Returns a resource created from a Go template, parsed and executed with the given context. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: resource.Resource + signatures: [resources.ExecuteAsTemplate TARGETPATH CONTEXT RESOURCE] +--- + +The `resources.ExecuteAsTemplate` function returns a resource created from a Go template, parsed and executed with the given context, caching the result using the target path as its cache key. + +Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods. + - Let's say you have a CSS file that you wish to populate with values from your site configuration: ++Let's say you have a CSS file that you wish to populate with values from your project configuration: + +```go-html-template {file="assets/css/template.css"} +body { + background-color: {{ site.Params.style.bg_color }}; + color: {{ site.Params.style.text_color }}; +} +``` + - And your site configuration contains: ++And your project configuration contains: + +{{< code-toggle file=hugo >}} +[params.style] +bg_color = '#fefefe' +text_color = '#222' +{{< /code-toggle >}} + +Place this in your baseof.html template: + +```go-html-template +{{ with resources.Get "css/template.css" }} + {{ with resources.ExecuteAsTemplate "css/main.css" $ . }} + + {{ end }} +{{ end }} +``` + +The example above: + +1. Captures the template as a resource +1. Executes the resource as a template, passing the current page in context +1. Publishes the resource to css/main.css + +The result is: + +```css {file="public/css/main.css"} +body { + background-color: #fefefe; + color: #222; +} +``` + +[`publish`]: /methods/resource/publish/ +[`permalink`]: /methods/resource/permalink/ +[`relpermalink`]: /methods/resource/relpermalink/ diff --cc docs/content/en/functions/resources/FromString.md index 8761d1c99,000000000..608b834de mode 100644,000000..100644 --- a/docs/content/en/functions/resources/FromString.md +++ b/docs/content/en/functions/resources/FromString.md @@@ -1,76 -1,0 +1,76 @@@ +--- +title: resources.FromString +description: Returns a resource created from a string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: resource.Resource + signatures: [resources.FromString TARGETPATH STRING] +--- + +The `resources.FromString` function returns a resource created from a string, caching the result using the target path as its cache key. + +Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods. + +[`publish`]: /methods/resource/publish/ +[`permalink`]: /methods/resource/permalink/ +[`relpermalink`]: /methods/resource/relpermalink/ + +Let's say you need to publish a file named "site.json" in the root of your `public` directory, containing the build date, the Hugo version used to build the site, and the date that the content was last modified. For example: + +```json +{ + "build_date": "2026-01-11T11:27:49-08:00", - "hugo_version": "0.155.3", ++ "hugo_version": "0.156.0", + "last_modified": "2026-01-11T11:27:59-08:00" +} +``` + +Place this in your baseof.html template: + +```go-html-template +{{ if .IsHome }} + {{ $rfc3339 := "2006-01-02T15:04:05Z07:00" }} + {{ $m := dict + "hugo_version" hugo.Version + "build_date" (now.Format $rfc3339) + "last_modified" (site.Lastmod.Format $rfc3339) + }} + {{ $json := jsonify $m }} + {{ $r := resources.FromString "site.json" $json }} + {{ $r.Publish }} +{{ end }} +``` + +The example above: + +1. Creates a map with the relevant key-value pairs using the [`dict`] function +1. Encodes the map as a JSON string using the [`jsonify`] function +1. Creates a resource from the JSON string using the `resources.FromString` function +1. Publishes the file to the root of the `public` directory using the resource's `.Publish` method + +Combine `resources.FromString` with [`resources.ExecuteAsTemplate`] if your string contains template actions. Rewriting the example above: + +```go-html-template +{{ if .IsHome }} + {{ $string := ` + {{ $rfc3339 := "2006-01-02T15:04:05Z07:00" }} + {{ $m := dict + "hugo_version" hugo.Version + "build_date" (now.Format $rfc3339) + "last_modified" (site.Lastmod.Format $rfc3339) + }} + {{ $json := jsonify $m }} + ` + }} + {{ $r := resources.FromString "" $string }} + {{ $r = $r | resources.ExecuteAsTemplate "site.json" . }} + {{ $r.Publish }} +{{ end }} +``` + +[`dict`]: /functions/collections/dictionary/ +[`jsonify`]: /functions/encoding/jsonify/ +[`resources.ExecuteAsTemplate`]: /functions/resources/executeastemplate/ diff --cc docs/content/en/functions/resources/GetRemote.md index 2a3270e88,000000000..35afd73c4 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/GetRemote.md +++ b/docs/content/en/functions/resources/GetRemote.md @@@ -1,243 -1,0 +1,240 @@@ +--- +title: resources.GetRemote +description: Returns a remote resource from the given URL, or nil if none found. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: resource.Resource + signatures: ['resources.GetRemote URL [OPTIONS]'] +--- + +{{< new-in 0.141.0 >}} +The `Err` method on the returned resource was removed in v0.141.0. + - Use the [`try`] statement instead, as shown in the [error handling] example below. - ++Use the [`try`](/functions/go-template/try) statement instead, as shown in the [error handling](#error-handling) example below. +{{< /new-in >}} + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else with .Value }} + + {{ else }} + {{ errorf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +## Options + +The `resources.GetRemote` function takes an optional map of options. + +body +: (`string`) The data you want to transmit to the server. + +headers +: (`map[string][]string`) The collection of key-value pairs that provide additional information about the request. + +key +: (`string`) The cache key. Hugo derives the default value from the URL and options map. See [caching](#caching). + +method +: (`string`) The action to perform on the requested resource, typically one of `GET`, `POST`, or `HEAD`. + +timeout +: (`string`) Cancels the request if it does not complete within this duration (e.g. "30s"). + +responseHeaders +: {{< new-in 0.143.0 />}} +: (`[]string`) The headers to extract from the server's response, accessible through the resource's [`Data.Headers`] method. Header name matching is case-insensitive.[`Data.Headers`]: /methods/resource/data/#headers + +## Options examples + +> [!note] +> For brevity, the examples below do not include [error handling]. + +To include a header: + +```go-html-template +{{ $url := "https://example.org/api" }} +{{ $opts := dict + "headers" (dict "Authorization" "Bearer abcd") +}} +{{ $resource := resources.GetRemote $url $opts }} +``` + +To specify more than one value for the same header key, use a slice: + +```go-html-template +{{ $url := "https://example.org/api" }} +{{ $opts := dict + "headers" (dict "X-List" (slice "a" "b" "c")) +}} +{{ $resource := resources.GetRemote $url $opts }} +``` + +To post data: + +```go-html-template +{{ $url := "https://example.org/api" }} +{{ $opts := dict + "method" "post" + "body" `{"complete": true}` + "headers" (dict "Content-Type" "application/json") +}} +{{ $resource := resources.GetRemote $url $opts }} +``` + +To override the default cache key: + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ $opts := dict + "key" (print $url (now.Format "2006-01-02")) +}} +{{ $resource := resources.GetRemote $url $opts }} +``` + +To extract specific headers from the server's response: + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ $opts := dict + "method" "HEAD" + "responseHeaders" (slice "X-Frame-Options" "Server") +}} +{{ $resource := resources.GetRemote $url $opts }} +``` + +To set a per-request timeout (e.g. when fetching many feeds where a few slow ones should not stall the build): + +```go-html-template +{{ $url := "https://example.org/feed.rss" }} +{{ $opts := dict "timeout" "10s" }} +{{ with try (resources.GetRemote $url $opts) }} + {{ with .Err }} + {{ warnf "Failed to fetch feed: %s" . }} + {{ else with .Value }} + {{ $data = . | transform.Unmarshal }} + {{ end }} +{{ end }} +``` + +## Remote data + +When retrieving remote data, use the [`transform.Unmarshal`] function to [unmarshal](g) the response. + +[`transform.Unmarshal`]: /functions/transform/unmarshal/ + +```go-html-template +{{ $data := dict }} +{{ $url := "https://example.org/books.json" }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else with .Value }} + {{ $data = . | transform.Unmarshal }} + {{ else }} + {{ errorf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +> [!note] +> When retrieving remote data, a misconfigured server may send a response header with an incorrect [Content-Type]. For example, the server may set the Content-Type header to `application/octet-stream` instead of `application/json`. +> +> In these cases, pass the resource `Content` through the `transform.Unmarshal` function instead of passing the resource itself. For example, in the above, do this instead: +> +> `{{ $data = .Content | transform.Unmarshal }}` + +## Error handling + +Use the [`try`] statement to capture HTTP request errors. If you do not handle the error yourself, Hugo will fail the build. + +> [!note] +> Hugo does not classify an HTTP response with status code 404 as an error. In this case `resources.GetRemote` returns nil. + +```go-html-template +{{ $url := "https://broken-example.org/images/a.jpg" }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else with .Value }} + + {{ else }} + {{ errorf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +To log an error as a warning instead of an error: + +```go-html-template +{{ $url := "https://broken-example.org/images/a.jpg" }} +{{ with try (resources.GetRemote $url) }} + {{ with .Err }} + {{ warnf "%s" . }} + {{ else with .Value }} + + {{ else }} + {{ warnf "Unable to get remote resource %q" $url }} + {{ end }} +{{ end }} +``` + +## HTTP response + +The [`Data`] method on a resource returned by the `resources.GetRemote` function returns information from the HTTP response. + +[`Data`]: /methods/resource/data/ + +## Caching + +Resources returned from `resources.GetRemote` are cached to disk. See [configure file caches] for details. + +By default, Hugo derives the cache key from the arguments passed to the function. Override the cache key by setting a `key` in the options map. Use this approach to have more control over how often Hugo fetches a remote resource. + +```go-html-template +{{ $url := "https://example.org/images/a.jpg" }} +{{ $cacheKey := print $url (now.Format "2006-01-02") }} +{{ $opts := dict "key" $cacheKey }} +{{ $resource := resources.GetRemote $url $opts }} +``` + +## Security + +To protect against malicious intent, the `resources.GetRemote` function inspects the server response including: + +- The [Content-Type] in the response header +- The file extension, if any +- The content itself + +If Hugo is unable to resolve the media type to an entry in its [allowlist], the function throws an error: + +```text +ERROR error calling resources.GetRemote: failed to resolve media type... +``` + +For example, you will see the error above if you attempt to download an executable. + - Although the allowlist contains entries for common media types, you may encounter situations where Hugo is unable to resolve the media type of a file that you know to be safe. In these situations, edit your site configuration to add the media type to the allowlist. For example: ++Although the allowlist contains entries for common media types, you may encounter situations where Hugo is unable to resolve the media type of a file that you know to be safe. In these situations, edit your project configuration to add the media type to the allowlist. For example: + +{{< code-toggle file=hugo >}} +[security.http] +mediaTypes = ['^image/avif$','^application/vnd\.api\+json$'] +{{< /code-toggle >}} + +Note that the entry above is: + +- An _addition_ to the allowlist; it does not _replace_ the allowlist +- An array of [regular expressions](g) + - [allowlist]: https://en.wikipedia.org/wiki/Whitelist - [Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type - +[`try`]: /functions/go-template/try ++[allowlist]: https://en.wikipedia.org/wiki/Whitelist +[configure file caches]: /configuration/caches/ - ++[Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type +[error handling]: #error-handling diff --cc docs/content/en/functions/resources/PostProcess.md index 766817ff5,000000000..c848ec239 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/PostProcess.md +++ b/docs/content/en/functions/resources/PostProcess.md @@@ -1,148 -1,0 +1,148 @@@ +--- +title: resources.PostProcess +description: Processes the given resource after the build. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: postpub.PostPublishedResource + signatures: [resources.PostProcess RESOURCE] +--- + +The `resources.PostProcess` function delays resource transformation steps until the build is complete, primarily for tasks like removing unused CSS rules. + +## Example + +In this example, after the build is complete, Hugo will: + +1. Purge unused CSS using the [PurgeCSS] plugin for [PostCSS] +1. Add vendor prefixes to CSS rules using the [Autoprefixer] plugin for PostCSS +1. [Minify] the CSS +1. [Fingerprint] the CSS + +Step 1 +: Install [Node.js]. + +Step 2 +: Install the required Node.js packages in the root of your project: + + ```sh {copy=true} + npm i -D postcss postcss-cli autoprefixer @fullhuman/postcss-purgecss + ``` + +Step 3 +: Enable creation of the `hugo_stats.json` file when building the site. If you are only using this for the production build, consider placing it below [`config/production`]. + + {{< code-toggle file=hugo copy=true >}} + [build.buildStats] + enable = true + {{< /code-toggle >}} + + See the [configure build] documentation for details and options. + +Step 4 +: Create a PostCSS configuration file in the root of your project. + + ```js {file="postcss.config.js" copy=true} + const autoprefixer = require('autoprefixer'); + const purgeCSSPlugin = require('@fullhuman/postcss-purgecss').default; + + const purgecss = purgeCSSPlugin({ + content: ['./hugo_stats.json'], + defaultExtractor: content => { + const els = JSON.parse(content).htmlElements; + return [ + ...(els.tags || []), + ...(els.classes || []), + ...(els.ids || []), + ]; + }, + // https://purgecss.com/safelisting.html + safelist: [] + }); + + module.exports = { + plugins: [ + process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null, + autoprefixer, + ] + }; + ``` + + > [!note] + > If you are a Windows user, and the path to your project contains a space, you must place the PostCSS configuration within the package.json file. See [this example] and issue [#7333]. + +Step 5 +: Place your CSS file within the `assets/css` directory. + +Step 6 +: If the current environment is not `development`, process the resource with PostCSS: + + ```go-html-template {copy=true} + {{ with resources.Get "css/main.css" }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | postCSS | minify | fingerprint | resources.PostProcess }} + + {{ end }} + {{ end }} + {{ end }} + ``` + +## Environment variables + +Hugo passes the environment variables below to PostCSS, allowing you to do something like: + +```js +process.env.HUGO_ENVIRONMENT !== 'development' ? purgecss : null, +``` + +PWD +: The absolute path to the project working directory. + +HUGO_ENVIRONMENT +: The current Hugo environment, set with the `--environment` command line flag. - Default is `production` for `hugo` and `development` for `hugo server`. ++Default is `production` for `hugo build` and `development` for `hugo server`. + +HUGO_PUBLISHDIR +: The absolute path to the publish directory, typically `public`. This value points to a directory on disk, even when rendering to memory with the `--renderToMemory` command line flag. + +HUGO_FILE_X +: Hugo automatically mounts the following files from your project's root directory under `assets/_jsconfig`: + +- `babel.config.js` +- `postcss.config.js` +- `tailwind.config.js` + +For each file, Hugo creates a corresponding environment variable named `HUGO_FILE_:filename:`, where `:filename:` is the uppercase version of the filename with periods replaced by underscores. This allows you to access these files within your JavaScript, for example: + +```js +let tailwindConfig = process.env.HUGO_FILE_TAILWIND_CONFIG_JS || './tailwind.config.js'; +``` + +## Limitations + +Do not use `resources.PostProcess` when running Hugo's built-in development server. The examples above specifically prevent this by verifying that the current environment is not `development`. + +The `resources.PostProcess` function only works within templates that produce HTML files. + +You cannot manipulate the values returned from the resource's methods. For example, the `strings.ToUpper` function in this example will not work as expected: + +```go-html-template +{{ $css := resources.Get "css/main.css" }} +{{ $css = $css | css.PostCSS | minify | fingerprint | resources.PostProcess }} +{{ $css.RelPermalink | strings.ToUpper }} +``` + +[#7333]: https://github.com/gohugoio/hugo/issues/7333 +[`config/production`]: /configuration/introduction/#configuration-directory +[Autoprefixer]: https://github.com/postcss/autoprefixer +[configure build]: /configuration/build/ +[Fingerprint]: /functions/resources/fingerprint/ +[Minify]: /functions/resources/minify/ +[Node.js]: https://nodejs.org/en +[PostCSS]: https://postcss.org/ +[PurgeCSS]: https://github.com/FullHuman/purgecss +[this example]: https://github.com/postcss/postcss-load-config#packagejson diff --cc docs/content/en/functions/strings/Title.md index d1b4aca01,000000000..0ff79cdf0 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/Title.md +++ b/docs/content/en/functions/strings/Title.md @@@ -1,29 -1,0 +1,29 @@@ +--- +title: strings.Title +description: Returns the given string, converting it to title case. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [title] + returnType: string + signatures: [strings.Title STRING] +aliases: [/functions/title] +--- + +```go-html-template +{{ title "table of contents (TOC)" }} → Table of Contents (TOC) +``` + - By default, Hugo follows the capitalization rules published in the [Associated Press Stylebook]. Change your [site configuration] if you would prefer to: ++By default, Hugo follows the capitalization rules published in the [Associated Press Stylebook]. Change your [project configuration] if you would prefer to: + +- Follow the capitalization rules published in the [Chicago Manual of Style] +- Capitalize the first letter of every word +- Capitalize the first letter of the first word +- Disable the effects of the `title` function + +The last option is useful if your theme uses the `title` function, and you would prefer to manually capitalize strings as needed. + +[Associated Press Stylebook]: https://www.apstylebook.com/ +[Chicago Manual of Style]: https://www.chicagomanualofstyle.org/home.html - [site configuration]: /configuration/all/#title-case-style ++[project configuration]: /configuration/all/#title-case-style diff --cc docs/content/en/functions/templates/Current.md index b82818c47,000000000..47adf38ae mode 100644,000000..100644 --- a/docs/content/en/functions/templates/Current.md +++ b/docs/content/en/functions/templates/Current.md @@@ -1,155 -1,0 +1,155 @@@ +--- +title: templates.Current +description: Returns information about the currently executing template. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: tpl.CurrentTemplateInfo + signatures: [templates.Current] +--- + +> [!note] +> This function is experimental and subject to change. + +{{< new-in 0.146.0 />}} + +The `templates.Current` function provides introspection capabilities, allowing you to access details about the currently executing templates. This is useful for debugging complex template hierarchies and understanding the flow of execution during rendering. + +## Methods + +Ancestors +: (`tpl.CurrentTemplateInfos`) Returns a slice containing information about each template in the current execution chain, starting from the parent of the current template and going up towards the initial template called. It excludes any base template applied via `define` and `block`. You can chain the `Reverse` method to this result to get the slice in chronological execution order. + +Base +: (`tpl.CurrentTemplateInfoCommonOps`) Returns an object representing the base template that was applied to the current template, if any. This may be `nil`. + +Filename +: (`string`) Returns the absolute path of the current template. This will be empty for embedded templates. + +Name +: (`string`) Returns the name of the current template. This is usually the path relative to the layouts directory. + +Parent +: (`tpl.CurrentTemplateInfo`) Returns an object representing the parent of the current template, if any. This may be `nil`. + +## Examples + - The examples below help visualize template execution and require a `debug` parameter set to `true` in your site configuration: ++The examples below help visualize template execution and require a `debug` parameter set to `true` in your project configuration: + +{{< code-toggle file=hugo >}} +[params] +debug = true +{{< /code-toggle >}} + +### Boundaries + +To visually mark where a template begins and ends execution: + +```go-html-template {file="layouts/page.html"} +{{ define "main" }} + {{ if site.Params.debug }} +
    [entering {{ templates.Current.Filename }}]
    + {{ end }} + +

    {{ .Title }}

    + {{ .Content }} + + {{ if site.Params.debug }} +
    [leaving {{ templates.Current.Filename }}]
    + {{ end }} +{{ end }} +``` + +### Call stack + +To display the chain of templates that led to the current one, create a _partial_ template that iterates through its ancestors: + +```go-html-template {file="layouts/_partials/template-call-stack.html" copy=true} +{{ with templates.Current }} +
    + {{ range .Ancestors }} + {{ .Filename }}
    + {{ with .Base }} + {{ .Filename }}
    + {{ end }} + {{ end }} +
    +{{ end }} +``` + +Then call the partial from any template: + +```go-html-template {file="layouts/_partials/footer/copyright.html" copy=true} +{{ if site.Params.debug }} + {{ partial "template-call-stack.html" . }} +{{ end }} +``` + +The rendered template stack would look something like this: + +```text +/home/user/project/layouts/_partials/footer/copyright.html +/home/user/project/themes/foo/layouts/_partials/footer.html +/home/user/project/layouts/page.html +/home/user/project/themes/foo/layouts/baseof.html +``` + +To reverse the order of the entries, chain the `Reverse` method to the `Ancestors` method: + +```go-html-template {file="layouts/_partials/template-call-stack.html" copy=true} +{{ with templates.Current }} +
    + {{ range .Ancestors.Reverse }} + {{ with .Base }} + {{ .Filename }}
    + {{ end }} + {{ .Filename }}
    + {{ end }} +
    +{{ end }} +``` + +### VS Code + +To render links that, when clicked, will open the template in Microsoft Visual Studio Code, create a _partial_ template with anchor elements that use the `vscode` URI scheme: + +```go-html-template {file="layouts/_partials/template-open-in-vs-code.html" copy=true} +{{ with templates.Current.Parent }} +
    + {{ .Name }} + {{ with .Base }} + {{ .Name }} + {{ end }} +
    +{{ end }} +``` + +Then call the partial from any template: + +```go-html-template {file="layouts/page.html" copy=true} +{{ define "main" }} +

    {{ .Title }}

    + {{ .Content }} + + {{ if site.Params.debug }} + {{ partial "template-open-in-vs-code.html" . }} + {{ end }} +{{ end }} +``` + +Use the same approach to render the entire call stack as links: + +```go-html-template {file="layouts/_partials/template-call-stack.html" copy=true} +{{ with templates.Current }} +
    + {{ range .Ancestors }} + {{ .Filename }}
    + {{ with .Base }} + {{ .Filename }}
    + {{ end }} + {{ end }} +
    +{{ end }} +``` diff --cc docs/content/en/functions/time/AsTime.md index 760329a13,000000000..884d6c61b mode 100644,000000..100644 --- a/docs/content/en/functions/time/AsTime.md +++ b/docs/content/en/functions/time/AsTime.md @@@ -1,48 -1,0 +1,48 @@@ +--- +title: time.AsTime +description: Returns the given string representation of a date/time value as a time.Time value. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [time] + returnType: time.Time + signatures: ['time.AsTime INPUT [TIMEZONE]'] +aliases: [/functions/time] +--- + +## Overview + +Hugo provides [functions] and [methods] to format, localize, parse, compare, and manipulate date/time values. Before you can do any of these with string representations of date/time values, you must first convert them to [`time.Time`] values using the `time.AsTime` function. + +```go-html-template +{{ $t := "2023-10-15T13:18:50-07:00" }} +{{ time.AsTime $t }} → 2023-10-15 13:18:50 -0700 PDT (time.Time) +``` + +## Parsable strings + +As shown above, the first argument must be a parsable string representation of a date/time value. For example: + +{{% include "/_common/parsable-date-time-strings.md" %}} + - To override the default time zone, set the [`timeZone`] in your site configuration or provide a second argument to the `time.AsTime` function. For example: ++To override the default time zone, set the [`timeZone`] in your project configuration or provide a second argument to the `time.AsTime` function. For example: + +```go-html-template +{{ time.AsTime "15 Oct 2023" "America/Los_Angeles" }} +``` + +The list of valid time zones may be system dependent, but should include `UTC`, `Local`, or any location in the [IANA Time Zone database]. + +The order of precedence for determining the time zone is: + +1. The time zone offset in the date/time string +1. The time zone provided as the second argument to the `time.AsTime` function - 1. The time zone specified in your site configuration ++1. The time zone specified in your project configuration +1. The `Etc/UTC` time zone + +[IANA Time Zone database]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones +[`time.Time`]: https://pkg.go.dev/time#Time +[`timeZone`]: /configuration/all/#timezone +[functions]: /functions/time/ +[methods]: /methods/time/ diff --cc docs/content/en/functions/time/Format.md index f1b0d6d83,000000000..112a6e72e mode 100644,000000..100644 --- a/docs/content/en/functions/time/Format.md +++ b/docs/content/en/functions/time/Format.md @@@ -1,80 -1,0 +1,80 @@@ +--- +title: time.Format +description: Returns the given date/time as a formatted and localized string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [dateFormat] + returnType: string + signatures: [time.Format LAYOUT INPUT] +aliases: [/functions/dateformat] +--- + +Use the `time.Format` function with `time.Time` values: + +```go-html-template +{{ $t := time.AsTime "2023-10-15T13:18:50-07:00" }} +{{ time.Format "2 Jan 2006" $t }} → 15 Oct 2023 +``` + +Or use `time.Format` with a parsable string representation of a date/time value: + +```go-html-template +{{ $t := "15 Oct 2023" }} +{{ time.Format "January 2, 2006" $t }} → October 15, 2023 +``` + +Examples of parsable string representations: + +{{% include "/_common/parsable-date-time-strings.md" %}} + - To override the default time zone, set the [`timeZone`] in your site configuration. The order of precedence for determining the time zone is: ++To override the default time zone, set the [`timeZone`] in your project configuration. The order of precedence for determining the time zone is: + +1. The time zone offset in the date/time string - 1. The time zone specified in your site configuration ++1. The time zone specified in your project configuration +1. The `Etc/UTC` time zone + +[`timeZone`]: /configuration/all/#timezone + +## Layout string + +{{% include "/_common/time-layout-string.md" %}} + +## Localization + +Use the `time.Format` function to localize `time.Time` values for the current language and region. + +{{% include "/_common/functions/locales.md" %}} + +Use the layout string as described above, or one of the tokens below. For example: + +```go-html-template +{{ .Date | time.Format ":date_medium" }} → Jan 27, 2023 +``` + +Localized to en-US: + +Token|Result +:--|:-- +`:date_full`|`Friday, January 27, 2023` +`:date_long`|`January 27, 2023` +`:date_medium`|`Jan 27, 2023` +`:date_short`|`1/27/23` +`:time_full`|`11:44:58 pm Pacific Standard Time` +`:time_long`|`11:44:58 pm PST` +`:time_medium`|`11:44:58 pm` +`:time_short`|`11:44 pm` + +Localized to de-DE: + +Token|Result +:--|:-- +`:date_full`|`Freitag, 27. Januar 2023` +`:date_long`|`27. Januar 2023` +`:date_medium`|`27.01.2023` +`:date_short`|`27.01.23` +`:time_full`|`23:44:58 Nordamerikanische Westküsten-Normalzeit` +`:time_long`|`23:44:58 PST` +`:time_medium`|`23:44:58` +`:time_short`|`23:44` diff --cc docs/content/en/functions/transform/Emojify.md index 31c5dce70,000000000..6a4501fc5 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/Emojify.md +++ b/docs/content/en/functions/transform/Emojify.md @@@ -1,27 -1,0 +1,27 @@@ +--- +title: transform.Emojify +description: Runs a string through the Emoji emoticons processor. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [emojify] + returnType: template.HTML + signatures: [transform.Emojify INPUT] +aliases: [/functions/emojify] +--- + +`emojify` runs a passed string through the Emoji emoticons processor. + +See the list of [emoji shortcodes] for available emoticons. + - The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set [`enableEmoji`] to `true` in your site's configuration. Then you can write emoji shorthand directly into your content files; ++The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set [`enableEmoji`] to `true` in your project configuration. Then you can write emoji shorthand directly into your content files; + +```text +I :heart: Hugo! +``` + +I :heart: Hugo! + +[`enableEmoji`]: /configuration/all/#enableemoji +[emoji shortcodes]: /quick-reference/emojis/ diff --cc docs/content/en/functions/transform/Highlight.md index 5633f2256,000000000..1e4e235b4 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/Highlight.md +++ b/docs/content/en/functions/transform/Highlight.md @@@ -1,53 -1,0 +1,53 @@@ +--- +title: transform.Highlight +description: Renders code with a syntax highlighter. +categories: [] +keywords: [highlight] +params: + functions_and_methods: + aliases: [highlight] + returnType: template.HTML + signatures: ['transform.Highlight CODE LANG [OPTIONS]'] +aliases: [/functions/highlight] +--- + +The `highlight` function uses the [Chroma] syntax highlighter, supporting over 200 languages with more than 40 [highlighting styles]. + +[chroma]: https://github.com/alecthomas/chroma +[highlighting styles]: /quick-reference/syntax-highlighting-styles/ + +## Arguments + +The `transform.Highlight` shortcode takes three arguments. + +CODE +: (`string`) The code to highlight. + +LANG +: (`string`) The language of the code to highlight. Choose from one of the [supported languages]. This value is case-insensitive. + +OPTIONS - : (`map or string`) A map or comma-separated key-value pairs wrapped in quotation marks. Set default values for each option in your [site configuration]. The key names are case-insensitive. ++: (`map or string`) A map or comma-separated key-value pairs wrapped in quotation marks. Set default values for each option in your [project configuration]. The key names are case-insensitive. + - [site configuration]: /configuration/markup#highlight ++[project configuration]: /configuration/markup#highlight +[supported languages]: /content-management/syntax-highlighting#languages + +## Examples + +```go-html-template +{{ $input := `fmt.Println("Hello World!")` }} +{{ transform.Highlight $input "go" }} + +{{ $input := `console.log('Hello World!');` }} +{{ $lang := "js" }} +{{ transform.Highlight $input $lang "lineNos=table, style=api" }} + +{{ $input := `echo "Hello World!"` }} +{{ $lang := "bash" }} +{{ $opts := dict "lineNos" "table" "style" "dracula" }} +{{ transform.Highlight $input $lang $opts }} +``` + +## Options + +{{% include "_common/syntax-highlighting-options.md" %}} diff --cc docs/content/en/functions/transform/PortableText.md index fa9a91e33,000000000..d100f5eb2 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/PortableText.md +++ b/docs/content/en/functions/transform/PortableText.md @@@ -1,215 -1,0 +1,215 @@@ +--- +title: transform.PortableText +description: Converts Portable Text to Markdown. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [transform.PortableText MAP] +--- + +{{< new-in "0.145.0" />}} + +[Portable Text](https://www.portabletext.org/) is a JSON structure that represent rich text content in the [Sanity](https://www.sanity.io/) CMS. In Hugo, this function is typically used in a [Content Adapter](https://gohugo.io/content-management/content-adapters/) that creates pages from Sanity data. + +## Types supported + +- `block` and `span` +- `image`. Note that the image handling is currently very simple; we link to the `asset.url` using `asset.altText` as the image alt text and `asset.title` as the title. For more fine grained control you may want to process the images in a [image render hook](/render-hooks/images/). +- `code` (see the [code-input](https://www.sanity.io/plugins/code-input) plugin). Code will be rendered as [fenced code blocks](/contribute/documentation/#fenced-code-blocks) with any file name provided passed on as a markdown attribute. + +> [!note] +> Since the Portable Text gets converted to Markdown before it gets passed to Hugo, rendering of links, headings, images and code blocks can be controlled with [Render Hooks](https://gohugo.io/render-hooks/). + +## Example + +### Content Adapter + +```go-html-template {file="content/_content.gotmpl" copy=true} +{{ $projectID := "mysanityprojectid" }} +{{ $useCached := true }} +{{ $api := "api" }} +{{ if $useCached }} + {{/* See https://www.sanity.io/docs/api-cdn */}} + {{ $api = "apicdn" }} +{{ end }} +{{ $url := printf "https://%s.%s.sanity.io/v2021-06-07/data/query/production" $projectID $api }} + +{{/* prettier-ignore-start */ -}} +{{ $q := `*[_type == 'post']{ + title, publishedAt, summary, slug, body[]{ + ..., + _type == "image" => { + ..., + asset->{ + _id, + path, + url, + altText, + title, + description, + metadata { + dimensions { + aspectRatio, + width, + height + } + } + } + } + }, + }` +}} +{{/* prettier-ignore-end */ -}} +{{ $body := dict "query" $q | jsonify }} +{{ $opts := dict "method" "post" "body" $body }} +{{ $r := resources.GetRemote $url $opts }} +{{ $m := $r | transform.Unmarshal }} +{{ $result := $m.result }} +{{ range $result }} + {{ if not .slug }} + {{ continue }} + {{ end }} + {{ $markdown := transform.PortableText .body }} + {{ $content := dict + "mediaType" "text/markdown" + "value" $markdown + }} + {{ $params := dict + "portabletext" (.body | jsonify (dict "indent" " ")) + }} + {{ $page := dict + "content" $content + "kind" "page" + "path" .slug.current + "title" .title + "date" (.publishedAt | time ) + "summary" .summary + "params" $params + }} + {{ $.AddPage $page }} +{{ end }} +``` + +### Sanity setup + +Below outlines a suitable Sanity studio setup for the above example. + +```ts {file="sanity.config.ts" copy=true} +import {defineConfig} from 'sanity' +import {structureTool} from 'sanity/structure' +import {visionTool} from '@sanity/vision' +import {schemaTypes} from './schemaTypes' +import {media} from 'sanity-plugin-media' +import {codeInput} from '@sanity/code-input' + +export default defineConfig({ + name: 'default', + title: 'my-sanity-project', + + projectId: 'mysanityprojectid', + dataset: 'production', + + plugins: [structureTool(), visionTool(), media(),codeInput()], + + schema: { + types: schemaTypes, + }, +}) +``` + +Type/schema definition: + +```ts {file="schemaTypes/postType.ts" copy=true} +import {defineField, defineType} from 'sanity' + +export const postType = defineType({ + name: 'post', + title: 'Post', + type: 'document', + fields: [ + defineField({ + name: 'title', + type: 'string', + validation: (rule) => rule.required(), + }), + defineField({ + name: 'summary', + type: 'string', + validation: (rule) => rule.required(), + }), + defineField({ + name: 'slug', + type: 'slug', + options: {source: 'title'}, + validation: (rule) => rule.required(), + }), + defineField({ + name: 'publishedAt', + type: 'datetime', + initialValue: () => new Date().toISOString(), + validation: (rule) => rule.required(), + }), + defineField({ + name: 'body', + type: 'array', + of: [ + { + type: 'block', + }, + { + type: 'image' + }, + { + type: 'code', + options: { + language: 'css', + languageAlternatives: [ + {title: 'HTML', value: 'html'}, + {title: 'CSS', value: 'css'}, + ], + withFilename: true, + }, + }, + ], + }), + ], +}) +``` + +Note that the above requires some additional plugins to be installed: + - ```bash ++```sh +npm i sanity-plugin-media @sanity/code-input +``` + +```ts {file="schemaTypes/index.ts" copy=true} +import {postType} from './postType' + +export const schemaTypes = [postType] +``` + +## Server setup + +Unfortunately, Sanity's API does not support [RFC 7234](https://tools.ietf.org/html/rfc7234) and their output changes even if the data has not. A recommended setup is therefore to use their cached `apicdn` endpoint (see above) and then set up a reasonable polling and file cache strategy in your Hugo configuration, e.g: + + +{{< code-toggle file=hugo >}} +[HTTPCache] + [[HTTPCache.polls]] + disable = false + low = '30s' + high = '3m' + [HTTPCache.polls.for] + includes = ['https://*.*.sanity.io/**'] + +[caches.getresource] + dir = ':cacheDir/:project' + maxAge = "5m" +{{< /code-toggle >}} + + +The polling above will be used when running the server/watch mode and rebuild when you push new content in Sanity. + +See [Caching in resources.GetRemote](/functions/resources/getremote/#caching) for more fine grained control. diff --cc docs/content/en/functions/transform/ToMath.md index 97689f5d5,000000000..27b2f0d70 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/ToMath.md +++ b/docs/content/en/functions/transform/ToMath.md @@@ -1,196 -1,0 +1,196 @@@ +--- +title: transform.ToMath +description: Renders mathematical equations and expressions written in the LaTeX markup language. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: template.HTML + signatures: ['transform.ToMath INPUT [OPTIONS]'] +aliases: [/functions/tomath] +--- + +{{< new-in 0.132.0 />}} + +Hugo uses an embedded instance of the [KaTeX] display engine to render mathematical markup to HTML. You do not need to install the KaTeX display engine. + +```go-html-template +{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }} +``` + +> [!note] +> By default, Hugo renders mathematical markup to [MathML], and does not require any CSS to display the result. +> +> To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet. + +```go-html-template +{{ $opts := dict "output" "htmlAndMathml" }} +{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" $opts }} +``` + +## Options + +Pass a map of options as the second argument to the `transform.ToMath` function. The options below are a subset of the KaTeX [rendering options]. + +displayMode +: (`bool`) Whether to render in display mode instead of inline mode. Default is `false`. + +errorColor +: (`string`) The color of the error messages expressed as an RGB [hexadecimal color]. Default is `#cc0000`. + +fleqn +: (`bool`) Whether to render flush left with a 2em left margin. Default is `false`. + +macros +: (`map`) A map of macros to be used in the math expression. Default is `{}`. + + ```go-html-template + {{ $macros := dict + "\\addBar" "\\bar{#1}" + "\\bold" "\\mathbf{#1}" + }} + {{ $opts := dict "macros" $macros }} + {{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }} + ``` + +minRuleThickness +: (`float`) The minimum thickness of the fraction lines in `em`. Default is `0.04`. + +output +: (`string`) Determines the markup language of the output, one of `html`, `mathml`, or `htmlAndMathml`. Default is `mathml`. + + With `html` and `htmlAndMathml` you must include the KaTeX style sheet within the `head` element of your base template. + + ```html + + ``` + +strict +: {{< new-in 0.147.6 />}} +: (`string`) Controls how KaTeX handles LaTeX features that offer convenience but aren't officially supported, one of `error`, `ignore`, or `warn`. Default is `error`. + + - `error`: Throws an error when convenient, unsupported LaTeX features are encountered. + - `ignore`: Allows convenient, unsupported LaTeX features without any feedback. + - `warn`: {{< new-in 0.147.7 />}} Emits a warning when convenient, unsupported LaTeX features are encountered. + + The `newLineInDisplayMode` error code, which flags the use of `\\` or `\newline` in display mode outside an array or tabular environment, is intentionally designed not to throw an error, despite this behavior being questionable. + +throwOnError +: (`bool`) Whether to throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTeX. Default is `true`. + +## Error handling + +There are three ways to handle errors: + +1. Let KaTeX throw an error and fail the build. This is the default behavior. +1. Set the `throwOnError` option to `false` to make KaTeX render the expression as an error instead of throwing an error. See [options](#options). +1. Handle the error in your template. + +The example below demonstrates error handing within a template. + +## Example + +Instead of client-side JavaScript rendering of mathematical markup using MathJax or KaTeX, create a passthrough render hook which calls the `transform.ToMath` function. + +Step 1 - : Enable and configure the Goldmark [passthrough extension][] in your site configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves. ++: Enable and configure the Goldmark [passthrough extension][] in your project configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves. + +[passthrough extension]: /configuration/markup/#passthrough + + {{< code-toggle file=hugo copy=true >}} + [markup.goldmark.extensions.passthrough] + enable = true + [markup.goldmark.extensions.passthrough.delimiters] + block = [['\[', '\]'], ['$$', '$$']] + inline = [['\(', '\)']] + {{< /code-toggle >}} + + > [!note] + > The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration, you must double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting. + +Step 2 +: Create a [passthrough render hook][] to capture and render the LaTeX markup.4 + +[passthrough render hook]: /render-hooks/passthrough/ + + ```go-html-template {file="layouts/_markup/render-passthrough.html" copy=true} + {{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }} + {{- with try (transform.ToMath .Inner $opts) }} + {{- with .Err }} + {{- errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }} + {{- else }} + {{- .Value }} + {{- $.Page.Store.Set "hasMath" true }} + {{- end }} + {{- end -}} + ``` + +Step 3 +: In your base template, conditionally include the KaTeX CSS within the head element. + + ```go-html-template {file="layouts/baseof.html" copy=true} + + {{ $noop := .WordCount }} + {{ if .Page.Store.Get "hasMath" }} + + {{ end }} + + ``` + + In the above, note the use of a [noop](g) statement to force content rendering before we check the value of `hasMath` with the `Store.Get` method. + + > [!note] + > This conditional approach only identifies math on the current page. Mathematical expressions will not display correctly when one page's content is embedded within another. For example, if a [list page](g) calls the [`Content`][] or [`Summary`][] methods while ranging through its page collection, the list page will not load the KaTeX CSS. + > + > If this affects your site, use this conditional logic instead: + > + > ```go-html-template {file="layouts/baseof.html" copy=true} + > {{ $noop := .WordCount }} + > {{ if or (.Page.Store.Get "hasMath") .IsNode }} + > + > {{ end }} + > ``` + +Step 4 +: Add some mathematical markup to your content, then test. + + ```text {file="content/example.md"} + This is an inline \(a^*=x-b^*\) equation. + + These are block equations: + + \[a^*=x-b^*\] + + $$a^*=x-b^*$$ + ``` + +## Chemistry + +{{< new-in 0.144.0 />}} + +You can also use the `transform.ToMath` function to render chemical equations, leveraging the `\ce` and `\pu` functions from the [mhchem] package. + +```text +$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$ +``` + +$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$ + +[`Content`]: /methods/page/content/ +[`Summary`]: /methods/page/summary/ +[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color +[KaTeX]: https://katex.org/ +[MathML]: https://developer.mozilla.org/en-US/docs/Web/MathML +[mhchem]: https://mhchem.github.io/MathJax-mhchem/ +[rendering options]: https://katex.org/docs/options.html diff --cc docs/content/en/functions/urls/AbsLangURL.md index da45ca224,000000000..b2cf021c3 mode 100644,000000..100644 --- a/docs/content/en/functions/urls/AbsLangURL.md +++ b/docs/content/en/functions/urls/AbsLangURL.md @@@ -1,72 -1,0 +1,72 @@@ +--- +title: urls.AbsLangURL +description: Returns an absolute URL with a language prefix, if any. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [absLangURL] + returnType: string + signatures: [urls.AbsLangURL INPUT] +aliases: [/functions/abslangurl] +--- + +Use this function with both monolingual and multilingual configurations. The URL returned by this function depends on: + +- Whether the input begins with a slash (`/`) - - The `baseURL` in your site configuration ++- The `baseURL` in your project configuration +- The language prefix, if any + - This is the site configuration for the examples that follow: ++This is the project configuration for the examples that follow: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = true +[languages.en] +weight = 1 +[languages.es] +weight = 2 +{{< /code-toggle >}} + +## Input does not begin with a slash + - If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your site configuration. ++If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your project configuration. + +When rendering the `en` site with `baseURL = https://example.org/` + +```go-html-template +{{ absLangURL "" }} → https://example.org/en/ +{{ absLangURL "articles" }} → https://example.org/en/articles +{{ absLangURL "style.css" }} → https://example.org/en/style.css +``` + +When rendering the `en` site with `baseURL = https://example.org/docs/` + +```go-html-template +{{ absLangURL "" }} → https://example.org/docs/en/ +{{ absLangURL "articles" }} → https://example.org/docs/en/articles +{{ absLangURL "style.css" }} → https://example.org/docs/en/style.css +``` + +## Input begins with a slash + - If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration. ++If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your project configuration. + +When rendering the `en` site with `baseURL = https://example.org/` + +```go-html-template +{{ absLangURL "/" }} → https://example.org/en/ +{{ absLangURL "/articles" }} → https://example.org/en/articles +{{ absLangURL "/style.css" }} → https://example.org/en/style.css +``` + +When rendering the `en` site with `baseURL = https://example.org/docs/` + +```go-html-template +{{ absLangURL "/" }} → https://example.org/en/ +{{ absLangURL "/articles" }} → https://example.org/en/articles +{{ absLangURL "/style.css" }} → https://example.org/en/style.css +``` + +> [!note] +> As illustrated by the previous example, using a leading slash is rarely desirable and can lead to unexpected outcomes. In nearly all cases, omit the leading slash. diff --cc docs/content/en/functions/urls/AbsURL.md index 72613cd0b,000000000..e29862429 mode 100644,000000..100644 --- a/docs/content/en/functions/urls/AbsURL.md +++ b/docs/content/en/functions/urls/AbsURL.md @@@ -1,62 -1,0 +1,62 @@@ +--- +title: urls.AbsURL +description: Returns an absolute URL. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [absURL] + returnType: string + signatures: [urls.AbsURL INPUT] +aliases: [/functions/absurl] +--- + +With multilingual configurations, use the [`urls.AbsLangURL`] function instead. The URL returned by this function depends on: + +- Whether the input begins with a slash (`/`) - - The `baseURL` in your site configuration ++- The `baseURL` in your project configuration + +## Input does not begin with a slash + - If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your site configuration. ++If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your project configuration. + +With `baseURL = https://example.org/` + +```go-html-template +{{ absURL "" }} → https://example.org/ +{{ absURL "articles" }} → https://example.org/articles +{{ absURL "style.css" }} → https://example.org/style.css +``` + +With `baseURL = https://example.org/docs/` + +```go-html-template +{{ absURL "" }} → https://example.org/docs/ +{{ absURL "articles" }} → https://example.org/docs/articles +{{ absURL "style.css" }} → https://example.org/docs/style.css +``` + +## Input begins with a slash + - If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration. ++If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your project configuration. + +With `baseURL = https://example.org/` + +```go-html-template +{{ absURL "/" }} → https://example.org/ +{{ absURL "/articles" }} → https://example.org/articles +{{ absURL "/style.css" }} → https://example.org/style.css +``` + +With `baseURL = https://example.org/docs/` + +```go-html-template +{{ absURL "/" }} → https://example.org/ +{{ absURL "/articles" }} → https://example.org/articles +{{ absURL "/style.css" }} → https://example.org/style.css +``` + +> [!note] +> As illustrated by the previous example, using a leading slash is rarely desirable and can lead to unexpected outcomes. In nearly all cases, omit the leading slash. + +[`urls.AbsLangURL`]: /functions/urls/abslangurl/ diff --cc docs/content/en/functions/urls/Anchorize.md index d18bd9a4d,000000000..d529ec493 mode 100644,000000..100644 --- a/docs/content/en/functions/urls/Anchorize.md +++ b/docs/content/en/functions/urls/Anchorize.md @@@ -1,36 -1,0 +1,36 @@@ +--- +title: urls.Anchorize +description: Returns the given string, sanitized for usage in an HTML id attribute. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [anchorize] + returnType: string + signatures: [urls.Anchorize INPUT] +aliases: [/functions/anchorize] +--- + +{{% include "/_common/functions/urls/anchorize-vs-urlize.md" %}} + +## Sanitizing logic + - With the default Markdown renderer, Goldmark, the sanitizing logic is controlled by your site configuration: ++With the default Markdown renderer, Goldmark, the sanitizing logic is controlled by your project configuration: + +{{< code-toggle file=hugo >}} +[markup.goldmark.parser] +autoHeadingIDType = 'github' +{{< /code-toggle >}} + +This controls the behavior of the `anchorize` function and the generation of heading IDs when rendering Markdown to HTML. + +Set `autoHeadingIDType` to one of: + +github +: Compatible with GitHub. This is the default. + +github-ascii +: Similar to the `github` setting, but removes non-ASCII characters. + +blackfriday +: Provided for backwards compatibility with Hugo v0.59.1 and earlier. This option will be removed in a future release. diff --cc docs/content/en/functions/urls/RelLangURL.md index af8bff3d7,000000000..ea3131672 mode 100644,000000..100644 --- a/docs/content/en/functions/urls/RelLangURL.md +++ b/docs/content/en/functions/urls/RelLangURL.md @@@ -1,82 -1,0 +1,82 @@@ +--- +title: urls.RelLangURL +description: Returns a relative URL with a language prefix, if any. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [relLangURL] + returnType: string + signatures: [urls.RelLangURL INPUT] +aliases: [/functions/rellangurl] +--- + +Use this function with both monolingual and multilingual configurations. The URL returned by this function depends on: + +- Whether the input begins with a slash (`/`) - - The `baseURL` in your site configuration ++- The `baseURL` in your project configuration +- The language prefix, if any + - This is the site configuration for the examples that follow: ++This is the project configuration for the examples that follow: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = true +[languages.en] +weight = 1 +[languages.es] +weight = 2 +{{< /code-toggle >}} + +## Input does not begin with a slash + - If the input does not begin with a slash, the resulting URL will be relative to the `baseURL` in your site configuration. ++If the input does not begin with a slash, the resulting URL will be relative to the `baseURL` in your project configuration. + +When rendering the `en` site with `baseURL = https://example.org/` + +```go-html-template +{{ relLangURL "" }} → /en/ +{{ relLangURL "articles" }} → /en/articles +{{ relLangURL "style.css" }} → /en/style.css +{{ relLangURL "https://example.org" }} → https://example.org +{{ relLangURL "https://example.org/" }} → /en +{{ relLangURL "https://www.example.org" }} → https://www.example.org +{{ relLangURL "https://www.example.org/" }} → https://www.example.org/ +``` + +When rendering the `en` site with `baseURL = https://example.org/docs/` + +```go-html-template +{{ relLangURL "" }} → /docs/en/ +{{ relLangURL "articles" }} → /docs/en/articles +{{ relLangURL "style.css" }} → /docs/en/style.css +{{ relLangURL "https://example.org" }} → https://example.org +{{ relLangURL "https://example.org/" }} → https://example.org/ +{{ relLangURL "https://example.org/docs" }} → https://example.org/docs +{{ relLangURL "https://example.org/docs/" }} → /docs/en +{{ relLangURL "https://www.example.org" }} → https://www.example.org +{{ relLangURL "https://www.example.org/" }} → https://www.example.org/ +``` + +## Input begins with a slash + - If the input begins with a slash, the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration. ++If the input begins with a slash, the resulting URL will be relative to the protocol+host of the `baseURL` in your project configuration. + +When rendering the `en` site with `baseURL = https://example.org/` + +```go-html-template +{{ relLangURL "/" }} → /en/ +{{ relLangURL "/articles" }} → /en/articles +{{ relLangURL "/style.css" }} → /en/style.css +``` + +When rendering the `en` site with `baseURL = https://example.org/docs/` + +```go-html-template +{{ relLangURL "/" }} → /en/ +{{ relLangURL "/articles" }} → /en/articles +{{ relLangURL "/style.css" }} → /en/style.css +``` + +> [!note] +> As illustrated by the previous example, using a leading slash is rarely desirable and can lead to unexpected outcomes. In nearly all cases, omit the leading slash. diff --cc docs/content/en/functions/urls/RelURL.md index 0aef4043f,000000000..97328eb2a mode 100644,000000..100644 --- a/docs/content/en/functions/urls/RelURL.md +++ b/docs/content/en/functions/urls/RelURL.md @@@ -1,72 -1,0 +1,72 @@@ +--- +title: urls.RelURL +description: Returns a relative URL. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [relURL] + returnType: string + signatures: [urls.RelURL INPUT] +aliases: [/functions/relurl] +--- + +With multilingual configurations, use the [`urls.RelLangURL`] function instead. The URL returned by this function depends on: + +- Whether the input begins with a slash (`/`) - - The `baseURL` in your site configuration ++- The `baseURL` in your project configuration + +## Input does not begin with a slash + - If the input does not begin with a slash, the resulting URL will be relative to the `baseURL` in your site configuration. ++If the input does not begin with a slash, the resulting URL will be relative to the `baseURL` in your project configuration. + +With `baseURL = https://example.org/` + +```go-html-template +{{ relURL "" }} → / +{{ relURL "articles" }} → /articles +{{ relURL "style.css" }} → /style.css +{{ relURL "https://example.org" }} → https://example.org +{{ relURL "https://example.org/" }} → / +{{ relURL "https://www.example.org" }} → https://www.example.org +{{ relURL "https://www.example.org/" }} → https://www.example.org/ +``` + +With `baseURL = https://example.org/docs/` + +```go-html-template +{{ relURL "" }} → /docs/ +{{ relURL "articles" }} → /docs/articles +{{ relURL "style.css" }} → /docs/style.css +{{ relURL "https://example.org" }} → https://example.org +{{ relURL "https://example.org/" }} → https://example.org/ +{{ relURL "https://example.org/docs" }} → https://example.org/docs +{{ relURL "https://example.org/docs/" }} → /docs +{{ relURL "https://www.example.org" }} → https://www.example.org +{{ relURL "https://www.example.org/" }} → https://www.example.org/ +``` + +## Input begins with a slash + - If the input begins with a slash, the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration. ++If the input begins with a slash, the resulting URL will be relative to the protocol+host of the `baseURL` in your project configuration. + +With `baseURL = https://example.org/` + +```go-html-template +{{ relURL "/" }} → / +{{ relURL "/articles" }} → /articles +{{ relURL "/style.css" }} → /style.css +``` + +With `baseURL = https://example.org/docs/` + +```go-html-template +{{ relURL "/" }} → / +{{ relURL "/articles" }} → /articles +{{ relURL "/style.css" }} → /style.css +``` + +> [!note] +> As illustrated by the previous example, using a leading slash is rarely desirable and can lead to unexpected outcomes. In nearly all cases, omit the leading slash. + +[`urls.RelLangURL`]: /functions/urls/rellangurl/ diff --cc docs/content/en/functions/urls/URLize.md index b0cc812ec,000000000..28bc1dc47 mode 100644,000000..100644 --- a/docs/content/en/functions/urls/URLize.md +++ b/docs/content/en/functions/urls/URLize.md @@@ -1,61 -1,0 +1,61 @@@ +--- +title: urls.URLize +description: Returns the given string, sanitized for usage in a URL. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [urlize] + returnType: string + signatures: [urls.URLize INPUT] +aliases: [/functions/urlize] +--- + +{{% include "/_common/functions/urls/anchorize-vs-urlize.md" %}} + +## Example + +Use the `urlize` function to create a link to a [term page](g). + - Consider this site configuration: ++Consider this project configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +author = 'authors' +{{< /code-toggle >}} + +And this front matter: + +{{< code-toggle file=content/books/les-miserables.md fm=true >}} +title = 'Les Misérables' +authors = ['Victor Hugo'] +{{< /code-toggle >}} + +The published site will have this structure: + +```text +public/ +├── authors/ +│ ├── victor-hugo/ +│ │ └── index.html +│ └── index.html +├── books/ +│ ├── les-miserables/ +│ │ └── index.html +│ └── index.html +└── index.html +``` + +To create a link to the term page: + +```go-html-template +{{ $taxonomy := "authors" }} +{{ $term := "Victor Hugo" }} +{{ with index .Site.Taxonomies $taxonomy (urlize $term) }} + {{ .Page.LinkTitle }} +{{ end }} +``` + +To generate a list of term pages associated with a given content page, use the [`GetTerms`] method on a `Page` object. + +[`GetTerms`]: /methods/page/getterms/ diff --cc docs/content/en/getting-started/directory-structure.md index d01822c96,000000000..863775d99 mode 100644,000000..100644 --- a/docs/content/en/getting-started/directory-structure.md +++ b/docs/content/en/getting-started/directory-structure.md @@@ -1,204 -1,0 +1,204 @@@ +--- +title: Directory structure +description: An overview of Hugo's directory structure. +categories: [] +keywords: [] +weight: 30 +aliases: [/overview/source-directory/] +--- + - Each Hugo project is a directory, with subdirectories that contribute to the content, structure, behavior, and presentation of your site. ++Each Hugo project is a directory, with subdirectories that contribute to content, structure, behavior, and presentation. + - ## Site skeleton ++## Project skeleton + - Hugo generates a project skeleton when you create a new site. For example, this command: ++Hugo generates a project skeleton when you create a new project. For example, this command: + +```sh - hugo new site my-site ++hugo new project my-project +``` + +Creates this directory structure: + +```txt - my-site/ ++my-project/ +├── archetypes/ +│ └── default.md +├── assets/ +├── content/ +├── data/ +├── i18n/ +├── layouts/ +├── static/ +├── themes/ - └── hugo.toml <-- site configuration ++└── hugo.toml <-- project configuration +``` + - Depending on requirements, you may wish to organize your site configuration into subdirectories: ++Depending on requirements, you may wish to organize your project configuration into subdirectories: + +```txt - my-site/ ++my-project/ +├── archetypes/ +│ └── default.md +├── assets/ - ├── config/ <-- site configuration ++├── config/ <-- project configuration +│ └── _default/ +│ └── hugo.toml +├── content/ +├── data/ +├── i18n/ +├── layouts/ +├── static/ +└── themes/ +``` + - When you build your site, Hugo creates a `public` directory, and typically a `resources` directory as well: ++When you build your project, Hugo creates a `public` directory, and typically a `resources` directory as well: + +```txt - my-site/ ++my-project/ +├── archetypes/ +│ └── default.md +├── assets/ +├── config/ +│ └── _default/ +│ └── hugo.toml +├── content/ +├── data/ +├── i18n/ +├── layouts/ - ├── public/ <-- created when you build your site - ├── resources/ <-- created when you build your site ++├── public/ <-- created when you build your project ++├── resources/ <-- created when you build your project +├── static/ +└── themes/ +``` + +## Directories + - Each of the subdirectories contributes to the content, structure, behavior, or presentation of your site. ++Each of the subdirectories contributes to content, structure, behavior, or presentation. + +archetypes +: The `archetypes` directory contains templates for new content. See [details](/content-management/archetypes/). + +assets +: The `assets` directory contains global resources typically passed through an asset pipeline. This includes resources such as images, CSS, Sass, JavaScript, and TypeScript. See [details](/hugo-pipes/introduction/). + +config - : The `config` directory contains your site configuration, possibly split into multiple subdirectories and files. For projects with minimal configuration or projects that do not need to behave differently in different environments, a single configuration file named `hugo.toml` in the root of the project is sufficient. See [details](/configuration/introduction/#configuration-directory). ++: The `config` directory contains your project configuration, possibly split into multiple subdirectories and files. For projects with minimal configuration or projects that do not need to behave differently in different environments, a single configuration file named `hugo.toml` in the root of the project is sufficient. See [details](/configuration/introduction/#configuration-directory). + +content - : The `content` directory contains the markup files (typically Markdown) and page resources that comprise the content of your site. See [details](/content-management/organization/). ++: The `content` directory contains the markup files (typically Markdown) and page resources that comprise the content of your project. See [details](/content-management/organization/). + +data +: The `data` directory contains data files (JSON, TOML, YAML, or XML) that augment content, configuration, localization, and navigation. See [details](/content-management/data-sources/). + +i18n - : The `i18n` directory contains translation tables for multilingual sites. See [details](/content-management/multilingual/). ++: The `i18n` directory contains translation tables for multilingual projects. See [details](/content-management/multilingual/). + +layouts +: The `layouts` directory contains templates to transform content, data, and resources into a complete website. See [details](/templates/). + +public - : The `public` directory contains the published website, generated when you run the `hugo` or `hugo server` commands. Hugo recreates this directory and its content as needed. See [details](/getting-started/usage/#build-your-site). ++: The `public` directory contains the published website, generated when you run the `hugo build` or `hugo server` commands. Hugo recreates this directory and its content as needed. See [details](/getting-started/usage/#build-your-project). + +resources - : The `resources` directory contains cached output from Hugo's asset pipelines, generated when you run the `hugo` or `hugo server` commands. By default this cache directory includes CSS and images. Hugo recreates this directory and its content as needed. ++: The `resources` directory contains cached output from Hugo's asset pipelines, generated when you run the `hugo build` or `hugo server` commands. By default this cache directory includes CSS and images. Hugo recreates this directory and its content as needed. + +static - : The `static` directory contains files that will be copied to the `public` directory when you build your site. For example: `favicon.ico`, `robots.txt`, and files that verify site ownership. Before the introduction of [page bundles](g) and [asset pipelines](/hugo-pipes/introduction/), the `static` directory was also used for images, CSS, and JavaScript. ++: The `static` directory contains files that will be copied to the `public` directory when you build your project. For example: `favicon.ico`, `robots.txt`, and files that verify website ownership. Before the introduction of [page bundles](g) and [asset pipelines](/hugo-pipes/introduction/), the `static` directory was also used for images, CSS, and JavaScript. + +themes +: The `themes` directory contains one or more [themes](g), each in its own subdirectory. + +## Union file system + +Hugo creates a union file system, allowing you to mount two or more directories to the same location. For example, let's say your home directory contains a Hugo project in one directory, and shared content in another: + +```text +home/ +└── user/ - ├── my-site/ ++ ├── my-project/ + │ ├── content/ + │ │ ├── books/ + │ │ │ ├── _index.md + │ │ │ ├── book-1.md + │ │ │ └── book-2.md + │ │ └── _index.md + │ ├── themes/ + │ │ └── my-theme/ + │ └── hugo.toml + └── shared-content/ + └── films/ + ├── _index.md + ├── film-1.md + └── film-2.md +``` + - You can include the shared content when you build your site using mounts. In your site configuration: ++You can include the shared content using mounts. In your project configuration: + +{{< code-toggle file=hugo >}} +[[module.mounts]] +source = 'content' +target = 'content' + +[[module.mounts]] +source = '/home/user/shared-content' +target = 'content' +{{< /code-toggle >}} + +> [!note] +> When you overlay one directory on top of another, you must mount both directories. +> +> Hugo does not follow symbolic links. If you need the functionality provided by symbolic links, use Hugo's union file system instead. + +After mounting, the union file system has this structure: + +```text +home/ +└── user/ - └── my-site/ ++ └── my-project/ + ├── content/ + │ ├── books/ + │ │ ├── _index.md + │ │ ├── book-1.md + │ │ └── book-2.md + │ ├── films/ + │ │ ├── _index.md + │ │ ├── film-1.md + │ │ └── film-2.md + │ └── _index.md + ├── themes/ + │ └── my-theme/ + └── hugo.toml +``` + +> [!note] +> When two or more files have the same path, the order of precedence follows the order of the mounts. For example, if the shared content directory contains `books/book-1.md`, it will be ignored because the project's `content` directory was mounted first. + +You can mount directories to `archetypes`, `assets`, `content`, `data`, `i18n`, `layouts`, and `static`. See [details](/configuration/module/#mounts). + +You can also mount directories from Git repositories using Hugo Modules. See [details](/hugo-modules/). + +## Theme skeleton + +Hugo generates a functional theme skeleton when you create a new theme. For example, this command: + +```text +hugo new theme my-theme +``` + +Creates this directory structure (subdirectories not shown): + +```text +my-theme/ +├── archetypes/ +├── assets/ +├── content/ +├── data/ +├── i18n/ +├── layouts/ +├── static/ +└── hugo.toml +``` + +Using the union file system described above, Hugo mounts each of these directories to the corresponding location in the project. When two files have the same path, the file in the project directory takes precedence. This allows you, for example, to override a theme's template by placing a copy in the same location within the project directory. + +If you are simultaneously using components from two or more themes or modules, and there's a path collision, the first mount takes precedence. diff --cc docs/content/en/getting-started/quick-start.md index cc800181c,000000000..3d05333ba mode 100644,000000..100644 --- a/docs/content/en/getting-started/quick-start.md +++ b/docs/content/en/getting-started/quick-start.md @@@ -1,218 -1,0 +1,216 @@@ +--- +title: Quick start - description: Create a Hugo site in minutes. ++description: Create your first Hugo project. +categories: [] +keywords: [] +params: - minVersion: v0.146.0 ++ minVersion: v0.156.0 +weight: 10 +aliases: [/quickstart/,/overview/quickstart/] +--- + +In this tutorial you will: + - 1. Create a site ++1. Create a project +1. Add content - 1. Configure the site - 1. Publish the site ++1. Configure the project ++1. Publish the project + +## Prerequisites + +Before you begin this tutorial you must: + +1. [Install Hugo] (extended or extended/deploy edition, {{% param "minVersion" %}} or later) +1. [Install Git] + +You must also be comfortable working from the command line. + - ## Create a site ++## Create a project + +### Commands + +> [!note] +> **If you are a Windows user:** +> +> - Do not use the Command Prompt +> - Do not use Windows PowerShell - > - Run these commands from [PowerShell] or a Linux terminal such as WSL or Git > Bash ++> - Run these commands from [PowerShell][] or a Linux terminal such as WSL or Git > Bash +> - > PowerShell and Windows PowerShell [are different applications]. ++> PowerShell and Windows PowerShell [are different applications][]. + +Verify that you have installed Hugo {{% param "minVersion" %}} or later. + +```text +hugo version +``` + - Run these commands to create a Hugo site with the [Ananke] theme. The next section provides an explanation of each command. ++Run these commands to create a Hugo project with the [Ananke][] theme. The next section provides an explanation of each command. + +```text - hugo new site quickstart ++hugo new project quickstart +cd quickstart +git init +git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke +echo "theme = 'ananke'" >> hugo.toml +hugo server +``` + - View your site at the URL displayed in your terminal. Press `Ctrl + C` to stop Hugo's development server. ++View your project at the URL displayed in your terminal. Press `Ctrl + C` to stop Hugo's development server. + +### Explanation of commands + - Create the [site skeleton] for your project in the `quickstart` directory. ++Create the [project skeleton][] for your project in the `quickstart` directory. + +```text - hugo new site quickstart ++hugo new project quickstart +``` + +Change the current directory to the root of your project. + +```text +cd quickstart +``` + +Initialize an empty Git repository in the current directory. + +```text +git init +``` + - Clone the [Ananke] theme into the `themes` directory, adding it to your project as a [Git submodule]. ++Clone the [Ananke][] theme into the `themes` directory, adding it to your project as a [Git submodule][]. + +```text +git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke +``` + - Append a line to the site configuration file, indicating the current theme. ++Append a line to your project configuration file, indicating the current theme. + +```text +echo "theme = 'ananke'" >> hugo.toml +``` + - Start Hugo's development server to view the site. ++Start Hugo's development server. + +```text +hugo server +``` + +Press `Ctrl + C` to stop Hugo's development server. + +## Add content + - Add a new page to your site. ++Add a new page to your project. + +```text +hugo new content content/posts/my-first-post.md +``` + +Hugo created the file in the `content/posts` directory. Open the file with your editor. + +```text ++++ +title = 'My First Post' +date = 2024-01-14T07:07:07+01:00 +draft = true ++++ +``` + - Notice the `draft` value in the [front matter] is `true`. By default, Hugo does not publish draft content when you build the site. Learn more about [draft, future, and expired content]. ++Notice the `draft` value in the [front matter][] is `true`. By default, Hugo does not publish draft content when you build the project. Learn more about [draft, future, and expired content][]. + - Add some [Markdown] to the body of the post, but do not change the `draft` value. ++Add some [Markdown][] to the body of the post, but do not change the `draft` value. + +```text ++++ +title = 'My First Post' +date = 2024-01-14T07:07:07+01:00 +draft = true ++++ +## Introduction + +This is **bold** text, and this is *emphasized* text. + +Visit the [Hugo](https://gohugo.io) website! +``` + - Save the file, then start Hugo's development server to view the site. You can run either of the following commands to include draft content. ++Save the file, then start Hugo's development server. You can run either of the following commands to include draft content. + +```text +hugo server --buildDrafts +hugo server -D +``` + - View your site at the URL displayed in your terminal. Keep the development server running as you continue to add and change content. ++View your project at the URL displayed in your terminal. Keep the development server running as you continue to add and change content. + +When satisfied with your new content, set the front matter `draft` parameter to `false`. + +> [!note] - > Hugo's rendering engine conforms to the CommonMark [specification] for Markdown. The CommonMark organization provides a useful [live testing tool] powered by the reference implementation. ++> Hugo's rendering engine conforms to the CommonMark [specification][] for Markdown. The CommonMark organization provides a useful [live testing tool][] powered by the reference implementation. + - ## Configure the site ++## Configure the project + - With your editor, open the [site configuration] file (`hugo.toml`) in the root of your project. ++With your editor, open your [project configuration][] file (`hugo.toml`) in the root of your project. + +```text +baseURL = 'https://example.org/' +languageCode = 'en-us' - title = 'My New Hugo Site' ++title = 'My New Hugo Project' +theme = 'ananke' +``` + +Make the following changes: + - 1. Set the `baseURL` for your production site. This value must begin with the protocol and end with a slash, as shown above. - 1. Set the `languageCode` to your language and region. - 1. Set the `title` for your production site. ++1. Set the `baseURL` for your project. This value must begin with the protocol and end with a slash, as shown above. ++1. Set the `languageCode` to your locale. ++1. Set the `title` for your project. + +Start Hugo's development server to see your changes, remembering to include draft content. + +```text +hugo server -D +``` + +> [!note] +> Most theme authors provide configuration guidelines and options. Make sure to visit your theme's repository or documentation site for details. +> - > [The New Dynamic], authors of the Ananke theme, provide [documentation] for configuration and usage. They also provide a [demonstration site]. ++> [The New Dynamic][], authors of the Ananke theme, provide [documentation][] for configuration and usage. They also provide a [demonstration site][]. + - ## Publish the site ++## Publish the project + - In this step you will _publish_ your site, but you will not _deploy_ it. ++In this step you will _publish_ your project, but you will not _deploy_ it. + - When you _publish_ your site, Hugo creates the entire static site in the `public` directory in the root of your project. This includes the HTML files, and assets such as images, CSS files, and JavaScript files. - - When you publish your site, you typically do _not_ want to include [draft, future, or expired content]. The command is simple. ++When you publish your project, Hugo renders all build artifacts to the `public` directory in the root of your project. This includes the HTML files for every site, along with assets such as images, CSS, and JavaScript. The command is simple. + +```text +hugo +``` + - To learn how to _deploy_ your site, see the [host and deploy] section. ++To learn how to _deploy_ your project, see the [host and deploy][] section. + +## Ask for help + - Hugo's [forum] is an active community of users and developers who answer questions, share knowledge, and provide examples. A quick search of over 20,000 topics will often answer your question. Please be sure to read about [requesting help] before asking your first question. ++Hugo's [forum][] is an active community of users and developers who answer questions, share knowledge, and provide examples. A quick search of over 20,000 topics will often answer your question. Please be sure to read about [requesting help] before asking your first question. + +## Other resources + - For other resources to help you learn Hugo, including books and video tutorials, see the [external learning resources](/getting-started/external-learning-resources/) page. ++For other resources to help you learn Hugo, including books and video tutorials, see the [external learning resources][] page. + +[Ananke]: https://github.com/theNewDynamic/gohugo-theme-ananke +[are different applications]: https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.3 +[demonstration site]: https://gohugo-ananke-theme-demo.netlify.app/ - [site skeleton]: /getting-started/directory-structure/#site-skeleton +[documentation]: https://github.com/theNewDynamic/gohugo-theme-ananke#readme +[draft, future, and expired content]: /getting-started/usage/#draft-future-and-expired-content - [draft, future, or expired content]: /getting-started/usage/#draft-future-and-expired-content ++[external learning resources]: /getting-started/external-learning-resources/ +[forum]: https://discourse.gohugo.io/ +[front matter]: /content-management/front-matter/ +[Git submodule]: https://git-scm.com/book/en/v2/Git-Tools-Submodules +[host and deploy]: /host-and-deploy/ +[Install Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[Install Hugo]: /installation/ +[live testing tool]: https://spec.commonmark.org/dingus/ +[Markdown]: https://daringfireball.net/projects/markdown +[PowerShell]: https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows ++[project configuration]: /configuration/ ++[project skeleton]: /getting-started/directory-structure/#project-skeleton +[requesting help]: https://discourse.gohugo.io/t/requesting-help/9132 - [site configuration]: /configuration/ +[specification]: https://spec.commonmark.org/ +[The New Dynamic]: https://www.thenewdynamic.com/ diff --cc docs/content/en/getting-started/usage.md index cc43c0cf0,000000000..41c703bfb mode 100644,000000..100644 --- a/docs/content/en/getting-started/usage.md +++ b/docs/content/en/getting-started/usage.md @@@ -1,156 -1,0 +1,156 @@@ +--- +title: Basic usage +description: Use the command-line interface (CLI) to perform basic tasks. +categories: [] +keywords: [] +weight: 20 +aliases: [/overview/usage/,/extras/livereload/,/doc/usage/,/usage/] +--- + +## Test your installation + +After [installing] Hugo, test your installation by running: + +```sh +hugo version +``` + +You should see something like: + +```text +hugo v0.155.3-8a858213b73907e823e2be2b5640a0ce4c04d295+extended linux/amd64 BuildDate=2026-02-08T16:40:42Z VendorInfo=gohugoio +``` + +## Display available commands + +To see a list of the available commands and flags: + +```sh +hugo help +``` + +To get help with a subcommand, use the `--help` flag. For example: + +```sh +hugo server --help +``` + - ## Build your site ++## Build your project + - To build your site, `cd` into your project directory and run: ++To build your project, `cd` into your project directory and run: + +```sh - hugo ++hugo build +``` + - The [`hugo`] command builds your site, publishing the files to the `public` directory. To publish your site to a different directory, use the [`--destination`] flag or set [`publishDir`] in your site configuration. ++The [`hugo build`] command builds your project, publishing the files to the `public` directory. To publish your project to a different directory, use the [`--destination`] flag or set [`publishDir`] in your project configuration. + +> [!note] - > Hugo does not clear the `public` directory before building your site. Existing files are overwritten, but not deleted. This behavior is intentional to prevent the inadvertent removal of files that you may have added to the `public` directory after the build. ++> Hugo does not clear the `public` directory before building your project. Existing files are overwritten, but not deleted. This behavior is intentional to prevent the inadvertent removal of files that you may have added to the `public` directory after the build. +> +> Depending on your needs, you may wish to manually clear the contents of the `public` directory before every build. + +## Draft, future, and expired content + +Hugo allows you to set `draft`, `date`, `publishDate`, and `expiryDate` in the [front matter] of your content. By default, Hugo will not publish content when: + +- The `draft` value is `true` +- The `date` is in the future +- The `publishDate` is in the future +- The `expiryDate` is in the past + +> [!note] +> Hugo publishes descendants of draft, future, and expired [node](g) pages. To prevent publication of these descendants, use the [`cascade`] front matter field to cascade [build options] to the descendant pages. + - You can override the default behavior when running `hugo` or `hugo server` with command line flags: ++You can override the default behavior when running `hugo build` or `hugo server` with command line flags: + +```sh - hugo --buildDrafts # or -D - hugo --buildExpired # or -E - hugo --buildFuture # or -F ++hugo build --buildDrafts # or -D ++hugo build --buildExpired # or -E ++hugo build --buildFuture # or -F +``` + - Although you can also set these values in your site configuration, it can lead to unwanted results unless all content authors are aware of, and understand, the settings. ++Although you can also set these values in your project configuration, it can lead to unwanted results unless all content authors are aware of, and understand, the settings. + +> [!note] - > As noted above, Hugo does not clear the `public` directory before building your site. Depending on the _current_ evaluation of the four conditions above, after the build your `public` directory may contain extraneous files from a previous build. ++> As noted above, Hugo does not clear the `public` directory before building your project. Depending on the _current_ evaluation of the four conditions above, after the build your `public` directory may contain extraneous files from a previous build. +> +> A common practice is to manually clear the contents of the `public` directory before each build to remove draft, expired, and future content. + +## Develop and test your site + +To view your site while developing layouts or creating content, `cd` into your project directory and run: + +```sh +hugo server +``` + +The [`hugo server`] command builds your site and serves your pages using a minimal HTTP server. When you run `hugo server` it will display the URL of your local site: + +```text +Web Server is available at http://localhost:1313/ +``` + +While the server is running, it watches your project directory for changes to assets, configuration, content, data, layouts, translations, and static files. When it detects a change, the server rebuilds your site and refreshes your browser using [LiveReload]. + +Most Hugo builds are so fast that you may not notice the change unless you are looking directly at your browser. + +### LiveReload + +While the server is running, Hugo injects JavaScript into the generated HTML pages. The LiveReload script creates a connection from the browser to the server via web sockets. You do not need to install any software or browser plugins, nor is any configuration required. + +### Automatic redirection + +When editing content, if you want your browser to automatically redirect to the page you last modified, run: + +```sh +hugo server --navigateToChanged +``` + +## Deploy your site + +> [!note] - > As noted above, Hugo does not clear the `public` directory before building your site. Manually clear the contents of the `public` directory before each build to remove draft, expired, and future content. ++> As noted above, Hugo does not clear the `public` directory before building your project. Manually clear the contents of the `public` directory before each build to remove draft, expired, and future content. + +When you are ready to deploy your site, run: + +```sh +hugo +``` + +This builds your site, publishing the files to the `public` directory. The directory structure will look something like this: + +```text +public/ +├── categories/ +│ ├── index.html +│ └── index.xml <-- RSS feed for this section +├── posts/ +│ ├── my-first-post/ +│ │ └── index.html +│ ├── index.html +│ └── index.xml <-- RSS feed for this section +├── tags/ +│ ├── index.html +│ └── index.xml <-- RSS feed for this section +├── index.html +├── index.xml <-- RSS feed for the site +└── sitemap.xml +``` + +In a simple hosting environment, where you typically `ftp`, `rsync`, or `scp` your files to the root of a virtual host, the contents of the `public` directory are all that you need. + +Most of our users deploy their sites to a [CI/CD](g) platform, where a push[^1] to their remote Git repository triggers a build and deployment. Learn more in the [host and deploy] section. + +[^1]: The Git repository contains the entire project directory, typically excluding the `public` directory because the site is built _after_ the push. + +[`--destination`]: /commands/hugo/#options +[`cascade`]: /content-management/front-matter/#cascade +[`hugo server`]: /commands/hugo_server/ - [`hugo`]: /commands/hugo/ ++[`hugo build`]: /commands/hugo/ +[`publishDir`]: /configuration/all/#publishdir +[build options]: /content-management/build-options/ +[front matter]: /content-management/front-matter/ +[host and deploy]: /host-and-deploy/ +[installing]: /installation/ +[LiveReload]: https://github.com/livereload/livereload-js diff --cc docs/content/en/host-and-deploy/deploy-with-hugo-deploy.md index 8feeccbae,000000000..6dae734c4 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/deploy-with-hugo-deploy.md +++ b/docs/content/en/host-and-deploy/deploy-with-hugo-deploy.md @@@ -1,97 -1,0 +1,97 @@@ +--- +title: Deploy with hugo +description: Deploy your site with the hugo CLI. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hugo-deploy/] +--- + +Use the `hugo deploy` command to deploy your site Amazon S3, Azure Blob Storage, or Google Cloud Storage. + +> [!note] +> This feature requires the Hugo extended/deploy edition. See the [installation] section for details. + +## Assumptions + +1. You have completed the [Quick Start] or have a Hugo website you are ready to deploy and share with the world. +1. You have an account with the service provider ([AWS], [Azure], or [Google Cloud]) that you want to deploy to. +1. You have authenticated. + - AWS: [Install the CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and run [`aws configure`](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). + - Azure: [Install the CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) and run [`az login`](https://docs.microsoft.com/en-us/cli/azure/authenticate-azure-cli). + - Google Cloud: [Install the CLI](https://cloud.google.com/sdk) and run [`gcloud auth login`](https://cloud.google.com/sdk/gcloud/reference/auth/login). + + Each service supports various authentication methods, including environment variables. See [details](https://gocloud.dev/howto/blob/#services). + +1. You have created a bucket to deploy to. If you want your site to be + public, be sure to configure the bucket to be publicly readable as a static website. + - AWS: [create a bucket](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html) and [host a static website](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html) + - Azure: [create a storage container](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal) and [host a static website](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website) + + - Google Cloud: [create a bucket](https://cloud.google.com/storage/docs/creating-buckets) and [host a static website](https://cloud.google.com/storage/docs/hosting-static-website) + +## Configuration + - Create a deployment target in your [site configuration]. The only required parameters are [`name`] and [`url`]: ++Create a deployment target in your [project configuration]. The only required parameters are [`name`] and [`url`]: + +{{< code-toggle file=hugo >}} +[deployment] + [[deployment.targets]] + name = 'production' + url = 's3://my_bucket?region=us-west-1' +{{< /code-toggle >}} + +## Deploy + +To deploy to a target: + - ```bash ++```sh +hugo deploy [--target=] +``` + +This command syncs the contents of your local `public` directory (the default publish directory) with the destination bucket. If no target is specified, Hugo deploys to the first configured target. + +For more command-line options, see `hugo help deploy` or the [CLI documentation]. + +### File list creation + +`hugo deploy` creates local and remote file lists by traversing the local publish directory and the remote bucket. Inclusion and exclusion are determined by the deployment target's [configuration]: + +- `include`: All files are skipped by default except those that match the pattern. +- `exclude`: Files matching the pattern are skipped. + +> [!note] +> During local file list creation, Hugo skips `.DS_Store` files and hidden directories (those starting with a period, like `.git`), except for the [`.well-known`] directory, which is traversed if present. + +### File list comparison + +Hugo compares the local and remote file lists to identify necessary changes. It first compares file names. If both exist, it compares sizes and MD5 checksums. Any difference triggers a re-upload, and remote files not present locally are deleted. + +> [!note] +> Excluded remote files (due to `include`/`exclude` configuration) won't be deleted. + +The `--force` flag forces all files to be re-uploaded, even if Hugo detects no local/remote differences. + +The `--confirm` or `--dryRun` flags cause Hugo to display the detected differences and then pause or stop. + +### Synchronization + +Hugo applies the changes to the remote bucket: uploading missing or changed files and deleting remote files not present locally. Uploaded file headers are configured remotely based on the matchers configuration. + +> [!note] +> To prevent accidental data loss, Hugo will not delete more than 256 remote files by default. Use the `--maxDeletes` flag to override this limit. + +## Advanced configuration + +See [configure deployment](/configuration/deployment/). + +[`.well-known`]: https://en.wikipedia.org/wiki/Well-known_URI +[`name`]: /configuration/deployment/#name +[`url`]: /configuration/deployment/#url +[AWS]: https://aws.amazon.com +[Azure]: https://azure.microsoft.com +[CLI documentation]: /commands/hugo_deploy/ +[configuration]: /configuration/deployment/#targets-1 +[Google Cloud]: https://cloud.google.com/ +[installation]: /installation/ +[Quick Start]: /getting-started/quick-start/ - [site configuration]: /configuration/deployment/ ++[project configuration]: /configuration/deployment/ diff --cc docs/content/en/host-and-deploy/deploy-with-rclone.md index 8f641bc5d,000000000..b5e898d83 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/deploy-with-rclone.md +++ b/docs/content/en/host-and-deploy/deploy-with-rclone.md @@@ -1,43 -1,0 +1,43 @@@ +--- +title: Deploy with rclone +description: Deploy your site with the rclone CLI. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/deployment-with-rclone/] +--- + +## Assumptions + +- A web host running a web server. This could be a shared hosting environment or a VPS. +- Access to your web host with any of the [protocols supported by rclone](https://rclone.org/#providers), such as SFTP. +- A functional static website built with Hugo +- Deploying from an [Rclone](https://rclone.org) compatible operating system +- You have [installed Rclone](https://rclone.org/install/). + - **NB**: You can remove ``--interactive`` in the commands below once you are comfortable with rclone, if you wish. Also, ``--gc`` and ``--minify`` are optional in the ``hugo`` commands below. ++**NB**: You can remove `--interactive` in the commands below once you are comfortable with rclone, if you wish. Also, `--gc` and `--minify` are optional in the commands below. + +## Getting started + +The spoiler is that you can even deploy your entire website from any compatible OS with no configuration. Using SFTP for example: + +```txt - hugo --gc --minify ++hugo build --gc --minify +rclone sync --interactive --sftp-host sftp.example.com --sftp-user www-data --sftp-ask-password public/ :sftp:www/ +``` + +## Configure Rclone for even easier usage + +The easiest way is simply to run `rclone config`. + +The [Rclone docs](https://rclone.org/docs/) provide [an example of configuring Rclone to use SFTP](https://rclone.org/sftp/). + - For the next commands, we will assume you configured a remote you named ``hugo-www`` ++For the next commands, we will assume you configured a remote you named `hugo-www`. + +The above 'spoiler' commands could become: + +```txt - hugo --gc --minify ++hugo build --gc --minify +rclone sync --interactive public/ hugo-www:www/ +``` + +After you issue the above commands (and respond to any prompts), check your website and you will see that it is deployed. diff --cc docs/content/en/host-and-deploy/deploy-with-rsync.md index 0ad64d6fb,000000000..1c0967ba9 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/deploy-with-rsync.md +++ b/docs/content/en/host-and-deploy/deploy-with-rsync.md @@@ -1,135 -1,0 +1,135 @@@ +--- +title: Deploy with rsync +description: Deploy your site with the rsync CLI. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/deployment-with-rsync/] +--- + +## Assumptions + +- A web host running a web server. This could be a shared hosting environment or a VPS. +- Access to your web host with SSH +- A functional static website built with Hugo + +The spoiler is that you can deploy your entire website with a command that looks like the following: + +```txt +hugo && rsync -avz --delete public/ www-data@ftp.topologix.fr:~/www/ +``` + +As you will see, we'll put this command in a shell script file, which makes building and deployment as easy as executing `./deploy`. + +## Copy Your SSH Key to your host + +To make logging in to your server more secure and less interactive, you can upload your SSH key. If you have already installed your SSH key to your server, you can move on to the next section. + +First, install the ssh client. On Debian distributions, use the following command: + +```sh {file="install-openssh.sh"} +sudo apt-get install openssh-client +``` + +Then generate your ssh key. First, create the `.ssh` directory in your home directory if it doesn't exist: + +```txt +~$ cd && mkdir .ssh & cd .ssh +``` + +Next, execute this command to generate a new keypair called `rsa_id`: + +```txt +~/.ssh/$ ssh-keygen -t rsa -q -C "For SSH" -f rsa_id +``` + +You'll be prompted for a passphrase, which is an extra layer of protection. Enter the passphrase you'd like to use, and then enter it again when prompted, or leave it blank if you don't want to have a passphrase. Not using a passphrase will let you transfer files non-interactively, as you won't be prompted for a password when you log in, but it is slightly less secure. + +To make logging in easier, add a definition for your web host to the file `~/.ssh/config` with the following command, replacing `HOST` with the IP address or hostname of your web host, and `USER` with the username you use to log in to your web host when transferring files: + +```txt +~/.ssh/$ cat >> config <. + +Don't forget to update your static pages before push! + +## Manual deploy + +To deploy your Hugo site, execute the `firebase deploy` command, and your site will be up in no time: + +```sh +hugo && firebase deploy +``` + +## CI setup (other tools) + +You can generate a deploy token using + +```sh +firebase login:ci +``` + +You can also set up your CI and add the token to a private variable like `$FIREBASE_DEPLOY_TOKEN`. + +> [!note] +> This is a private secret and it should not appear in a public repository. Make sure you understand your chosen CI and that it's not visible to others. + +You can then add a step in your build to do the deployment using the token: + +```sh +firebase deploy --token $FIREBASE_DEPLOY_TOKEN +``` + +## Reference links + +- [Firebase CLI Reference](https://firebase.google.com/docs/cli/#administrative_commands) + +[console]: https://console.firebase.google.com/ +[Quick Start]: /getting-started/quick-start/ +[signup]: https://console.firebase.google.com/ diff --cc docs/content/en/host-and-deploy/host-on-github-pages/index.md index 5e900cffe,000000000..2ead348ee mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-github-pages/index.md +++ b/docs/content/en/host-and-deploy/host-on-github-pages/index.md @@@ -1,208 -1,0 +1,208 @@@ +--- +title: Host on GitHub Pages +description: Host your site on GitHub Pages. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hosting-on-github/] +--- + +## Types of sites + +There are three types of GitHub Pages sites: project, user, and organization. Project sites are connected to a specific project hosted on GitHub. User and organization sites are connected to a specific account on GitHub.com. + +> [!note] +> See the [GitHub Pages documentation] to understand the requirements for repository ownership and naming. + +## Prerequisites + +Please complete the following tasks before continuing: + +1. [Create](https://github.com/signup) a GitHub account +1. [Log in](https://github.com/login) to your GitHub account +1. [Create](https://github.com/new) a GitHub repository for your project +1. [Create](https://git-scm.com/docs/git-init) a local Git repository for your project with a [remote](https://git-scm.com/docs/git-remote) reference to your GitHub repository +1. Create a Hugo site within your local Git repository and test it with the `hugo server` command +1. Commit the changes to your local Git repository and push to your GitHub repository + +## Procedure + +Step 1 +: Visit your GitHub repository. From the main menu choose **Settings** > **Pages**. In the center of your screen you will see this: + + ![screen capture](gh-pages-01.png) + + Change the **Source** to `GitHub Actions`. The change is immediate; you do not have to press a Save button. + + ![screen capture](gh-pages-02.png) + +Step 2 - : In your site configuration, change the location of the image cache to the [`cacheDir`] as shown below: ++: In your project configuration, change the location of the image cache to the [`cacheDir`] as shown below: + + {{< code-toggle file=hugo copy=true >}} + [caches.images] + dir = ":cacheDir/images" + {{< /code-toggle >}} + + See [configure file caches] for more information. + +Step 3 +: Create a file named `hugo.yaml` in a directory named `.github/workflows`. + + ```text + mkdir -p .github/workflows + touch .github/workflows/hugo.yaml + ``` + +Step 4 +: Copy and paste the YAML below into the file you created. + + ```yaml {file=".github/workflows/hugo.yaml" copy=true} + name: Build and deploy + on: + push: + branches: + - main + workflow_dispatch: + permissions: + contents: read + pages: write + id-token: write + concurrency: + group: pages + cancel-in-progress: false + defaults: + run: + shell: bash + jobs: + build: + runs-on: ubuntu-latest + env: + DART_SASS_VERSION: 1.97.3 - GO_VERSION: 1.25.6 - HUGO_VERSION: 0.155.3 - NODE_VERSION: 24.13.0 ++ GO_VERSION: 1.26.0 ++ HUGO_VERSION: 0.156.0 ++ NODE_VERSION: 24.13.1 + TZ: Europe/Oslo + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + submodules: recursive + fetch-depth: 0 + - name: Setup Go + uses: actions/setup-go@v6 + with: + go-version: ${{ env.GO_VERSION }} + cache: false + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Setup Pages + id: pages + uses: actions/configure-pages@v5 + - name: Create directory for user-specific executable files + run: | + mkdir -p "${HOME}/.local" + - name: Install Dart Sass + run: | + curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + echo "${HOME}/.local/dart-sass" >> "${GITHUB_PATH}" + - name: Install Hugo + run: | + curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + mkdir "${HOME}/.local/hugo" + tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + echo "${HOME}/.local/hugo" >> "${GITHUB_PATH}" + - name: Verify installations + run: | + echo "Dart Sass: $(sass --version)" + echo "Go: $(go version)" + echo "Hugo: $(hugo version)" + echo "Node.js: $(node --version)" + - name: Install Node.js dependencies + run: | + [[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true + - name: Configure Git + run: | + git config core.quotepath false + - name: Cache restore + id: cache-restore + uses: actions/cache/restore@v5 + with: + path: ${{ runner.temp }}/hugo_cache + key: hugo-${{ github.run_id }} + restore-keys: + hugo- + - name: Build the site + run: | - hugo \ ++ hugo build \ + --gc \ + --minify \ + --baseURL "${{ steps.pages.outputs.base_url }}/" \ + --cacheDir "${{ runner.temp }}/hugo_cache" + - name: Cache save + id: cache-save + uses: actions/cache/save@v5 + with: + path: ${{ runner.temp }}/hugo_cache + key: ${{ steps.cache-restore.outputs.cache-primary-key }} + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: ./public + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + ``` + +Step 5 +: Commit the changes to your local Git repository and push to your GitHub repository. + +Step 6 +: From GitHub's main menu, choose **Actions**. You will see something like this: + + ![screen capture](gh-pages-03.png) + +Step 7 +: When GitHub has finished building and deploying your site, the color of the status indicator will change to green. + + ![screen capture](gh-pages-04.png) + +Step 8 +: Click on the commit message as shown above. Under the deploy step, you will see a link to your live site. + + ![screen capture](gh-pages-05.png) + +In the future, whenever you push a change from your local Git repository, GitHub Pages will rebuild and deploy your site. + +## Customize the workflow + +The example workflow above includes this step, which typically takes 10‑15 seconds: + +```yaml +- name: Install Dart Sass + run: sudo snap install dart-sass +``` + +You may remove this step if your site, themes, and modules do not transpile Sass to CSS using the [Dart Sass] transpiler. + +## Other resources + +- [Learn more about GitHub Actions](https://docs.github.com/en/actions) +- [Caching dependencies to speed up workflows](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows) +- [Manage a custom domain for your GitHub Pages site](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages) + +[`cacheDir`]: /configuration/all/#cachedir +[configure file caches]: /configuration/caches/ +[Dart Sass]: /functions/css/sass/#dart-sass +[GitHub Pages documentation]: https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages#types-of-github-pages-sites diff --cc docs/content/en/host-and-deploy/host-on-gitlab-pages.md index 46832909e,000000000..441c0b11f mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-gitlab-pages.md +++ b/docs/content/en/host-and-deploy/host-on-gitlab-pages.md @@@ -1,136 -1,0 +1,136 @@@ +--- +title: Host on GitLab Pages +description: Host your site on GitLab Pages. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hosting-on-gitlab/] +--- + +## Assumptions + +- Working familiarity with Git for version control +- Completion of the Hugo [Quick Start] +- A [GitLab account](https://gitlab.com/users/sign_in) +- A Hugo website on your local machine that you are ready to publish + +## BaseURL + - The `baseURL` in your [site configuration](/configuration/) must reflect the full URL of your GitLab pages repository if you are using the default GitLab Pages URL (e.g., `https://.gitlab.io//`) and not a custom domain. ++The `baseURL` in your [project configuration](/configuration/) must reflect the full URL of your GitLab pages repository if you are using the default GitLab Pages URL (e.g., `https://.gitlab.io//`) and not a custom domain. + +## Configure GitLab CI/CD + +Define your [CI/CD](g) jobs by creating a `.gitlab-ci.yml` file in the root of your project. + +```yaml {file=".gitlab-ci.yml" copy=true} +variables: + # Application versions + DART_SASS_VERSION: 1.97.3 - HUGO_VERSION: 0.155.3 - NODE_VERSION: 24.13.0 ++ HUGO_VERSION: 0.156.0 ++ NODE_VERSION: 24.13.1 + # Git + GIT_DEPTH: 0 + GIT_STRATEGY: clone + GIT_SUBMODULE_STRATEGY: recursive + # Time zone + TZ: Europe/Oslo + +image: - name: golang:1.25.6-bookworm ++ name: golang:1.26.0-bookworm + +pages: + stage: deploy + script: + # Create directory for user-specific executable files + - echo "Creating directory for user-specific executable files..." + - mkdir -p "${HOME}/.local" + + # Install utilities + - echo "Installing utilities..." + - apt-get update + - apt-get install -y brotli xz-utils zstd + + # Install Dart Sass + - echo "Installing Dart Sass ${DART_SASS_VERSION}..." + - curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + - tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + - rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + - export PATH="${HOME}/.local/dart-sass:${PATH}" + + # Install Hugo + - echo "Installing Hugo ${HUGO_VERSION}..." + - curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + - mkdir "${HOME}/.local/hugo" + - tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + - rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + - export PATH="${HOME}/.local/hugo:${PATH}" + + # Install Node.js + - echo "Installing Node.js ${NODE_VERSION}..." + - curl -sLJO "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" + - tar -C "${HOME}/.local" -xf "node-v${NODE_VERSION}-linux-x64.tar.xz" + - rm "node-v${NODE_VERSION}-linux-x64.tar.xz" + - export PATH="${HOME}/.local/node-v${NODE_VERSION}-linux-x64/bin:${PATH}" + + # Verify installations + - echo "Verifying installations..." + - "echo Dart Sass: $(sass --version)" + - "echo Go: $(go version)" + - "echo Hugo: $(hugo version)" + - "echo Node.js: $(node --version)" + - "echo brotli: $(brotli --version)" + - "echo xz: $(xz --version)" + - "echo zstd: $(zstd --version)" + + # Install Node.js dependencies + - echo "Installing Node.js dependencies..." + - "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci --prefer-offline || true" + + # Configure Git + - echo "Configuring Git..." + - git config core.quotepath false + + # Build site + - echo "Building site..." - - hugo --gc --minify --baseURL "${CI_PAGES_URL}" ++ - hugo build --gc --minify --baseURL "${CI_PAGES_URL}" + + # Compress published files + - echo "Compressing published files..." + - find public/ -type f -regextype posix-extended -regex '.+\.(css|html|js|json|mjs|svg|txt|xml)$' -print0 > files.txt + - time xargs --null --max-procs=0 --max-args=1 brotli --quality=10 --force --keep < files.txt + - time xargs --null --max-procs=0 --max-args=1 gzip -9 --force --keep < files.txt + artifacts: + paths: + - public + rules: + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH +``` + +## Push your Hugo website to GitLab + +Next, create a new repository on GitLab. It is not necessary to make the repository public. In addition, you might want to add `/public` to your .gitignore file, as there is no need to push compiled assets to GitLab or keep your output website in version control. + +```sh +# initialize new git repository +git init + +# add /public directory to our .gitignore file +echo "/public" >> .gitignore + +# commit and push code to master branch +git add . +git commit -m "Initial commit" +git remote add origin https://gitlab.com/YourUsername/your-hugo-site.git +git push -u origin master +``` + +## Wait for your page to build + +That's it! You can now follow the CI agent building your page at `https://gitlab.com///pipelines`. + +After the build has passed, your new website is available at `https://.gitlab.io//`. + +## Next steps + +GitLab supports using custom CNAME's and TLS certificates. For more details on GitLab Pages, see the [GitLab Pages setup documentation](https://about.gitlab.com/2016/04/07/gitlab-pages-setup/). + +[Quick Start]: /getting-started/quick-start/ diff --cc docs/content/en/host-and-deploy/host-on-netlify/index.md index fcca62b72,000000000..eb2eca4d4 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-netlify/index.md +++ b/docs/content/en/host-and-deploy/host-on-netlify/index.md @@@ -1,121 -1,0 +1,121 @@@ +--- +title: Host on Netlify +description: Host your site on Netlify. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hosting-on-netlify/] +--- + +Use these instructions to enable continuous deployment from a GitHub repository. The same general steps apply if you are using Azure DevOps, Bitbucket, or GitLab for version control. + +## Prerequisites + +Please complete the following tasks before continuing: + +1. [Create](https://app.netlify.com/signup) a Netlify account +1. [Log in](https://app.netlify.com/login) to your Netlify account +1. [Create](https://github.com/signup) a GitHub account +1. [Log in](https://github.com/login) to your GitHub account +1. [Create](https://github.com/new) a GitHub repository for your project +1. [Create](https://git-scm.com/docs/git-init) a local Git repository for your project with a [remote](https://git-scm.com/docs/git-remote) reference to your GitHub repository +1. Create a Hugo site within your local Git repository and test it with the `hugo server` command +1. Commit the changes to your local Git repository and push to your GitHub repository. + +## Procedure + + + +Step 1 +: Create a `netlify.toml` file in the root of your project. + + ```text {file="netlify.toml" copy=true} + [build.environment] + DART_SASS_VERSION = "1.97.3" - GO_VERSION = "1.25.6" - HUGO_VERSION = "0.155.3" - NODE_VERSION = "24.13.0" ++ GO_VERSION = "1.26.0" ++ HUGO_VERSION = "0.156.0" ++ NODE_VERSION = "24.13.1" + TZ = "Europe/Oslo" + + [build] + publish = "public" + command = """\ + git config core.quotepath false && \ - hugo --gc --minify --baseURL "${URL}" ++ hugo build --gc --minify --baseURL "${URL}" + """ + ``` + + If your site requires Dart Sass to transpile Sass to CSS, set the `DART_SASS_VERSION` and include the Dart Sass installation in the build step. + + ```text {file="netlify.toml" copy=true} + [build.environment] + DART_SASS_VERSION = "1.97.3" - GO_VERSION = "1.25.6" - HUGO_VERSION = "0.155.3" - NODE_VERSION = "24.13.0" ++ GO_VERSION = "1.26.0" ++ HUGO_VERSION = "0.156.0" ++ NODE_VERSION = "24.13.1" + TZ = "Europe/Oslo" + + [build] + publish = "public" + command = """\ + curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" && \ + tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" && \ + rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" && \ + export PATH="${HOME}/.local/dart-sass:${PATH}" && \ + git config core.quotepath false && \ - hugo --gc --minify --baseURL "${URL}" ++ hugo build --gc --minify --baseURL "${URL}" + """ + ``` + +Step 2 +: Commit the changes to your local Git repository and push to your GitHub repository. + +Step 3 +: In the upper right corner of the Netlify dashboard, press the **Add new project** button and select “Import an existing project". + + ![screen capture](netlify-01.png) + +Step 4 +: Connect to GitHub. + + ![screen capture](netlify-02.png) + +Step 5 +: Press the "Authorize Netlify" button to allow the Netlify application to access your GitHub account. + + ![screen capture](netlify-03.png) + +Step 6 +: Press the **Configure Netlify on GitHub** button. + + ![screen capture](netlify-04.png) + +Step 7 +: Select the GitHub account where you want to install the Netlify application. + + ![screen capture](netlify-05.png) + +Step 8 +: Authorize the Netlify application to access all repositories or only select repositories, then press the Install button. + + ![screen capture](netlify-06.png) + +Your browser will be redirected to the Netlify dashboard. + +Step 9 +: Click on the name of the repository you wish to import. + + ![screen capture](netlify-07.png) + +Step 10 +: On the "Review configuration" page, enter a project name, leave the settings at their default values, then press the **Deploy** button. + + ![screen capture](netlify-08.png) + + ![screen capture](netlify-09.png) + +Step 11 +: When the deployment completes, click on the link to your published site. + + ![screen capture](netlify-10.png) + +In the future, whenever you push a change from your local Git repository, Netlify will rebuild and deploy your site. diff --cc docs/content/en/host-and-deploy/host-on-render/index.md index bec42af64,000000000..609ff8c31 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-render/index.md +++ b/docs/content/en/host-and-deploy/host-on-render/index.md @@@ -1,170 -1,0 +1,170 @@@ +--- +title: Host on Render +description: Host your site on Render. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hosting-on-render/] +--- + +Use these instructions to enable continuous deployment from a GitHub repository. The same general steps apply if you are using Bitbucket or GitLab for version control. + +## Prerequisites + +Please complete the following tasks before continuing: + +1. [Create](https://dashboard.render.com/register) a Render account +1. [Log in](https://dashboard.render.com/login) to your Render account +1. [Create](https://github.com/signup) a GitHub account +1. [Log in](https://github.com/login) to your GitHub account +1. [Create](https://github.com/new) a GitHub repository for your project +1. [Create](https://git-scm.com/docs/git-init) a local Git repository for your project with a [remote](https://git-scm.com/docs/git-remote) reference to your GitHub repository +1. Create a Hugo site within your local Git repository and test it with the `hugo server` command + +## Procedure + +Step 1 +: Create a [Render Blueprint][] in the root of your project. + + ``` {file="render.yaml" copy=true} + services: + - type: web + name: hosting-render + repo: https://github.com/jmooring/hosting-render + runtime: static + buildCommand: chmod a+x build.sh && ./build.sh + staticPublishPath: public + envVars: + - key: DART_SASS_VERSION + value: 1.97.3 + - key: GO_VERSION - value: 1.25.6 ++ value: 1.26.0 + - key: HUGO_VERSION - value: 0.155.3 ++ value: 0.156.0 + - key: NODE_VERSION - value: 24.13.0 ++ value: 24.13.1 + - key: TZ + value: Europe/Oslo + ``` + +Step 2 +: Create a `build.sh` file in the root of your project. + + ```sh {file="build.sh" copy=true} + #!/usr/bin/env bash + + #------------------------------------------------------------------------------ + # @file + # Builds a Hugo site hosted on a Render. + # + # Render automatically installs Node.js dependencies. + #------------------------------------------------------------------------------ + + main() { + + # Create directory for user-specific executable files + echo "Creating directory for user-specific executable files..." + mkdir -p "${HOME}/.local" + + # Install Dart Sass + echo "Installing Dart Sass ${DART_SASS_VERSION}..." + curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + export PATH="${HOME}/.local/dart-sass:${PATH}" + + # Install Go + echo "Installing Go ${GO_VERSION}..." + curl -sLJO "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" + tar -C "${HOME}/.local" -xf "go${GO_VERSION}.linux-amd64.tar.gz" + rm "go${GO_VERSION}.linux-amd64.tar.gz" + export PATH="${HOME}/.local/go/bin:${PATH}" + + # Install Hugo + echo "Installing Hugo ${HUGO_VERSION}..." + curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + mkdir -p "${HOME}/.local/hugo" + tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + export PATH="${HOME}/.local/hugo:${PATH}" + + # Verify installations + echo "Verifying installations..." + echo Dart Sass: "$(sass --version)" + echo Go: "$(go version)" + echo Hugo: "$(hugo version)" + echo Node.js: "$(node --version)" + + # Configure Git + echo "Configuring Git..." + git config core.quotepath false + if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then + git fetch --unshallow + fi + + # Build the site + echo "Building the site..." - hugo --gc --minify --baseURL "${RENDER_EXTERNAL_URL}" ++ hugo build --gc --minify --baseURL "${RENDER_EXTERNAL_URL}" + + } + + set -euo pipefail + main "$@" + ``` + +Step 3 +: Commit the changes to your local Git repository and push to your GitHub repository. + +Step 4 +: On the Render [dashboard][], press the **Add new** button and select "Blueprint" from the drop-down menu. + + ![screen capture](render-01.png) + +Step 5 +: Press the **GitHub** button to connect to your GitHub account. + + ![screen capture](render-02.png) + +Step 6 +: Press the **Authorize Render** button to allow the Render application to access your GitHub account. + + ![screen capture](render-03.png) + +Step 7 +: Select the GitHub account where you want to install the Render application. + + ![screen capture](render-04.png) + +Step 8 +: Authorize the Render application to access all repositories or only select repositories, then press the **Install** button. + +![screen capture](render-05.png) + +Step 9 +: On the "Create a new Blueprint Instance in My Workspacee" page, press the **Connect** button to the right of the name of your GitHub repository. + + ![screen capture](render-06.png) + +Step 10 +: Enter a unique name for your Blueprint, then press the **Deploy Blueprint** button at the bottom of the page. + + ![screen capture](render-07.png) + +Step 11 +: Wait for the site to build and deploy, then click on the "Resources" link on the left side of the page. + + ![screen capture](render-08.png) + +Step 12 +: Click on the link to the static site resource. + + ![screen capture](render-09.png) + +Step 13 +: Click on the link to your published site. + + ![screen capture](render-10.png) + +In the future, whenever you push a change from your local Git repository, Render will rebuild and deploy your site. + +[Render Blueprint]: https://render.com/docs/blueprint-spec +[dashboard]: https://dashboard.render.com/ diff --cc docs/content/en/host-and-deploy/host-on-sourcehut-pages.md index 70fd1bb96,000000000..75f3b45b5 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-sourcehut-pages.md +++ b/docs/content/en/host-and-deploy/host-on-sourcehut-pages.md @@@ -1,125 -1,0 +1,125 @@@ +--- +title: Host on SourceHut Pages +description: Host your site on SourceHut Pages. +categories: [] +keywords: [] +aliases: [/hosting-and-deployment/hosting-on-sourcehut/] +--- + +## Assumptions + +- Working familiarity with [Git][] or [Mercurial][] for version control +- Completion of the Hugo [Quick Start][] +- A [SourceHut account][] +- A Hugo website on your local machine that you are ready to publish + +[Git]: https://git-scm.com/ +[Mercurial]: https://www.mercurial-scm.org/ +[SourceHut account]: https://meta.sr.ht/login +[Quick Start]: /getting-started/quick-start/ + +Any and all mentions of `` refer to your actual SourceHut username and must be substituted accordingly. + +## BaseURL + - The [`baseURL`][] in your site configuration must reflect the full URL provided by SourceHut Pages if you are using the default address (e.g. `https://.srht.site/`). If you want to use another domain, check the [custom domain section][] of the official documentation. ++The [`baseURL`][] in your project configuration must reflect the full URL provided by SourceHut Pages if you are using the default address (e.g. `https://.srht.site/`). If you want to use another domain, check the [custom domain section][] of the official documentation. + +[`baseURL`]: /configuration/all/#baseurl +[custom domain section]: https://srht.site/custom-domains + +## Manual deployment + +This method does not require a paid account. To proceed you will need to create a [SourceHut personal access token][] and install and configure the [hut][] CLI tool: + +[SourceHut personal access token]: https://meta.sr.ht/oauth2/personal-token +[hut]: https://sr.ht/~xenrox/hut/ + +```sh - hugo ++hugo build +tar -C public -cvz . > site.tar.gz +hut init +hut pages publish -d .srht.site site.tar.gz +``` + +A TLS certificate will be automatically obtained for you, and your new website will be available at `https://.srht.site/` (or the provided custom domain). + +## Automated deployment + +This method requires a paid account and relies on the SourceHut build system. + +First, define your [build manifest][] by creating a `.build.yml` file in the root of your project. The following is a bare-bones template: + +[build manifest]: https://man.sr.ht/builds.sr.ht/#build-manifests + +```yaml {file=".build.yml" copy=true} +image: alpine/edge +packages: + - hugo + - hut +oauth: pages.sr.ht/PAGES:RW +environment: + site: .srht.site +tasks: +- package: | + cd $site - hugo ++ hugo build + tar -C public -cvz . > ../site.tar.gz +- upload: | + hut pages publish -d $site site.tar.gz +``` + +If your site requires [Dart Sass][] to transpile Sass to CSS, set the DART_SASS_VERSION to the [latest version number][] and include the Dart Sass installation lines before running the Hugo build step. Note that for Alpine, the `linux-x64-musl` version is used. + +[Dart Sass]: https://gohugo.io/functions/css/sass/#dart-sass +[latest version number]: https://github.com/sass/dart-sass/releases + +```yaml {file=".build.yml" copy=true} +image: alpine/edge +packages: + - hugo + - hut + - curl # For Dart Sass installation +oauth: pages.sr.ht/PAGES:RW +environment: + site: .srht.site +tasks: +- package: | + DART_SASS_VERSION=1.97.1 # Latest version as of 20/12/2025 + mkdir -p $HOME/.local + curl -L https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64-musl.tar.gz -o dart-sass.tar.gz + tar -xzf dart-sass.tar.gz -C $HOME/.local + rm dart-sass.tar.gz + chmod -R +x $HOME/.local/dart-sass/src + export PATH="$HOME/.local/dart-sass:$PATH" + sass --version # Verify installation + cd $site - hugo ++ hugo build + tar -C public -cvz . > ../site.tar.gz +- upload: | + hut pages publish -d $site site.tar.gz +``` + +Now what's left is creating a repository titled `.srht.site` (or your custom domain, if applicable) and pushing your local project. Here's an example using Git: + +```sh +# initialize new git repository +git init + +# add /public directory to our .gitignore file +echo "/public" >> .gitignore + +# commit and push code to main branch +git add . +git commit -m "Initial commit" +git remote add origin https://git.sr.ht/~/.srht.site +git push -u origin main +``` + +You can now follow the build progress of your page at `https://builds.sr.ht/`. + +After the build has passed, a TLS certificate will be automatically obtained for you and your new website will be available at `https://.srht.site/` (or the provided custom domain). + +## Other resources + +- [SourceHut Pages](https://srht.site/) +- [SourceHut Builds user manual](https://man.sr.ht/builds.sr.ht/) diff --cc docs/content/en/host-and-deploy/host-on-vercel/index.md index fb1b8b7e7,000000000..0a0143442 mode 100644,000000..100644 --- a/docs/content/en/host-and-deploy/host-on-vercel/index.md +++ b/docs/content/en/host-and-deploy/host-on-vercel/index.md @@@ -1,165 -1,0 +1,165 @@@ +--- +title: Host on Vercel +description: Host your site on Vercel. +categories: [] +keywords: [] +--- + +Use these instructions to enable continuous deployment from a GitHub repository. The same general steps apply if you are using Bitbucket or GitLab for version control. + +## Prerequisites + +Please complete the following tasks before continuing: + +1. [Create](https://vercel.com/signup) a Vercel account +1. [Log in](https://vercel.com/login) to your Vercel account +1. [Create](https://github.com/signup) a GitHub account +1. [Log in](https://github.com/login) to your GitHub account +1. [Create](https://github.com/new) a GitHub repository for your project +1. [Create](https://git-scm.com/docs/git-init) a local Git repository for your project with a [remote](https://git-scm.com/docs/git-remote) reference to your GitHub repository +1. Create a Hugo site within your local Git repository and test it with the `hugo server` command + +## Procedure + +Step 1 +: Create a `vercel.json` file in the root of your project. + + ```json {file="vercel.json" copy=true} + { + "$schema": "https://openapi.vercel.sh/vercel.json", + "buildCommand": "chmod a+x build.sh && ./build.sh", + "outputDirectory": "public" + } + ``` + +Step 2 +: Create a `build.sh` file in the root of your project. + + ```sh {file="build.sh" copy=true} + #!/usr/bin/env bash + + #------------------------------------------------------------------------------ + # @file + # Builds a Hugo site hosted on Vercel. + # + # The Vercel build image automatically installs Node.js dependencies. + #------------------------------------------------------------------------------ + + main() { + + DART_SASS_VERSION=1.97.3 - GO_VERSION=1.25.6 - HUGO_VERSION=0.155.3 - NODE_VERSION=24.13.0 ++ GO_VERSION=1.26.0 ++ HUGO_VERSION=0.156.0 ++ NODE_VERSION=24.13.1 + + export TZ=Europe/Oslo + + # Install Dart Sass + echo "Installing Dart Sass ${DART_SASS_VERSION}..." + curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz" + export PATH="${HOME}/.local/dart-sass:${PATH}" + + # Install Go + echo "Installing Go ${GO_VERSION}..." + curl -sLJO "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" + tar -C "${HOME}/.local" -xf "go${GO_VERSION}.linux-amd64.tar.gz" + rm "go${GO_VERSION}.linux-amd64.tar.gz" + export PATH="${HOME}/.local/go/bin:${PATH}" + + # Install Hugo + echo "Installing Hugo ${HUGO_VERSION}..." + curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + mkdir "${HOME}/.local/hugo" + tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz" + export PATH="${HOME}/.local/hugo:${PATH}" + + # Install Node.js + echo "Installing Node.js ${NODE_VERSION}..." + curl -sLJO "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" + tar -C "${HOME}/.local" -xf "node-v${NODE_VERSION}-linux-x64.tar.xz" + rm "node-v${NODE_VERSION}-linux-x64.tar.xz" + export PATH="${HOME}/.local/node-v${NODE_VERSION}-linux-x64/bin:${PATH}" + + # Verify installations + echo "Verifying installations..." + echo Dart Sass: "$(sass --version)" + echo Go: "$(go version)" + echo Hugo: "$(hugo version)" + echo Node.js: "$(node --version)" + + # Configure Git + echo "Configuring Git..." + git config core.quotepath false + if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then + git fetch --unshallow + fi + + # Build the site + echo "Building the site" - hugo --gc --minify --baseURL "https://${VERCEL_PROJECT_PRODUCTION_URL}" ++ hugo build --gc --minify --baseURL "https://${VERCEL_PROJECT_PRODUCTION_URL}" + + } + + set -euo pipefail + main "$@" + ``` + +Step 3 +: Commit the changes to your local Git repository and push to your GitHub repository. + +Step 4 +: In the upper right corner of the Vercel dashboard, press the **Add New** button and select "Project" from the drop down menu. + + ![screen capture](vercel-01.png) + +Step 5 +: Press the "Continue with GitHub" button. + + ![screen capture](vercel-02.png) + +Step 6 +: Press the **Authorize Vercel** button to allow the Vercel application to access your GitHub account. + + ![screen capture](vercel-03.png) + +Step 7 +: Press the **Install** button to install the Vercel application. + + ![screen capture](vercel-04.png) + +Step 8 +: Select the GitHub account where you want to install the Vercel application. + + ![screen capture](vercel-05.png) + +Step 9 +: Authorize the Vercel application to access all repositories or only select repositories, then press the **Install** button. + + ![screen capture](vercel-06.png) + + Your browser will be redirected to the Cloudflare dashboard. + +Step 10 +: Press the **Import** button to the right of the name of your GitHub repository. + + ![screen capture](vercel-07.png) + +Step 11 +: On the "New Project" page, leave the settings at their default values and press the **Deploy** button. + + ![screen capture](vercel-08.png) + +Step 12 +: When the deployment completes, press the **Continue to Dashboard" button at the bottom of the page. + + ![screen capture](vercel-09.png) + +Step 13 +: On the "Production Deployment" page, click on the link to your published site. + + ![screen capture](vercel-10.png) + +In the future, whenever you push a change from your local Git repository, Vercel will rebuild and deploy your site. diff --cc docs/content/en/hugo-modules/use-modules.md index 6a0483e76,000000000..eb15b13a7 mode 100644,000000..100644 --- a/docs/content/en/hugo-modules/use-modules.md +++ b/docs/content/en/hugo-modules/use-modules.md @@@ -1,154 -1,0 +1,200 @@@ +--- +title: Use Hugo Modules - description: How to use Hugo Modules. ++description: Use modules to manage the content, layout, presentation, and behavior of your site. +categories: [] +keywords: [] +weight: 20 +aliases: [/themes/usage/,/themes/installing/,/installing-and-using-themes/] +--- + - ## Prerequisite ++> [!note] ++> To work with modules you must install [Git][] and [Go][] 1.18 or later. + - {{% include "/_common/gomodules-info.md" %}} ++## Introduction + - ## Initialize a new module ++{{% glossary-term module %}} + - Use `hugo mod init` to initialize a new Hugo Module. If it fails to guess the module path, you must provide it as an argument, e.g.: ++- Modules can be imported in any combination or sequence. ++- Module imports are recursive; importing Module A can trigger the import of Module B, and so on. ++- Modules can provide configuration files and directories, subject to the constraints described in the [merge configuration settings][] section of the documentation. ++- External directories, including those from non-Hugo projects, can be mounted to create a [unified file system](g). ++ ++## Import ++ ++To import a module, first initialize the project itself as a module. For example: + +```sh - hugo mod init github.com// ++hugo mod init github.com/user/project +``` + - Also see the [CLI Doc](/commands/hugo_mod_init/). ++This will generate a [`go.mod`][] file in the project root. ++ ++> [!note] ++> The module name is a unique identifier rather than a hosting requirement. Using a name like `github.com/user/project` is a common convention but it does not mean you must use Git or host your code on GitHub. You can use any name you like if you do not plan to have others import your project as a module. For example, you could use a simple name such as `my-project` when you run the initialization command. + - ## Use a module for a theme ++Then define one or more imports in your project configuration. This contrived example imports three modules, each containing custom shortcodes: + - The easiest way to use a Module for a theme is to import it in the configuration. ++{{< code-toggle file=hugo >}} ++[module] ++ [[module.imports]] ++ path = 'shortcodes-a' ++ [[module.imports]] ++ path = '/home/user/shortcodes-b' ++ [[module.imports]] ++ path = 'github.com/user/shortcodes-c' ++{{< /code-toggle >}} + - 1. Initialize the hugo module system: `hugo mod init github.com//` - 1. Import the theme: ++Import precedence is top-down. For example, if `shortcodes-a`, `shortcodes-b`, and `shortcodes-c` each define an `image` shortcode, the `image` shortcode from `shortcodes-a` will take effect. + - {{< code-toggle file=hugo >}} - [module] - [[module.imports]] - path = "github.com/spf13/hyde" - {{< /code-toggle >}} ++> [!note] ++> If multiple modules contain data files or [translation tables](g) with identical paths, the data is deeply merged, following top-down precedence. + - ## Update modules ++When you build your project, Hugo will: + - Modules will be downloaded and added when you add them as imports to your configuration. See [configure modules](/configuration/module/#imports). ++1. Download the modules ++1. Cache them for future use ++1. Generate a [`go.sum`][] file in the project root + - To update or manage versions, you can use `hugo mod get`. ++See [configuring module imports][] for details and options. + - Some examples: ++## Update + - ### Update all modules ++When you import a module, Hugo creates `go.mod` and `go.sum` files in your project root, storing version and checksum data. Clearing the module cache and rebuilding will re-download the originally imported module version, as specified in the `go.mod` file, ensuring consistent builds. Modules can be updated to other versions as needed. ++ ++To update a module to the latest version: + +```sh - hugo mod get -u ++hugo mod get -u github.com/user/shortcodes-c +``` + - ### Update all modules recursively ++To update a module to a specific version: + +```sh - hugo mod get -u ./... ++hugo mod get -u github.com/user/shortcodes-c@v0.42.0 +``` + - ### Update one module ++To update all modules to the latest version: + +```sh - hugo mod get -u github.com/gohugoio/myShortcodes ++hugo mod get -u +``` + - ### Get a specific version ++To recursively update all modules to the latest version: + +```sh - hugo mod get github.com/gohugoio/myShortcodes@v1.0.7 ++hugo mod get -u ./... +``` + - Also see the [CLI Doc](/commands/hugo_mod_get/). - - ## Make and test changes in a module ++## Tidy + - One way to do local development of a module imported in a project is to add a replace directive to a local directory with the source in `go.mod`: ++To remove unused entries from the `go.mod` and `go.sum` files: + +```sh - replace github.com/bep/hugotestmods/mypartials => /Users/bep/hugotestmods/mypartials ++hugo mod tidy +``` + - If you have the `hugo server` running, the configuration will be reloaded and `/Users/bep/hugotestmods/mypartials` put on the watch list. ++## Cache + - Instead of modifying the `go.mod` files, you can also use the modules configuration [`replacements`](/configuration/module/#top-level-options) option. ++Hugo caches modules to avoid repeated downloads during site builds. By default, these are stored in the `modules` directory within the [`cacheDir`][]. + - ## Print dependency graph ++To clean the module cache for the current project: + - Use `hugo mod graph` from the relevant module directory and it will print the dependency graph, including vendoring, module replacement or disabled status. - - E.g.: ++```sh ++hugo mod clean ++``` + - ```txt - hugo mod graph ++To clean the module cache for all projects: + - github.com/bep/my-modular-site github.com/bep/hugotestmods/mymounts@v1.2.0 - github.com/bep/my-modular-site github.com/bep/hugotestmods/mypartials@v1.0.7 - github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myassets@v1.0.4 - github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myv2@v1.0.0 - DISABLED github.com/bep/my-modular-site github.com/spf13/hyde@v0.0.0-20190427180251-e36f5799b396 - github.com/bep/my-modular-site github.com/bep/hugo-fresh@v1.0.1 - github.com/bep/my-modular-site in-themesdir ++```sh ++hugo mod clean --all +``` + - Also see the [CLI Doc](/commands/hugo_mod_graph/). ++For details on cache location and eviction, see [configuring file caches][]. + - ## Vendor your modules ++## Vendor + - `hugo mod vendor` will write all the module dependencies to a `_vendor` directory, which will then be used for all subsequent builds. ++{{% glossary-term vendor %}} + - Note that: ++Vendoring a module provides the benefits described above and allows for local inspection of its [components](g). + - - You can run `hugo mod vendor` on any level in the module tree. - - Vendoring will not store modules stored in your `themes` directory. - - Most commands accept a `--ignoreVendorPaths` flag, which will then not use the vendored modules in `_vendor` for the module paths matching the given [glob pattern](g). - - Also see the [CLI Doc](/commands/hugo_mod_vendor/). ++```sh ++hugo mod vendor ++``` + - ## Tidy go.mod, go.sum ++This command creates a `_vendor` directory containing copies of all imported modules, used in subsequent builds. Note that: + - Run `hugo mod tidy` to remove unused entries in `go.mod` and `go.sum`. ++- The `hugo mod vendor` command can be run from any module tree level. ++- Modules within the `themes` directory are not vendored. ++- The `--ignoreVendorPaths` flag allows you to exclude vendored modules matching a [glob pattern](g) from specific commands. + - Also see the [CLI Doc](/commands/hugo_mod_clean/). ++> [!important] ++> Instead of modifying files directly within the `_vendor` directory, override them by creating a corresponding file with the same relative path in your project's root. + - ## Clean module cache ++To remove the vendored modules, delete the `_vendor` directory. + - Run `hugo mod clean` to delete the entire modules cache. ++## Replace + - Note that you can also configure the `modules` cache with a `maxAge`. See [configure caches](/configuration/caches/). ++For local module development, use a `replace` directive in `go.mod` pointing to your local directory: + - Also see the [CLI Doc](/commands/hugo_mod_clean/). ++```text ++replace github.com/user/module => /home/user/projects/module ++``` + - ## Module workspaces ++With `hugo serve`r running, this change will trigger a configuration reload and add the local directory to the watch list. Alternatively, configure replacements by setting the [`replacements`][] parameter in your project configuration. + - Workspace support was added in [Go 1.18](https://go.dev/blog/get-familiar-with-workspaces) and Hugo got solid support for it in the `v0.109.0` version. ++## Workspace + - A common use case for a workspace is to simplify local development of a site with its theme modules. ++{{% glossary-term "workspace" %}} + - A workspace can be configured in a `*.work` file and activated with the [module.workspace](/configuration/module/) setting, which for this use is commonly controlled via the `HUGO_MODULE_WORKSPACE` OS environment variable. ++Workspaces simplify local development of sites with modules. Create a `.work` file to define a workspace, and activate it via the [`workspace`][] configuration parameter or the `HUGO_MODULE_WORKSPACE` environment variable. + - See the [hugo.work](https://github.com/gohugoio/hugo/blob/master/docs/hugo.work) file in the Hugo Docs repo for an example: ++A `.work` file example: + +```text - go 1.20 ++go 1.24 + +use . - use ../gohugoioTheme ++use ../my-hugo-module +``` + - Using the `use` directive, list all the modules you want to work on, pointing to its relative location. As in the example above, it's recommended to always include the main project (the `.`) in the list. - - With that you can start the Hugo server with that workspace enabled: ++Use the `use` directive to list module paths, including the main project (`.`). Start the Hugo server with the workspace enabled: + +```sh +HUGO_MODULE_WORKSPACE=hugo.work hugo server --ignoreVendorPaths "**" +``` + - The `--ignoreVendorPaths` flag is added above to ignore any of the vendored dependencies inside `_vendor`. If you don't use vendoring, you don't need that flag. But now the server is set up watching the files and directories in the workspace and you can see your local edits reloaded. ++The `--ignoreVendorPaths` flag, used to ignore vendored dependencies (if applicable), enables live reloading of local edits within the workspace. ++ ++## Graph ++ ++To generate a [dependency graph](g), including vendoring, module replacement, and disabled module information, execute `hugo mod graph` within the target module directory. For example: ++ ++```sh ++$ hugo mod graph ++ ++github.com/bep/my-modular-site github.com/bep/hugotestmods/mymounts@v1.2.0 ++github.com/bep/my-modular-site github.com/bep/hugotestmods/mypartials@v1.0.7 ++github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myassets@v1.0.4 ++github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myv2@v1.0.0 ++DISABLED github.com/bep/my-modular-site github.com/spf13/hyde@v0.0.0-20190427180251-e36f5799b396 ++github.com/bep/my-modular-site github.com/bep/hugo-fresh@v1.0.1 ++github.com/bep/my-modular-site in-themesdir ++``` ++ ++## Mounts ++ ++Imported modules automatically mount their component directories to Hugo's [unified file system](g). You can also manually mount any directory, including those from non-Hugo projects, to component directories. ++ ++See [configuring module mounts][] for details. ++ ++[`cacheDir`]: /configuration/all/#cachedir ++[`go.mod`]: https://go.dev/ref/mod#go-mod-file ++[`go.sum`]: https://go.dev/ref/mod#go-sum-files ++[`replacements`]: /configuration/module/#replacements ++[`workspace`]: /configuration/module/#workspace ++[configuring file caches]: /configuration/caches/ ++[configuring module imports]: /configuration/module/#imports ++[configuring module mounts]: /configuration/module/#mounts ++[Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git ++[Go]: https://go.dev/doc/install ++[merge configuration settings]: /configuration/introduction/#merge-configuration-settings diff --cc docs/content/en/installation/linux.md index 31fcaa90d,000000000..6e8c9cd49 mode 100644,000000..100644 --- a/docs/content/en/installation/linux.md +++ b/docs/content/en/installation/linux.md @@@ -1,218 -1,0 +1,216 @@@ +--- +title: Linux +description: Install Hugo on Linux. +categories: [] +keywords: [] +weight: 20 +--- + +{{% include "/_common/installation/01-editions.md" %}} + +{{% include "/_common/installation/02-prerequisites.md" %}} + +{{% include "/_common/installation/03-prebuilt-binaries.md" %}} + +## Package managers + - + +{{% include "/_common/installation/homebrew.md" %}} + +## Repository packages + +Most Linux distributions maintain a repository for commonly installed applications. + +> [!note] +> The Hugo version available in package repositories varies based on Linux distribution and release, and in some cases will not be the [latest version]. +> +> Use one of the other installation methods if your package repository does not provide the desired version. + +### Alpine Linux + +To install the extended edition of Hugo on [Alpine Linux]: + +```sh +doas apk add --no-cache --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community hugo +``` + +### Arch Linux + +Derivatives of the [Arch Linux] distribution of Linux include [EndeavourOS], [Garuda Linux], [Manjaro], and others. To install the extended edition of Hugo: + +```sh +sudo pacman -S hugo +``` + +### Debian + +Derivatives of the [Debian] distribution of Linux include [elementary OS], [KDE neon], [Linux Lite], [Linux Mint], [MX Linux], [Pop!_OS], [Ubuntu], [Zorin OS], and others. To install the extended edition of Hugo: + +```sh +sudo apt install hugo +``` + +You can also download Debian packages from the [latest release][] page. + +### Exherbo + +To install the extended edition of Hugo on [Exherbo]: + +1. Add this line to /etc/paludis/options.conf: + + ```text + www-apps/hugo extended + ``` + +1. Install using the Paludis package manager: + + ```sh + cave resolve -x repository/heirecka + cave resolve -x hugo + ``` + +### Fedora + +Derivatives of the [Fedora] distribution of Linux include [CentOS], [Red Hat Enterprise Linux], and others. To install the extended edition of Hugo: + +```sh +sudo dnf install hugo +``` + +### Gentoo + +Derivatives of the [Gentoo] distribution of Linux include [Calculate Linux], [Funtoo], and others. To install the extended edition of Hugo: + +1. Specify the `extended` [USE] flag in /etc/portage/package.use/hugo: + + ```text + www-apps/hugo extended + ``` + +1. Build using the Portage package manager: + + ```sh + sudo emerge www-apps/hugo + ``` + +### NixOS + +The NixOS distribution of Linux includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +nix-env -iA nixos.hugo +``` + +### openSUSE + +Derivatives of the [openSUSE] distribution of Linux include [GeckoLinux], [Linux Karmada], and others. To install the extended edition of Hugo: + +```sh +sudo zypper install hugo +``` + +### Solus + +The [Solus] distribution of Linux includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +sudo eopkg install hugo +``` + +### Void Linux + +To install the extended edition of Hugo on [Void Linux]: + +```sh +sudo xbps-install -S hugo +``` + +{{% include "/_common/installation/04-build-from-source.md" %}} + +## Comparison + + |Prebuilt binaries|Package managers|Repository packages|Build from source +:--|:--:|:--:|:--:|:--: +Easy to install?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: +Easy to upgrade?|:heavy_check_mark:|:heavy_check_mark:|varies|:heavy_check_mark: +Easy to downgrade?|:heavy_check_mark:|:heavy_check_mark: [^1]|varies|:heavy_check_mark: +Automatic updates?|:x:|varies [^2]|:x:|:x: +Latest version available?|:heavy_check_mark:|:heavy_check_mark:|varies|:heavy_check_mark: + +[^1]: Easy if a previous version is still installed. +[^2]: Snap packages are automatically updated. Homebrew requires advanced configuration. + +[Alpine Linux]: https://alpinelinux.org/ +[Arch Linux]: https://archlinux.org/ +[Calculate Linux]: https://www.calculate-linux.org/ +[CentOS]: https://www.centos.org/ +[Debian]: https://www.debian.org/ +[elementary OS]: https://elementary.io/ +[EndeavourOS]: https://endeavouros.com/ +[Exherbo]: https://www.exherbolinux.org/ +[Fedora]: https://getfedora.org/ +[Funtoo]: https://www.funtoo.org/ +[Garuda Linux]: https://garudalinux.org/ +[GeckoLinux]: https://geckolinux.github.io/ +[Gentoo]: https://www.gentoo.org/ +[KDE neon]: https://neon.kde.org/ +[latest release]: https://github.com/gohugoio/hugo/releases/latest +[latest version]: https://github.com/gohugoio/hugo/releases/latest +[Linux Karmada]: https://linuxkamarada.com/ +[Linux Lite]: https://www.linuxliteos.com/ +[Linux Mint]: https://linuxmint.com/ +[Manjaro]: https://manjaro.org/ +[MX Linux]: https://mxlinux.org/ +[openSUSE]: https://www.opensuse.org/ +[Pop!_OS]: https://pop.system76.com/ +[Red Hat Enterprise Linux]: https://www.redhat.com/ +[Solus]: https://getsol.us/ +[Ubuntu]: https://ubuntu.com/ +[USE]: https://packages.gentoo.org/packages/www-apps/hugo +[Void Linux]: https://voidlinux.org/ +[Zorin OS]: https://zorin.com/os/ diff --cc docs/content/en/methods/duration/_index.md index aeb113820,000000000..4c690ecc3 mode 100644,000000..100644 --- a/docs/content/en/methods/duration/_index.md +++ b/docs/content/en/methods/duration/_index.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: Duration methods +linkTitle: Duration - description: Use these methods with time.Duration values. ++description: Use these methods with a time.Duration value. +categories: [] +keywords: [] +--- diff --cc docs/content/en/methods/menu-entry/Children.md index ecad415fa,000000000..16cec71d9 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Children.md +++ b/docs/content/en/methods/menu-entry/Children.md @@@ -1,66 -1,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: ++With this project 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 +
      + {{ range .Site.Menus.main }} +
    • + {{ .Name }} + {{ if .HasChildren }} + + {{ end }} +
    • + {{ end }} +
    +``` + +Hugo renders this HTML: + +```html + +``` diff --cc docs/content/en/methods/menu-entry/HasChildren.md index 03e6cb672,000000000..59ef2e19e mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/HasChildren.md +++ b/docs/content/en/methods/menu-entry/HasChildren.md @@@ -1,66 -1,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: ++With this project 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 +
      + {{ range .Site.Menus.main }} +
    • + {{ .Name }} + {{ if .HasChildren }} + + {{ end }} +
    • + {{ end }} +
    +``` + +Hugo renders this HTML: + +```html + +``` diff --cc docs/content/en/methods/menu-entry/Name.md index 706d0f8c8,000000000..a00601b2d mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Name.md +++ b/docs/content/en/methods/menu-entry/Name.md @@@ -1,28 -1,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 ++If you define the menu entry in [front matter] or in your [project 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`]. + +```go-html-template +
      + {{ range .Site.Menus.main }} +
    • {{ .Name }}
    • + {{ end }} +
    +``` ++ ++[`LinkTitle`]: /methods/page/linktitle/ ++[`Title`]: /methods/page/title/ ++[automatically]: /content-management/menus/#define-automatically ++[front matter]: /content-management/menus/#define-in-front-matter ++[project configuration]: /content-management/menus/#define-in-project-configuration diff --cc docs/content/en/methods/menu-entry/PageRef.md index 31db24de0,000000000..8d4e53656 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/PageRef.md +++ b/docs/content/en/methods/menu-entry/PageRef.md @@@ -1,109 -1,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] +--- + +> [!note] +> 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 you specify a `pageRef` property when [defining a menu entry] in your project 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"} +
      + {{ range .Site.Menus.main }} +
    • {{ .Name }}
    • + {{ end }} +
    +``` + +Hugo render this HTML: + +```html + +``` + +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"} +
      + {{ range .Site.Menus.main }} +
    • {{ .Name }}
    • + {{ end }} +
    +``` + +Hugo renders this HTML: + +```html + +``` + - 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. ++In the above note that Hugo populates the `href` attribute of the second `anchor` element with the `pageRef` property as defined in your project 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 ++[defining a menu entry]: /content-management/menus/#define-in-project-configuration diff --cc docs/content/en/methods/menu-entry/Params.md index 20c4f7fc7,000000000..113178147 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Params.md +++ b/docs/content/en/methods/menu-entry/Params.md @@@ -1,61 -1,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: ++When you define menu entries in your [project 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 + +``` + +Hugo renders: + +```html + +``` + +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/ ++[front matter]: /content-management/menus/#define-in-front-matter ++[project configuration]: /content-management/menus/ diff --cc docs/content/en/methods/menu-entry/Weight.md index b96e2cc87,000000000..17fc3a43b mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Weight.md +++ b/docs/content/en/methods/menu-entry/Weight.md @@@ -1,31 -1,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 ++If you define the menu entry in [front matter] or in your [project configuration], the `Weight` method returns the `weight` property, falling back to the page's `Weight`. + +In this contrived example, we limit the number of menu entries based on weight: + +```go-html-template +
      + {{ range .Site.Menus.main }} + {{ if le .Weight 42 }} +
    • {{ .Name }}
    • + {{ end }} + {{ end }} +
    +``` ++ ++[`Weight`]: /methods/page/weight/ ++[automatically]: /content-management/menus/#define-automatically ++[front matter]: /content-management/menus/#define-in-front-matter ++[project configuration]: /content-management/menus/#define-in-project-configuration diff --cc docs/content/en/methods/output-format/Rel.md index 1dca4b10a,000000000..4c3db9791 mode 100644,000000..100644 --- a/docs/content/en/methods/output-format/Rel.md +++ b/docs/content/en/methods/output-format/Rel.md @@@ -1,18 -1,0 +1,18 @@@ +--- +title: Rel - description: Returns the rel value of the given output format, either the default or as defined in the site configuration. ++description: Returns the rel value of the given output format, either the default or as defined in your project configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [OUTPUTFORMAT.Rel] +--- + +{{% include "/_common/methods/output-formats/to-use-this-method.md" %}} + +```go-html-template +{{ with .Site.Home.OutputFormats.Get "rss" }} + {{ .Rel }} → alternate +{{ end }} +``` diff --cc docs/content/en/methods/page/Aliases.md index f549ad948,000000000..217af4e99 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Aliases.md +++ b/docs/content/en/methods/page/Aliases.md @@@ -1,139 -1,0 +1,138 @@@ +--- +title: Aliases +description: Returns the aliases defined in front matter as server-relative URLs, resolved according to the current content dimension. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: '[]string' + signatures: [PAGE.Aliases] +--- + +The `Aliases` method on a `Page` object returns the values defined in the [`aliases`][] front matter field as server-relative URLs, resolved according to the current [content dimension](g). + +The `Aliases` method is useful for generating a `_redirects` file, which contains a source URL, a target URL, and an HTTP status code for each alias. You can use a `_redirects` file with hosting services such as Cloudflare, GitLab Pages, and Netlify. + +## Redirects + +By default, Hugo handles aliases by creating individual HTML files for each alias path. These files contain a `meta http-equiv="refresh"` tag to redirect the visitor via the browser. + +While functional, generating a single `_redirects` file allows your hosting provider to handle redirects at the server level. This is more efficient than client-side redirection and improves performance by eliminating the need to load a middle-man HTML page. + +> [!tip] +> You can use the same general approach to generate an `.htaccess` file. + +## Example + +The following example demonstrates how to configure your site and create a template to automate the generation of a `_redirects` file. + +### Content structure + +The content structure for this multilingual example looks like this: + +```text +content/ +├── examples/ +│ ├── a.de.md aliases = ['a-old'] +│ ├── a.en.md aliases = ['a-old', 'a-older'] +│ ├── b.de.md aliases = ['b-old'] +│ └── b.en.md aliases = ['b-old', 'b-older'] +└── _index.md +``` + +In the example above, the aliases are [page-relative](g). To specify a [site-relative](g) path, preface the entry with a slash (`/`). Both forms are resolved to [server-relative](g) paths. + +Page-relative paths can also include directory traversal: + +| Path type | File path | Alias | Server-relative path | +| :--- | :--- | :--- | :--- | +| page-relative | `content/examples/a.en.md` | `a-old` | `/en/examples/a-old/` | +| page-relative | `content/examples/a.en.md` | `../a-old` | `/en/a-old/` | +| site-relative | `content/examples/a.en.md` | `/a-old` | `/en/a-old/` | + - ### Site configuration ++### Project configuration + - To implement this, you must update your site configuration to: ++To implement this, you must update your project configuration to: + +1. Disable the generation of default HTML redirect files by setting `disableAliases` to `true`. +1. Define a [media type][] named `text/redirects` to handle the file format. +1. Define a custom [output format][] named `redirects` to set the filename to `_redirects` and place it at the root of the published site. +1. Configure the home page [outputs][] to include the `redirects` format in addition to `html`. + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/' +disableAliases = true + +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = true + +[languages.en] + languageCode = 'en-US' + languageDirection = 'ltr' + languageName = 'English' + weight = 1 + title = 'My Site in English' + +[languages.de] + languageCode = 'de-DE' + languageDirection = 'ltr' + languageName = 'Deutsch' + weight = 2 + title = 'My Site in German' + +[mediaTypes] + [mediaTypes.'text/redirects'] + delimiter = '' + +[outputFormats] + [outputFormats.redirects] + baseName = '_redirects' + isPlainText = true + mediaType = 'text/redirects' + root = true + +[outputs] + home = ['html', 'redirects'] +{{< /code-toggle >}} + +### Template implementation + +Next, create a home page template specifically for the `redirects` output format. The following template iterates through every page in every language and extracts its aliases. + +To ensure the resulting `_redirects` file is valid, the template uses the [`strings.FindRE`][] function to check for whitespace such as tabs or newlines within the alias string. If whitespace is detected, Hugo will throw an error and fail the build to prevent generating an invalid file. + +```go-html-template {file="layouts/home.redirects" copy=true} - {{- if not (hugo.Store.Get "has_printed_redirects") -}} - {{- range .Sites -}} ++{{- if site.IsDefault -}} ++ {{- range hugo.Sites -}} + {{- range $p := .Pages -}} + {{- range .Aliases -}} + {{- if findRE `\s` . -}} + {{- errorf "One of the front matter aliases in %q contains whitespace" $p.String -}} + {{- end -}} + {{- printf "%s %s 301\n" . $p.RelPermalink -}} + {{- end -}} + {{- end -}} + {{- end -}} - {{- hugo.Store.Set "has_printed_redirects" true -}} +{{- end -}} +``` + +### Generated output + +Once Hugo processes the template, it produces a clean list of redirect rules. Each line follows the required format: the source URL, the destination URL, and the HTTP status code. + +The resulting `_redirects` file looks like this: + +```text +/de/examples/a-old /de/examples/a/ 301 +/de/examples/b-old /de/examples/b/ 301 +/en/examples/b-old /en/examples/b/ 301 +/en/examples/b-older /en/examples/b/ 301 +/en/examples/a-old /en/examples/a/ 301 +/en/examples/a-older /en/examples/a/ 301 +``` + +[`aliases`]: /content-management/front-matter/#aliases +[`strings.FindRE`]: /functions/strings/findre/ +[media type]: /configuration/media-types/ +[output format]: /configuration/output-formats/ +[outputs]: /configuration/outputs/ diff --cc docs/content/en/methods/page/AllTranslations.md index ed92cd482,000000000..27a9f932a mode 100644,000000..100644 --- a/docs/content/en/methods/page/AllTranslations.md +++ b/docs/content/en/methods/page/AllTranslations.md @@@ -1,88 -1,0 +1,88 @@@ +--- +title: AllTranslations +description: Returns all translations of the given page, including the current language, sorted by language weight. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.AllTranslations] +--- + - With this site configuration: ++With this project 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 }} + +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of each site: + +```html + +``` + +On the "Book 2" page of the English and German sites, Hugo will render this: + +```html + +``` diff --cc docs/content/en/methods/page/Data.md index 387422901,000000000..3d4433a8e mode 100644,000000..100644 --- a/docs/content/en/methods/page/Data.md +++ b/docs/content/en/methods/page/Data.md @@@ -1,101 -1,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 their 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: ++The examples that follow are based on this project 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 --cc docs/content/en/methods/page/Date.md index 21bf03445,000000000..ffddcf047 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Date.md +++ b/docs/content/en/methods/page/Date.md @@@ -1,33 -1,0 +1,33 @@@ +--- +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 field in front matter is often considered to be the creation date, You can change its meaning, and its effect on your project, in your project 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 +[time methods]: /methods/time/ +[time.Time]: https://pkg.go.dev/time#Time diff --cc docs/content/en/methods/page/Draft.md index 482a370bf,000000000..d814d8541 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Draft.md +++ b/docs/content/en/methods/page/Draft.md @@@ -1,21 -1,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. ++By default, Hugo does not publish draft pages when you build your project. To include draft pages when you build your project, 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 --cc docs/content/en/methods/page/ExpiryDate.md index a72155c33,000000000..67e6b30d3 mode 100644,000000..100644 --- a/docs/content/en/methods/page/ExpiryDate.md +++ b/docs/content/en/methods/page/ExpiryDate.md @@@ -1,32 -1,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. ++By default, Hugo excludes expired pages when building your project. 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 --cc docs/content/en/methods/page/File.md index 2af60a719,000000000..0bf2fdecf mode 100644,000000..100644 --- a/docs/content/en/methods/page/File.md +++ b/docs/content/en/methods/page/File.md @@@ -1,194 -1,0 +1,192 @@@ +--- +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 --cc docs/content/en/methods/page/Fragments.md index 1b30ac973,000000000..9df47f31c mode 100644,000000..100644 --- a/docs/content/en/methods/page/Fragments.md +++ b/docs/content/en/methods/page/Fragments.md @@@ -1,109 -1,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 +
    {{ debug.Dump .Fragments.Headings }}
    +``` + +### 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 +
    {{ debug.Dump .Fragments.HeadingsMap }}
    +``` + +### 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 +
    {{ debug.Dump .Fragments.Identifiers }}
    +``` + +### 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. ++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 project configuration. + +```go-html-template +{{ $startLevel := 2 }} +{{ $endLevel := 3 }} +{{ $ordered := true }} +{{ .Fragments.ToHTML $startLevel $endLevel $ordered }} +``` + +Hugo renders this to: + +```html + +``` + +> [!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/current/#atx-headings +[Markdown notation]: /content-management/shortcodes/#notation +[setext]: https://spec.commonmark.org/current/#setext-headings +[standard notation]: /content-management/shortcodes/#notation +[table of contents]: /methods/page/tableofcontents/ diff --cc docs/content/en/methods/page/GitInfo.md index f09eb76b4,000000000..ef2dffa4c mode 100644,000000..100644 --- a/docs/content/en/methods/page/GitInfo.md +++ b/docs/content/en/methods/page/GitInfo.md @@@ -1,185 -1,0 +1,185 @@@ +--- +title: GitInfo +description: Returns Git information related to the last commit of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: '*gitmap.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: ++You must also allow Hugo to access your repository. In your project configuration: + +{{< code-toggle file=hugo >}} +enableGitInfo = true +{{< /code-toggle >}} + - Alternatively, use the command line flag when building your site: ++Alternatively, use the command line flag when building your project: + +```sh - hugo --enableGitInfo ++hugo build --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 }} +``` + +### Ancestors + +(`gitmap.GitInfos`) A slice of file-filtered ancestor commits, if any, ordered from most recent to least recent. + +For example, to list the last 5 commits: + +```go-html-template +{{ with .GitInfo }} + {{ range .Ancestors | first 5 }} + {{ .CommitDate.Format "2006-01-02" }}: {{ .Subject }} + {{ end }} +{{ end }} +``` + +To reverse the order: + +```go-html-template +{{ with .GitInfo }} + {{ range .Ancestors.Reverse | first 5 }} + {{ .CommitDate.Format "2006-01-02" }}: {{ .Subject }} + {{ end }} +{{ end }} +``` + +### Parent + +(`*gitmap.GitInfo`) The first file-filtered ancestor commit, if any. + +## 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]. ++You can change this behavior in your [project configuration]. + +## Hosting considerations + +On a [CI/CD](g) platform, 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 be inaccurate. It might incorrectly reflect the most recent repository commit, rather than the commit that actually modified the file. + +While some providers perform a deep clone by default, others require you to configure the depth yourself. + +Hosting service|Default clone depth|Configurable +:--|:--|:-- +AWS Amplify|Deep|N/A +Cloudflare|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|Yes [^1] +Vercel|Shallow|Yes [^1] + +[^1]: To perform a deep clone when hosting on Cloudflare, Render, or Vercel, include this code in the build script after the repository has been cloned: + + ```text + if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then + git fetch --unshallow + fi + ``` + +[^2]: To perform a deep clone when hosting on GitHub Pages, set `fetch-depth: 0` in the `checkout` step of the GitHub Action. See [example](/host-and-deploy/host-on-github-pages/#step-7). + +[^3]: To perform a deep clone when hosting on GitLab Pages, set the `GIT_DEPTH` environment variable to `0` in the workflow file. See [example](/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/ ++[project configuration]: /configuration/front-matter/ diff --cc docs/content/en/methods/page/HasMenuCurrent.md index 207882167,000000000..22bcc6483 mode 100644,000000..100644 --- a/docs/content/en/methods/page/HasMenuCurrent.md +++ b/docs/content/en/methods/page/HasMenuCurrent.md @@@ -1,33 -1,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 . }} + {{ .Name }} + {{ else if $currentPage.HasMenuCurrent .Menu . }} + {{ .Name }} + {{ else }} + {{ .Name }} + {{ 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. ++> 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 project configuration. + +[menu templates]: /templates/menu/#example diff --cc docs/content/en/methods/page/IsMenuCurrent.md index 9bbacd018,000000000..60b68428a mode 100644,000000..100644 --- a/docs/content/en/methods/page/IsMenuCurrent.md +++ b/docs/content/en/methods/page/IsMenuCurrent.md @@@ -1,31 -1,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 . }} + {{ .Name }} + {{ else if $currentPage.HasMenuCurrent .Menu . }} + {{ .Name }} + {{ else }} + {{ .Name }} + {{ 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. ++> 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 project configuration. + +[menu templates]: /templates/menu/#example diff --cc docs/content/en/methods/page/IsTranslated.md index 2cdf911ac,000000000..6ce340ecb mode 100644,000000..100644 --- a/docs/content/en/methods/page/IsTranslated.md +++ b/docs/content/en/methods/page/IsTranslated.md @@@ -1,56 -1,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: ++With this project 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 --cc docs/content/en/methods/page/Language.md index 8ccc578f6,000000000..7eac722dd mode 100644,000000..100644 --- a/docs/content/en/methods/page/Language.md +++ b/docs/content/en/methods/page/Language.md @@@ -1,88 -1,0 +1,94 @@@ +--- +title: Language - description: Returns the language object for the given page. ++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 is derived from the language definition in the site configuration. ++The `Language` method on a `Page` object returns the `Language` object for the given page, derived from the language definition in your project configuration. + - You can also use the `Language` method on a `Site` object. See [details]. ++You can also use the `Language` method on a `Site` object. See [details][]. + +## Methods + - The examples below assume the following in the site configuration: ++The examples below assume the following in your project configuration: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +weight = 2 +{{< /code-toggle >}} + +### IsDefault + +{{< new-in 0.153.0 />}} + - (`bool`) Reports whether this is the default language object as defined by the [`defaultContentLanguage`][] setting in the site configuration. ++(`bool`) Reports whether this is the [default language][]. + +```go-html-template +{{ .Language.IsDefault }} → true +``` + +### Lang + - (`string`) The language tag as defined by [RFC 5646]. This is the lower cased key from the site configuration. ++(`string`) Returns the language tag as defined by [RFC 5646][]. This is the lowercased key from your project configuration. + +```go-html-template +{{ .Language.Lang }} → de +``` + +### LanguageCode + - (`string`) The language code from the site configuration. Falls back to `Lang` if not defined. ++(`string`) Returns the [`languageCode`][] from your project 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`. ++(`string`) Returns the [`languageDirection`][] from your project configuration. + +```go-html-template +{{ .Language.LanguageDirection }} → ltr +``` + +### LanguageName + - (`string`) The language name from the site configuration. ++(`string`) Returns the [`languageName`][] from your project configuration. + +```go-html-template +{{ .Language.LanguageName }} → Deutsch +``` + +### Name + - (`string`) The language tag as defined by [RFC 5646]. This is the lower cased key used in the site configuration. This is an alias for `Lang`. ++{{< new-in 0.153.0 />}} ++ ++(`string`) Returns the language tag as defined by [RFC 5646][]. This is the lowercased key from your project configuration. This is an alias for `Lang`. + +```go-html-template - {{ .Site.Language.Name }} → de ++{{ .Language.Name }} → de +``` + +### 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. ++(`int`) Returns the language [`weight`][] from your project configuration. + +```go-html-template +{{ .Language.Weight }} → 2 +``` + - [`defaultContentLanguage`]: /configuration/all/#defaultcontentlanguage - [details]: /methods/site/language/ ++[`languageCode`]: /configuration/languages/#languagecode ++[`languageDirection`]: /configuration/languages/#languagedirection ++[`languageName`]: /configuration/languages/#languagename ++[`weight`]: /configuration/languages/#weight ++[default language]: /quick-reference/glossary/#default-language ++[details]: /methods/page/language/ +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 diff --cc docs/content/en/methods/page/Paginate.md index 337811240,000000000..452bf9daf mode 100644,000000..100644 --- a/docs/content/en/methods/page/Paginate.md +++ b/docs/content/en/methods/page/Paginate.md @@@ -1,47 -1,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. ++By default, the number of elements on each pager is determined by your [project 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 in [home], [section], [taxonomy], and [term] templates. + +```go-html-template {file="layouts/section.html"} +{{ $pages := where .Site.RegularPages "Section" "articles" }} +{{ $pages = $pages.ByTitle }} +{{ range (.Paginate $pages 7).Pages }} +

    {{ .Title }}

    +{{ end }} +{{ partial "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]: /templates/types/#home +[section]: /templates/types/#section - [site configuration]: /configuration/pagination/ ++[project configuration]: /configuration/pagination/ +[taxonomy]: /templates/types/#taxonomy +[term]: /templates/types/#term diff --cc docs/content/en/methods/page/Paginator.md index 02b5d5719,000000000..059e55e2d mode 100644,000000..100644 --- a/docs/content/en/methods/page/Paginator.md +++ b/docs/content/en/methods/page/Paginator.md @@@ -1,40 -1,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`. ++The number of elements on each pager is determined by your [project configuration]. The default is `10`. + +You can invoke pagination in [home], [section], [taxonomy], 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/section.html"} +{{ range .Paginator.Pages }} +

    {{ .LinkTitle }}

    +{{ end }} +{{ partial "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]: /templates/types/#home +[section]: /templates/types/#section - [site configuration]: /configuration/pagination/ ++[project configuration]: /configuration/pagination/ +[taxonomy]: /templates/types/#taxonomy +[term]: /templates/types/#term +[`Paginate`]: /methods/page/paginate/ diff --cc docs/content/en/methods/page/Permalink.md index cc74f3342,000000000..ffd6ede0b mode 100644,000000..100644 --- a/docs/content/en/methods/page/Permalink.md +++ b/docs/content/en/methods/page/Permalink.md @@@ -1,24 -1,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: ++Project 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 --cc docs/content/en/methods/page/PublishDate.md index 7500a08aa,000000000..ec3c13377 mode 100644,000000..100644 --- a/docs/content/en/methods/page/PublishDate.md +++ b/docs/content/en/methods/page/PublishDate.md @@@ -1,32 -1,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. ++By default, Hugo excludes pages with future publish dates when building your project. 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 --cc docs/content/en/methods/page/RelPermalink.md index a3c610d50,000000000..ba03dc1bb mode 100644,000000..100644 --- a/docs/content/en/methods/page/RelPermalink.md +++ b/docs/content/en/methods/page/RelPermalink.md @@@ -1,24 -1,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: ++Project 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 --cc docs/content/en/methods/page/Rotate.md index 99cb69cc8,000000000..643945d85 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Rotate.md +++ b/docs/content/en/methods/page/Rotate.md @@@ -1,46 -1,0 +1,55 @@@ +--- +title: Rotate - description: Returns a collection of all pages sharing the same identity across the specified dimension, including the current page, sorted by the dimension's weight. ++description: Returns a collection of pages that vary along the specified dimension while sharing the current page's values for the other dimensions, including the current page, sorted by the dimension's default sort order. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.Rotate DIMENSION] +--- + +{{< new-in 0.153.0 />}} + - The `Rotate` method on a `Page` object returns a collection of all pages sharing the same identity across the specified [dimension](g), including the current page, sorted by the dimension's weight. ++The rotate method on a page object returns a collection of pages that vary along the specified [dimension](g), while holding the other dimensions constant. The result includes the current page and is sorted according to the rules of the specified dimension. For example, rotating along [language](g) returns all language variants that share the current page's [version](g) and [role](g). + - The `DIMENSION` argument must be one of `language`, `role`, or `version`. ++The `DIMENSION` argument must be one of `language`, `version`, or `role`. + - To render a list of all translations of the current page, including the current page: ++## Sort order ++ ++Use the following rules to understand how Hugo sorts the collection returned by the `Rotate` method. ++ ++| Dimension | Primary Sort | Secondary Sort | ++| :--- | :--- | :--- | ++| Language | Weight ascending | Lexicographical ascending | ++| Version | Weight ascending | Semantic version descending | ++| Role | Weight ascending | Lexicographical ascending | ++ ++## Examples ++ ++To render a list of the current page's language variants, including the current page, while sharing its current version and role: + +```go-html-template - {{ with .Rotate "language" }} - {{ range . }} -

    {{ .LinkTitle }}

    - {{ end }} ++{{/* Returns languages sorted by weight ascending, then lexicographically ascending */}} ++{{ range .Rotate "language" }} ++

    {{ .LinkTitle }}

    +{{ end }} +``` + - To render a list of all [roles](g) of the current page, including the current page: ++To render a list of the current page's version variants, including the current page, while sharing its current language and role: + +```go-html-template - {{ with .Rotate "role" }} - {{ range . }} -

    {{ .LinkTitle }}

    - {{ end }} ++{{/* Returns versions sorted by weight ascending, then semantic version descending */}} ++{{ range .Rotate "version" }} ++

    {{ .LinkTitle }}

    +{{ end }} +``` + - To render a list of all versions of the current page, including the current page: ++To render a list of the current page's role variants, including the current page, while sharing its current language and version: + +```go-html-template - {{ with .Rotate "version" }} - {{ range . }} -

    {{ .LinkTitle }}

    - {{ end }} ++{{/* Returns roles sorted by weight ascending, then lexicographically ascending */}} ++{{ range .Rotate "role" }} ++

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/page/Sitemap.md index 5dafb86b2,000000000..1d40f48b1 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Sitemap.md +++ b/docs/content/en/methods/page/Sitemap.md @@@ -1,79 -1,0 +1,79 @@@ +--- +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 + +(`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: ++With this project 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/sitemap.xml"} +{{ printf "" | safeHTML }} + + {{ range .Pages }} + + {{ .Permalink }} + {{ if not .Lastmod.IsZero }} + {{ .Lastmod.Format "2006-01-02T15:04:05-07:00" | safeHTML }} + {{ end }} + {{ with .Sitemap.ChangeFreq }} + {{ . }} + {{ end }} + + {{ end }} + +``` + +The change frequency will be `hourly` for the news page, and `monthly` for other pages. + +[sitemap templates]: /templates/sitemap/ diff --cc docs/content/en/methods/page/Sites.md index 308376680,000000000..98aeeab02 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Sites.md +++ b/docs/content/en/methods/page/Sites.md @@@ -1,68 -1,0 +1,86 @@@ +--- +title: Sites - description: Returns a collection of all Site objects, one for each language, ordered by language weight. ++description: Returns a collection of all sites for all dimensions. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Sites + signatures: [PAGE.Sites] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + - This is a convenience method to access `.Site.Sites`. ++{{< deprecated-in 0.156.0 >}} ++Use [`hugo.Sites`] instead. + - With this site configuration: ++[`hugo.Sites`]: /functions/hugo/sites/ ++{{< /deprecated-in >}} ++ ++{{% include "/_common/functions/hugo/sites-collection.md" %}} ++ ++With this project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' - defaultContentLanguageInSubdir = false ++defaultContentLanguageInSubdir = true ++defaultContentVersionInSubdir = true + +[languages.de] ++contentDir = 'content/de' +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +title = 'Projekt Dokumentation' +weight = 1 + +[languages.en] ++contentDir = 'content/en' +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +title = 'Project Documentation' +weight = 2 ++ ++[versions.'v1.0.0'] ++[versions.'v2.0.0'] ++[versions.'v3.0.0'] +{{< /code-toggle >}} + +This template: + +```go-html-template + +``` + +Produces a list of links to each home page: + +```html + +``` + +To render a link to the home page of the [default site](g): + +```go-html-template +{{ with .Sites.Default }} - {{ .Title }} ++ {{ .Title }} +{{ end }} +``` + +This is equivalent to: + +```go-html-template +{{ with index .Sites 0 }} - {{ .Title }} ++ {{ .Title }} +{{ end }} +``` diff --cc docs/content/en/methods/page/TableOfContents.md index f44d660ae,000000000..d5ae21639 mode 100644,000000..100644 --- a/docs/content/en/methods/page/TableOfContents.md +++ b/docs/content/en/methods/page/TableOfContents.md @@@ -1,47 -1,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/current/#atx-headings +[setext]: https://spec.commonmark.org/current/#setext-headings + +This template code: + +```go-html-template +{{ .TableOfContents }} +``` + +Produces this HTML: + +```html + +``` + - By default, the `TableOfContents` method returns an unordered list of level 2 and level 3 headings. You can adjust this in your site configuration: ++By default, the `TableOfContents` method returns an unordered list of level 2 and level 3 headings. You can adjust this in your project configuration: + +{{< code-toggle file=hugo >}} +[markup.tableOfContents] +endLevel = 3 +ordered = false +startLevel = 2 +{{< /code-toggle >}} diff --cc docs/content/en/methods/page/Title.md index 2201266a7,000000000..5135c5ac4 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Title.md +++ b/docs/content/en/methods/page/Title.md @@@ -1,46 -1,0 +1,46 @@@ +--- +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 +``` + +When a page is not backed by a file, the value returned by the `Title` method depends on the page [kind](g). + +Page kind|Page title when the page is not backed by a file +:--|:-- +home|site title +section|section name (capitalized and pluralized) +taxonomy|taxonomy name (capitalized and pluralized) +term|term name (capitalized and pluralized) + - You can disable automatic capitalization and pluralization in your site configuration: ++You can disable automatic capitalization and pluralization in your project configuration: + +{{< 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: ++You can change the capitalization style in your project configuration to one of `ap`, `chicago`, `go`, `firstupper`, or `none`. For example: + +{{< code-toggle file=hugo >}} +titleCaseStyle = "firstupper" +{{< /code-toggle >}} + +See [details]. + +[details]: /configuration/all/#title-case-style diff --cc docs/content/en/methods/page/TranslationKey.md index 1e930687e,000000000..2f6b8f308 mode 100644,000000..100644 --- a/docs/content/en/methods/page/TranslationKey.md +++ b/docs/content/en/methods/page/TranslationKey.md @@@ -1,71 -1,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: ++With this project 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 --cc docs/content/en/methods/page/Translations.md index c342a8618,000000000..58f9024f7 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Translations.md +++ b/docs/content/en/methods/page/Translations.md @@@ -1,86 -1,0 +1,86 @@@ +--- +title: Translations +description: Returns all translations of the given page, excluding the current language, sorted by language weight. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGE.Translations] +--- + - With this site configuration: ++With this project 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 }} + +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of the English site: + +```html + +``` + +Hugo will render this list on the "Book 2" page of the English site: + +```html + +``` diff --cc docs/content/en/methods/pager/PagerSize.md index b2397a3e8,000000000..13aa6c1cd mode 100644,000000..100644 --- a/docs/content/en/methods/pager/PagerSize.md +++ b/docs/content/en/methods/pager/PagerSize.md @@@ -1,30 -1,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]. ++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 [project configuration]. + +[`Paginate`]: /methods/page/paginate/ - [site configuration]: /templates/pagination/#configuration ++[project configuration]: /templates/pagination/#configuration + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages }} + +{{ range $paginator.Pages }} +

    {{ .LinkTitle }}

    +{{ end }} + +{{ with $paginator }} + {{ .PagerSize }} +{{ end }} +``` diff --cc docs/content/en/methods/pager/_index.md index 7a79bf42f,000000000..200640c3a mode 100644,000000..100644 --- a/docs/content/en/methods/pager/_index.md +++ b/docs/content/en/methods/pager/_index.md @@@ -1,6 -1,0 +1,6 @@@ +--- +title: Pager methods +linkTitle: Pager - description: Use these methods with Pager objects when building navigation for a paginated list page. ++description: Use these methods with a Pager object when building navigation for a paginated list page. +keywords: [] +--- diff --cc docs/content/en/methods/pages/ByDate.md index 18f1b985e,000000000..5d1e339a0 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByDate.md +++ b/docs/content/en/methods/pages/ByDate.md @@@ -1,28 -1,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. ++When sorting by date, the value is determined by your [project configuration], defaulting to the `date` field in front matter. + - [site configuration]: /configuration/front-matter/#dates ++[project configuration]: /configuration/front-matter/#dates + +```go-html-template +{{ range .Pages.ByDate }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByDate.Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/pages/ByExpiryDate.md index 703988c4e,000000000..4f34c6e03 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByExpiryDate.md +++ b/docs/content/en/methods/pages/ByExpiryDate.md @@@ -1,28 -1,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. ++When sorting by expiration date, the value is determined by your [project configuration], defaulting to the `expiryDate` field in front matter. + - [site configuration]: /configuration/front-matter/#dates ++[project configuration]: /configuration/front-matter/#dates + +```go-html-template +{{ range .Pages.ByExpiryDate }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByExpiryDate.Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/pages/ByLanguage.md index 36244eb4d,000000000..751e1d8f5 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByLanguage.md +++ b/docs/content/en/methods/pages/ByLanguage.md @@@ -1,24 -1,0 +1,45 @@@ +--- +title: ByLanguage - description: Returns the given page collection sorted by language in ascending order. ++description: Returns the given page collection sorted by language. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [PAGES.ByLanguage] +--- + ++When sorting by language, Hugo orders the page collection using the following priority: ++ ++1. Language weight (ascending) ++1. Date (descending) ++1. LinkTitle (ascending) ++ ++This method is rarely, if ever, needed. Page collections that already contain multiple languages, such as those returned by the [`Rotate`][], [`Translations`][], or [`AllTranslations`][] methods on a `Page` object, are already sorted by language weight. ++ ++This contrived example aggregates pages from all sites and then sorts them by language: ++ +```go-html-template - {{ range .Site.AllPages.ByLanguage }} ++{{ $p := slice }} ++{{ range hugo.Sites }} ++ {{ range .Pages }} ++ {{ $p = $p | append . }} ++ {{ end }} ++{{ end }} ++ ++{{ range $p.ByLanguage }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template - {{ range .Site.AllPages.ByLanguage.Reverse }} ++{{ range $p.ByLanguage.Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` ++ ++[`AllTranslations`]: /methods/page/alltranslations/ ++[`Rotate`]: /methods/page/rotate/ ++[`Translations`]: /methods/page/translations/ diff --cc docs/content/en/methods/pages/ByLastmod.md index 3c03d2a6e,000000000..7fc865e0a mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByLastmod.md +++ b/docs/content/en/methods/pages/ByLastmod.md @@@ -1,28 -1,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. ++When sorting by last modification date, the value is determined by your [project configuration], defaulting to the `lastmod` field in front matter. + - [site configuration]: /configuration/front-matter/#dates ++[project configuration]: /configuration/front-matter/#dates + +```go-html-template +{{ range .Pages.ByLastmod }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByLastmod.Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/pages/ByParam.md index 9544122a6,000000000..fcc9b287f mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByParam.md +++ b/docs/content/en/methods/pages/ByParam.md @@@ -1,34 -1,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. ++If the given parameter is not present in front matter, Hugo will use the matching parameter in your project configuration if present. + +```go-html-template +{{ range .Pages.ByParam "author" }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range (.Pages.ByParam "author").Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +If the targeted parameter is nested, access the field using dot notation: + +```go-html-template +{{ range .Pages.ByParam "author.last_name" }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/pages/ByPublishDate.md index 3dde6fd95,000000000..76d2b2b58 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/ByPublishDate.md +++ b/docs/content/en/methods/pages/ByPublishDate.md @@@ -1,28 -1,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. ++When sorting by publish date, the value is determined by your [project configuration], defaulting to the `publishDate` field in front matter. + - [site configuration]: /configuration/front-matter/#dates ++[project configuration]: /configuration/front-matter/#dates + +```go-html-template +{{ range .Pages.ByPublishDate }} +

    {{ .LinkTitle }}

    +{{ end }} +``` + +To sort in descending order: + +```go-html-template +{{ range .Pages.ByPublishDate.Reverse }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/pages/GroupByDate.md index 7ef4843a4,000000000..19f791886 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/GroupByDate.md +++ b/docs/content/en/methods/pages/GroupByDate.md @@@ -1,63 -1,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. ++When grouping by date, the value is determined by your [project 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 ++[project 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByDate "January 2006" "asc" }} +

    {{ .Key }}

    + +{{ 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +## Layout string + +{{% include "/_common/time-layout-string.md" %}} diff --cc docs/content/en/methods/pages/GroupByExpiryDate.md index d209e6c2b,000000000..7fe0282c2 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/GroupByExpiryDate.md +++ b/docs/content/en/methods/pages/GroupByExpiryDate.md @@@ -1,63 -1,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. ++When grouping by expiration date, the value is determined by your [project 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 ++[project 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByExpiryDate "January 2006" "asc" }} +

    {{ .Key }}

    + +{{ 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +## Layout string + +{{% include "/_common/time-layout-string.md" %}} diff --cc docs/content/en/methods/pages/GroupByLastmod.md index 8729cd3c9,000000000..45da5af31 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/GroupByLastmod.md +++ b/docs/content/en/methods/pages/GroupByLastmod.md @@@ -1,63 -1,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. ++When grouping by last modification date, the value is determined by your [project 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 ++[project 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByLastmod "January 2006" "asc" }} +

    {{ .Key }}

    + +{{ 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +## Layout string + +{{% include "/_common/time-layout-string.md" %}} diff --cc docs/content/en/methods/pages/GroupByPublishDate.md index 50e12f085,000000000..629a8480a mode 100644,000000..100644 --- a/docs/content/en/methods/pages/GroupByPublishDate.md +++ b/docs/content/en/methods/pages/GroupByPublishDate.md @@@ -1,63 -1,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. ++When grouping by publish date, the value is determined by your [project 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 ++[project 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +To sort the groups in ascending order: + +```go-html-template +{{ range .Pages.GroupByPublishDate "January 2006" "asc" }} +

    {{ .Key }}

    + +{{ 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" }} +

    {{ .Key }}

    + +{{ end }} +``` + +## Layout string + +{{% include "/_common/time-layout-string.md" %}} diff --cc docs/content/en/methods/resource/Exif.md index 4df1eef5b,000000000..e1cd2ab59 mode 100644,000000..100644 --- a/docs/content/en/methods/resource/Exif.md +++ b/docs/content/en/methods/resource/Exif.md @@@ -1,88 -1,0 +1,88 @@@ +--- +title: Exif +description: Applicable to JPEG, PNG, TIFF, and WebP images, returns an object containing Exif metadata. +categories: [] +keywords: ['metadata'] +params: + functions_and_methods: + returnType: meta.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 object containing [Exif][Exif_Definition] metadata. + +To extract [Exif][Exif_Definition], [IPTC][IPTC_Definition], and [XMP][XMP_Definition] metadata, use the [`Meta`] method instead. + +> [!note] +> Metadata is not preserved during image transformation. Use this method with the _original_ image resource to extract metadata from JPEG, PNG, TIFF, and WebP images. + +## Methods + +### Date + +(`time.Time`) Returns the image creation date/time. Format with the [`time.Format`] function. + +### Lat + +(`float64`) Returns the GPS latitude in degrees from Exif metadata. + +### Long + +(`float64`) Returns the GPS longitude in degrees from Exif metadata. + +### Tags + - (`meta.Tags`) Returns a collection of available Exif fields for this image. Availability is determined by the [`includeFields`][] and [`excludeFields`][] settings in your site configuration. ++(`meta.Tags`) Returns a collection of available Exif fields for this image. Availability is determined by the [`includeFields`][] and [`excludeFields`][] settings in your project configuration. + +## Examples + +To list the creation date, latitude, and longitude: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} +
     +      {{ printf "%-25s %v\n" "Date" .Date }}
     +      {{ printf "%-25s %v\n" "Latitude" .Lat }}
     +      {{ printf "%-25s %v\n" "Longitude" .Long }}
     +    
    + {{ end }} +{{ end }} +``` + +To list the available Exif fields: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} +
     +      {{ range $k, $v := .Tags -}}
     +        {{ printf "%-25s %v\n" $k $v }}
     +      {{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +To list specific Exif fields: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} +
     +      {{ with .Tags.ApertureValue }}{{ printf "%-25s %v\n" "ApertureValue" . }}{{ end }}
     +      {{ with .Tags.BrightnessValue }}{{ printf "%-25s %v\n" "BrightnessValue" . }}{{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +[`excludeFields`]: /configuration/imaging/#excludefields +[`includeFields`]: /configuration/imaging/#includefields +[`Meta`]: /methods/resource/meta/ +[`time.Format`]: /functions/time/format/ +[Exif_Definition]: https://en.wikipedia.org/wiki/Exif +[IPTC_Definition]: https://en.wikipedia.org/wiki/IPTC_Information_Interchange_Model +[XMP_Definition]: https://en.wikipedia.org/wiki/Extensible_Metadata_Platform diff --cc docs/content/en/methods/resource/Meta.md index a1c8a9010,000000000..b02e99862 mode 100644,000000..100644 --- a/docs/content/en/methods/resource/Meta.md +++ b/docs/content/en/methods/resource/Meta.md @@@ -1,167 -1,0 +1,167 @@@ +--- +title: Meta +description: Applicable to JPEG, PNG, TIFF, and WebP images, returns an object containing Exif, IPTC, and XMP metadata. +categories: [] +keywords: ['metadata'] +params: + functions_and_methods: + returnType: meta.MetaInfo + signatures: [RESOURCE.Meta] +--- + +{{< new-in 0.155.3 />}} + +{{% include "/_common/methods/resource/global-page-remote-resources.md" %}} + +Applicable to JPEG, PNG, TIFF, and WebP images, the `Meta` method on an image `Resource` object returns an object containing [Exif][Exif_Definition], [IPTC][IPTC_Definition], and [XMP][XMP_Definition] metadata. + +To extract Exif metadata only, use the [`Exif`] method instead. + +> [!note] +> Metadata is not preserved during image transformation. Use this method with the _original_ image resource to extract metadata from JPEG, PNG, TIFF, and WebP images. + +## Methods + +### Date + +(`time.Time`) Returns the image creation date/time. Format with the [`time.Format`] function. + +### Lat + +(`float64`) Returns the GPS latitude in degrees from Exif metadata, with a fallback to XMP metadata. + +### Long + +(`float64`) Returns the GPS longitude in degrees from Exif metadata, with a fallback to XMP metadata. + +### Orientation + +(`int`) Returns the value of the Exif `Orientation` tag, one of eight possible values: + +Value|Description +:--|:-- +`1`|Horizontal (normal) +`2`|Mirrored horizontal +`3`|Rotated 180 degrees +`4`|Mirrored vertical +`5`|Mirrored horizontal and rotated 270 degrees clockwise +`6`|Rotated 90 degrees clockwise +`7`|Mirrored horizontal and rotated 90 degrees clockwise +`8`|Rotated 270 degrees clockwise +{class="!mt-0"} + +> [!tip] +> Use the [`images.AutoOrient`] image filter to rotate and flip an image as needed per its Exif orientation tag + +### Exif + - (`meta.Tags`) Returns a collection of available Exif fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your site configuration. ++(`meta.Tags`) Returns a collection of available Exif fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your project configuration. + +### IPTC + - (`meta.Tags`) Returns a collection of available IPTC fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your site configuration. ++(`meta.Tags`) Returns a collection of available IPTC fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your project configuration. + +### XMP + - (`meta.Tags`) Returns a collection of available XMP fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your site configuration. ++(`meta.Tags`) Returns a collection of available XMP fields for this image. Availability is determined by the [`sources`][] setting and specific fields are managed via the [`fields`][] setting, both of which are managed in your project configuration. + +## Examples + +To list the creation date, latitude, longitude, and orientation: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ printf "%-25s %v\n" "Date" .Date }}
     +      {{ printf "%-25s %v\n" "Latitude" .Lat }}
     +      {{ printf "%-25s %v\n" "Longitude" .Long }}
     +      {{ printf "%-25s %v\n" "Orientation" .Orientation }}
     +    
    + {{ end }} +{{ end }} +``` + +To list the available Exif fields: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ range $k, $v := .Exif -}}
     +        {{ printf "%-25s %v\n" $k $v }}
     +      {{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +To list the available IPTC fields: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ range $k, $v := .IPTC -}}
     +        {{ printf "%-25s %v\n" $k $v }}
     +      {{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +To list the available XMP fields: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ range $k, $v := .XMP -}}
     +        {{ printf "%-25s %v\n" $k $v }}
     +      {{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +To list the available Exif, IPTC, and XMP fields together: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ range $k, $v := merge .Exif .IPTC .XMP -}}
     +        {{ printf "%-25s %v\n" $k $v }}
     +      {{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +To list specific values: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Meta }} +
     +      {{ with .Exif.ApertureValue }}{{ printf "%-25s %v\n" "ApertureValue" . }}{{ end }}
     +      {{ with .Exif.BrightnessValue }}{{ printf "%-25s %v\n" "BrightnessValue" . }}{{ end }}
     +
     +      {{ with .IPTC.Headline }}{{ printf "%-25s %v\n" "Headline" . }}{{ end }}
     +      {{ with index .IPTC "Province-State" }}{{ printf "%-25s %v\n" "Province-State" . }}{{ end }}
     +
     +      {{ with .XMP.Creator }}{{ printf "%-25s %v\n" "Creator" . }}{{ end }}
     +      {{ with .XMP.Subject }}{{ printf "%-25s %v\n" "Subject" . }}{{ end }}
     +    
    + {{ end }} +{{ end }} +``` + +[`Exif`]: /methods/resource/exif/ +[`fields`]: /configuration/imaging/#fields +[`images.AutoOrient`]: /functions/images/autoorient/ +[`sources`]: /configuration/imaging/#sources +[`time.Format`]: /functions/time/format/ +[Exif_Definition]: https://en.wikipedia.org/wiki/Exif +[IPTC_Definition]: https://en.wikipedia.org/wiki/IPTC_Information_Interchange_Model +[XMP_Definition]: https://en.wikipedia.org/wiki/Extensible_Metadata_Platform diff --cc docs/content/en/methods/resource/_index.md index edfbc5b14,000000000..c6012e75b mode 100644,000000..100644 --- a/docs/content/en/methods/resource/_index.md +++ b/docs/content/en/methods/resource/_index.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: Resource methods +linkTitle: Resource - description: Use these methods with global, page, and remote Resource objects. ++description: Use these methods with a global, page, or remote Resource object. +categories: [] +keywords: [] +--- diff --cc docs/content/en/methods/site/AllPages.md index 90cceee8c,000000000..aec40d558 mode 100644,000000..100644 --- a/docs/content/en/methods/site/AllPages.md +++ b/docs/content/en/methods/site/AllPages.md @@@ -1,22 -1,0 +1,27 @@@ +--- +title: AllPages +description: Returns a collection of all pages in all languages. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Pages + signatures: [SITE.AllPages] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + ++{{< deprecated-in 0.156.0 >}} ++See [details](https://discourse.gohugo.io/t/56732). ++{{< /deprecated-in >}} ++ +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 }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/site/BaseURL.md index 3644443cb,000000000..7b1b5e870 mode 100644,000000..100644 --- a/docs/content/en/methods/site/BaseURL.md +++ b/docs/content/en/methods/site/BaseURL.md @@@ -1,32 -1,0 +1,32 @@@ +--- +title: BaseURL - description: Returns the base URL as defined in the site configuration. ++description: Returns the base URL as defined in your project configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SITE.BaseURL] +--- + - Site configuration: ++Project 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 --cc docs/content/en/methods/site/BuildDrafts.md index 4beceeb6b,000000000..7b5019ffe mode 100644,000000..100644 --- a/docs/content/en/methods/site/BuildDrafts.md +++ b/docs/content/en/methods/site/BuildDrafts.md @@@ -1,28 -1,0 +1,33 @@@ +--- +title: BuildDrafts - description: Reports whether the current build includes draft pages. ++description: Reports reports whether draft publishing is enabled for the current build. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [SITE.BuildDrafts] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + ++{{< deprecated-in 0.156.0 >}} ++See [details](https://discourse.gohugo.io/t/56732). ++{{< /deprecated-in >}} ++ +By default, draft pages are not published when building a site. You can change this behavior with a command line flag: + +```sh - hugo --buildDrafts ++hugo build --buildDrafts +``` + - Or by setting `buildDrafts` to `true` in your site configuration: ++Or by setting `buildDrafts` to `true` in your project 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 --cc docs/content/en/methods/site/Config.md index d1b4d1f42,000000000..9cc885650 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Config.md +++ b/docs/content/en/methods/site/Config.md @@@ -1,52 -1,0 +1,52 @@@ +--- +title: Config - description: Returns a subset of the site configuration. ++description: Returns a subset of your project 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. ++The `Config` method on a `Site` object provides access to a subset of your project 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 --cc docs/content/en/methods/site/Copyright.md index dd8bdb4a3,000000000..e73ff66bc mode 100644,000000..100644 --- a/docs/content/en/methods/site/Copyright.md +++ b/docs/content/en/methods/site/Copyright.md @@@ -1,22 -1,0 +1,22 @@@ +--- +title: Copyright - description: Returns the copyright notice as defined in the site configuration. ++description: Returns the copyright notice as defined in your project configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SITE.Copyright] +--- + - Site configuration: ++Project configuration: + +{{< code-toggle file=hugo >}} +copyright = '© 2023 ABC Widgets, Inc.' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Copyright }} → © 2023 ABC Widgets, Inc. +``` diff --cc docs/content/en/methods/site/Data.md index 296851874,000000000..e54bad0f1 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Data.md +++ b/docs/content/en/methods/site/Data.md @@@ -1,103 -1,0 +1,108 @@@ +--- +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] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + ++{{< deprecated-in 0.156.0 >}} ++Use [`hugo.Data`](/functions/hugo/data/) instead. ++{{< /deprecated-in >}} ++ +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 }} +

    {{ $category | title }}

    +
      + {{ range $books }} +
    • {{ .title }} ({{ .isbn }})
    • + {{ end }} +
    +{{ end }} +``` + +Hugo renders this to: + +```html +

    Fiction

    +
      +
    • The Hunchback of Notre Dame (978-0140443530)
    • +
    • Les Misérables (978-0451419439)
    • +
    +

    Nonfiction

    +
      +
    • The Ancien Régime and the Revolution (978-0141441641)
    • +
    • Interpreting the French Revolution (978-0521280495)
    • +
    +``` + +To limit the listing to fiction, and sort by title: + +```go-html-template +
      + {{ range sort .Site.Data.books.fiction "title" }} +
    • {{ .title }} ({{ .author }})
    • + {{ end }} +
    +``` + +To find a fiction book by ISBN: + +```go-html-template +{{ range where .Site.Data.books.fiction "isbn" "978-0140443530" }} +
  • {{ .title }} ({{ .author }})
  • +{{ 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 --cc docs/content/en/methods/site/Dimension.md index 67297a353,000000000..7c2001640 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Dimension.md +++ b/docs/content/en/methods/site/Dimension.md @@@ -1,36 -1,0 +1,36 @@@ +--- +title: Dimension +description: Returns the dimension object for the given dimension for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.SiteDimension + signatures: [SITE.Dimension DIMENSION] +--- + +{{< new-in 0.153.0 />}} + +The `Dimension` method on a `Site` object returns the dimension object for the given [dimension](g). + - The `DIMENSION` argument must be one of `language`, `role`, or `version`. ++The `DIMENSION` argument must be one of `language`, `version`, or `role`. + +Example|Returns|Equivalent to +:--|:--|:-- +`{{ .Site.Dimension "language" }}`|`langs.Language`|`{{ .Site.Language }}` - `{{ .Site.Dimension "role" }}`|`roles.Role`|`{{ .Site.Role }}` +`{{ .Site.Dimension "version" }}`|`version.Version`|`{{ .Site.Version }}` ++`{{ .Site.Dimension "role" }}`|`roles.Role`|`{{ .Site.Role }}` + +```go-html-template +{{ $languageObject := .Site.Dimension "language" }} +{{ $languageObject.IsDefault }} → true +{{ $languageObject.Name }} → en + - {{ $roleObject := .Site.Dimension "role" }} - {{ $roleObject.IsDefault }} → true - {{ $roleObject.Name }} → guest - +{{ $versionObject := .Site.Dimension "version" }} +{{ $versionObject.IsDefault }} → true +{{ $versionObject.Name }} → v1.0.0 ++ ++{{ $roleObject := .Site.Dimension "role" }} ++{{ $roleObject.IsDefault }} → true ++{{ $roleObject.Name }} → guest +``` diff --cc docs/content/en/methods/site/GetPage.md index 34f531720,000000000..f21061a35 mode 100644,000000..100644 --- a/docs/content/en/methods/site/GetPage.md +++ b/docs/content/en/methods/site/GetPage.md @@@ -1,105 -1,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 {file="layouts/home.html"} +{{ with .Site.GetPage "/works/paintings" }} +
      + {{ range .Pages }} +
    • {{ .Title }} by {{ .Params.artist }}
    • + {{ end }} +
    +{{ end }} +``` + +Is rendered to: + +```html +
      +
    • Starry Night by Vincent van Gogh
    • +
    • The Mona Lisa by Leonardo da Vinci
    • +
    +``` + +To get a regular page instead of a section page: + +```go-html-template {file="layouts/home.html"} +{{ 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 where hugo.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 {file="layouts/home.html"} +{{ with .Site.GetPage "/headless" }} + {{ range .Resources.ByType "image" }} + + {{ end }} +{{ end }} +``` diff --cc docs/content/en/methods/site/Home.md index 11ce617ef,000000000..57b2ceaae mode 100644,000000..100644 --- a/docs/content/en/methods/site/Home.md +++ b/docs/content/en/methods/site/Home.md @@@ -1,39 -1,0 +1,39 @@@ +--- +title: Home +description: Returns the home Page object for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Page + signatures: [SITE.Home] +--- + +The `Home` method on a `Site` object is a convenient way to access the home page, and is functionally equivalent to: + +```go-html-template +{{ .Site.GetPage "/" }} +``` + +Because it returns a `Page` object, you can use any of the available [page methods][] by chaining them. For example: + +```go-html-template +{{ .Site.Home.Store.Set "greeting" "Hello" }} +``` + +This method is commonly used to generate a link to the home page. For example: + - Site configuration: ++Project 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/ +``` + +[page methods]: /methods/page/ diff --cc docs/content/en/methods/site/IsDefault.md index 000000000,000000000..251a3bbe4 new file mode 100644 --- /dev/null +++ b/docs/content/en/methods/site/IsDefault.md @@@ -1,0 -1,0 +1,50 @@@ ++--- ++title: IsDefault ++description: Reports whether the given site is the default site across all dimensions. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ returnType: bool ++ signatures: [SITE.IsDefault] ++--- ++ ++{{< new-in 0.156.0 />}} ++ ++The `IsDefault` method on a `Site` object reports whether the given site is the [default site](g) across all dimensions: [language](g), [version](g), and [role](g). This is useful to ensure that a block of code executes only once per build, regardless of the number of [sites](g) generated by your [dimensions](g). ++ ++For example, the following configuration defines a matrix of sites across language and version dimensions. ++ ++{{< code-toggle file=hugo >}} ++[languages.de] ++contentDir = 'content/de' ++languageCode = 'de-DE' ++languageDirection = 'ltr' ++languageName = 'Deutsch' ++title = 'Projekt Dokumentation' ++weight = 1 ++ ++[languages.en] ++contentDir = 'content/en' ++languageCode = 'en-US' ++languageDirection = 'ltr' ++languageName = 'English' ++title = 'Project Documentation' ++weight = 2 ++ ++[versions.'v1.0.0'] ++[versions.'v2.0.0'] ++[versions.'v3.0.0'] ++{{< /code-toggle >}} ++ ++If you call an initialization partial to handle one-time build logic or global variable setup, wrap that call in an [`if`][] statement using this function. This prevents the logic from being executed for every dimensional variation. ++ ++```go-html-template ++{{ if .Site.IsDefault }} ++ {{ partial "init.html" . }} ++{{ end }} ++``` ++ ++In this setup, the code block is only executed for the English version v3.0.0 site. English is selected because it has the lowest weight, and version v3.0.0 is selected because it is the first version when sorted semantically in descending order. ++ ++[`if`]: /functions/go-template/if/ diff --cc docs/content/en/methods/site/Language.md index 2550ad585,000000000..8e8cb7372 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Language.md +++ b/docs/content/en/methods/site/Language.md @@@ -1,99 -1,0 +1,105 @@@ +--- +title: Language - description: Returns the language object for the given site. ++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 `Page` object returns the language object for the given page. The language object is derived from the language definition in the site configuration. ++The `Language` method on a `Site` object returns the `Language` object for the given site, derived from the language definition in your project configuration. + - You can also use the `Language` method on a `Page` object. See [details]. ++You can also use the `Language` method on a `Page` object. See [details][]. + +## Methods + - The examples below assume the following in the site configuration: ++The examples below assume the following in your project configuration: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +weight = 1 +{{< /code-toggle >}} + +### IsDefault + +{{< new-in 0.153.0 />}} + - (`bool`) Reports whether this is the default language object as defined by the [`defaultContentLanguage`][] setting in the site configuration. ++(`bool`) Reports whether this is the [default language][]. + +```go-html-template +{{ .Site.Language.IsDefault }} → true +``` + +### Lang + - (`string`) The language tag as defined by [RFC 5646]. This is the lower cased key from the site configuration. ++(`string`) Returns the language tag as defined by [RFC 5646][]. This is the lowercased key from your project configuration. + +```go-html-template +{{ .Site.Language.Lang }} → de +``` + +### LanguageCode + - (`string`) The language code from the site configuration. Falls back to `Lang` if not defined. ++(`string`) Returns the [`languageCode`][] from your project 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`. ++(`string`) Returns the [`languageDirection`][] from your project configuration. + +```go-html-template +{{ .Site.Language.LanguageDirection }} → ltr +``` + +### LanguageName + - (`string`) The language name from the site configuration. ++(`string`) Returns the [`languageName`][] from your project configuration. + +```go-html-template +{{ .Site.Language.LanguageName }} → Deutsch +``` + +### Name + - (`string`) The language tag as defined by [RFC 5646]. This is the lower cased key from the site configuration. This is an alias for `Lang`. ++{{< new-in 0.153.0 />}} ++ ++(`string`) Returns the language tag as defined by [RFC 5646][]. This is the lowercased key from your project configuration. This is an alias for `Lang`. + +```go-html-template +{{ .Site.Language.Name }} → de +``` + +### 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. ++(`int`) Returns the language [`weight`][] from your project configuration. + +```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 + +``` + - [`defaultContentLanguage`]: /configuration/all/#defaultcontentlanguage ++[`languageCode`]: /configuration/languages/#languagecode ++[`languageDirection`]: /configuration/languages/#languagedirection ++[`languageName`]: /configuration/languages/#languagename ++[`weight`]: /configuration/languages/#weight ++[default language]: /quick-reference/glossary/#default-language +[details]: /methods/page/language/ +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 diff --cc docs/content/en/methods/site/LanguagePrefix.md index 81a5e8607,000000000..7b92c5950 mode 100644,000000..100644 --- a/docs/content/en/methods/site/LanguagePrefix.md +++ b/docs/content/en/methods/site/LanguagePrefix.md @@@ -1,51 -1,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: ++Consider this project 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 --cc docs/content/en/methods/site/Languages.md index 056d6193a,000000000..69277f329 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Languages.md +++ b/docs/content/en/methods/site/Languages.md @@@ -1,58 -1,0 +1,63 @@@ +--- +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] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + - 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. ++{{< deprecated-in 0.156.0 >}} ++See [details](https://discourse.gohugo.io/t/56732). ++{{< /deprecated-in >}} ++ ++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 your project configuration. + +To inspect the data structure: + +```go-html-template +
    {{ debug.Dump .Site.Languages }}
    +``` + - With this site configuration: ++With this project 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 +
      + {{ range .Site.Languages }} +
    • {{ .Title }} ({{ .LanguageName }})
    • + {{ end }} +
    +``` + +Is rendered to: + +```html +
      +
    • Projekt Dokumentation (Deutsch)
    • +
    • Project Documentation (English)
    • +
    +``` diff --cc docs/content/en/methods/site/MainSections.md index 6a0dbdc74,000000000..0df8de649 mode 100644,000000..100644 --- a/docs/content/en/methods/site/MainSections.md +++ b/docs/content/en/methods/site/MainSections.md @@@ -1,54 -1,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. ++description: Returns a slice of the main section names as defined in your project 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: ++Project 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. ++If `mainSections` is not defined in your project 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. ++When creating a theme, instead of hardcoding section names when listing the most relevant pages on the front page, instruct users to set `mainSections` in their project configuration. + +Then your _home_ template can do something like this: + +```go-html-template {file="layouts/home.html"} +{{ range where .Site.RegularPages "Section" "in" .Site.MainSections }} +

    {{ .LinkTitle }}

    +{{ end }} +``` diff --cc docs/content/en/methods/site/Param.md index 929e30e98,000000000..b2ec5d9bb mode 100644,000000..100644 --- a/docs/content/en/methods/site/Param.md +++ b/docs/content/en/methods/site/Param.md @@@ -1,28 -1,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. ++The `Param` method on a `Site` object is a convenience method to return the value of a user-defined parameter in your project 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 --cc docs/content/en/methods/site/Params.md index 8467be41d,000000000..62bc8f1f5 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Params.md +++ b/docs/content/en/methods/site/Params.md @@@ -1,42 -1,0 +1,42 @@@ +--- +title: Params - description: Returns a map of custom parameters as defined in the site configuration. ++description: Returns a map of custom parameters as defined in your project configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: maps.Params + signatures: [SITE.Params] +--- + - With this site configuration: ++With this project 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 --cc docs/content/en/methods/site/Role.md index cec6f8ffa,000000000..b8aee5f4a mode 100644,000000..100644 --- a/docs/content/en/methods/site/Role.md +++ b/docs/content/en/methods/site/Role.md @@@ -1,34 -1,0 +1,34 @@@ +--- +title: Role - description: Returns the role object for the given site. ++description: Returns the Role object for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: - returnType: roles.RoleSite ++ returnType: roles.Role + signatures: [SITE.Role] +--- + +{{< new-in 0.153.0 />}} + - The `Role` method on a `Site` object returns the role object for the given site. The role object is derived from the role definition in the site configuration. ++The `Role` method on a `Site` object returns the `Role` object for the given site, derived from the role definition in your project configuration. + +## Methods + +### IsDefault + - (`bool`) Reports whether this is the default role object as defined by the [`defaultContentRole`][] setting in the site configuration. ++(`bool`) Reports whether this is the [default role][]. + +```go-html-template +{{ .Site.Role.IsDefault }} → true +``` + +### Name + - (`string`) Returns the role name. This is the lower cased key from the site configuration. ++(`string`) Returns the role name. This is the lowercased key from your project configuration. + +```go-html-template +{{ .Site.Role.Name }} → guest +``` + - [`defaultContentRole`]: /configuration/all/#defaultcontentrole ++[default role]: /quick-reference/glossary/#default-role diff --cc docs/content/en/methods/site/Sites.md index 7d5d02724,000000000..7a06e232f mode 100644,000000..100644 --- a/docs/content/en/methods/site/Sites.md +++ b/docs/content/en/methods/site/Sites.md @@@ -1,66 -1,0 +1,86 @@@ +--- +title: Sites - description: Returns a collection of all Site objects, one for each language, ordered by default content language then by language weight. ++description: Returns a collection of all sites for all dimensions. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.Sites + signatures: [SITE.Sites] ++expiryDate: '2028-02-18' # deprecated 2026-02-18 in v0.156.0 +--- + - With this site configuration: ++{{< deprecated-in 0.156.0 >}} ++Use [`hugo.Sites`] instead. ++ ++[`hugo.Sites`]: /functions/hugo/sites/ ++{{< /deprecated-in >}} ++ ++{{% include "/_common/functions/hugo/sites-collection.md" %}} ++ ++With this project configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' - defaultContentLanguageInSubdir = false ++defaultContentLanguageInSubdir = true ++defaultContentVersionInSubdir = true + +[languages.de] ++contentDir = 'content/de' +languageCode = 'de-DE' +languageDirection = 'ltr' +languageName = 'Deutsch' +title = 'Projekt Dokumentation' +weight = 1 + +[languages.en] ++contentDir = 'content/en' +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +title = 'Project Documentation' +weight = 2 ++ ++[versions.'v1.0.0'] ++[versions.'v2.0.0'] ++[versions.'v3.0.0'] +{{< /code-toggle >}} + +This template: + +```go-html-template + +``` + +Produces a list of links to each home page: + +```html + +``` + +To render a link to the home page of the [default site](g): + +```go-html-template +{{ with .Site.Sites.Default }} - {{ .Title }} ++ {{ .Title }} +{{ end }} +``` + +This is equivalent to: + +```go-html-template +{{ with index .Site.Sites 0 }} - {{ .Title }} ++ {{ .Title }} +{{ end }} +``` diff --cc docs/content/en/methods/site/Taxonomies.md index ab28aff1d,000000000..4417c9ef7 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Taxonomies.md +++ b/docs/content/en/methods/site/Taxonomies.md @@@ -1,181 -1,0 +1,181 @@@ +--- +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: ++With this project 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 +
      + {{ range .Site.Taxonomies.genres.suspense }} +
    • {{ .LinkTitle }}
    • + {{ end }} +
    +``` + +Hugo renders this to: + +```html + +``` + +> [!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 + +``` + +### 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 + +``` + +### Render a site's taxonomies + +The following example displays all terms in a site's tags taxonomy: + +```go-html-template + +``` + +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 }} + + {{ end }} +{{ end }} +``` + +[taxonomies]: /content-management/taxonomies/ diff --cc docs/content/en/methods/site/Title.md index 935edda0c,000000000..ad8a48c3c mode 100644,000000..100644 --- a/docs/content/en/methods/site/Title.md +++ b/docs/content/en/methods/site/Title.md @@@ -1,22 -1,0 +1,22 @@@ +--- +title: Title - description: Returns the title as defined in the site configuration. ++description: Returns the title as defined in your project configuration. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string + signatures: [SITE.Title] +--- + - Site configuration: ++Project configuration: + +{{< code-toggle file=hugo >}} +title = 'My Documentation Site' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Title }} → My Documentation Site +``` diff --cc docs/content/en/methods/site/Version.md index 1c8870cc5,000000000..d424d4666 mode 100644,000000..100644 --- a/docs/content/en/methods/site/Version.md +++ b/docs/content/en/methods/site/Version.md @@@ -1,34 -1,0 +1,34 @@@ +--- +title: Version - description: Returns the version object for the given site. ++description: Returns the Version object for the given site. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: versions.Version + signatures: [SITE.Version] +--- + +{{< new-in 0.153.0 />}} + - The `Version` method on a `Site` object returns the version object for the given site. The version object is derived from the version definition in the site configuration. ++The `Version` method on a `Site` object returns the `Version` object for the given site, derived from the version definition in your project configuration. + +## Methods + +### IsDefault + - (`bool`) Reports whether this is the default version object as defined by the [`defaultContentVersion`][] setting in the site configuration. ++(`bool`) Reports whether this is the [default version][]. + +```go-html-template +{{ .Site.Version.IsDefault }} → true +``` + +### Name + - (`string`) Returns the version name. This is the lower cased key from the site configuration. ++(`string`) Returns the version name. This is the lowercased key from your project configuration. + +```go-html-template +{{ .Site.Version.Name }} → v1.0.0 +``` + - [`defaultContentVersion`]: /configuration/all/#defaultcontentversion ++[default version]: /quick-reference/glossary/#default-version diff --cc docs/content/en/methods/site/_index.md index f395a3693,000000000..4f878a100 mode 100644,000000..100644 --- a/docs/content/en/methods/site/_index.md +++ b/docs/content/en/methods/site/_index.md @@@ -1,8 -1,0 +1,8 @@@ +--- +title: Site methods +linkTitle: Site - description: Use these methods with Site objects. ++description: Use these methods with a Site object. +categories: [] +keywords: [] +aliases: [/variables/site/] +--- diff --cc docs/content/en/methods/taxonomy/_index.md index 13acdb10c,000000000..9cf4c7456 mode 100644,000000..100644 --- a/docs/content/en/methods/taxonomy/_index.md +++ b/docs/content/en/methods/taxonomy/_index.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: Taxonomy methods +linkTitle: Taxonomy - description: Use these methods with Taxonomy objects. ++description: Use these methods with a Taxonomy object. +keywords: [] +aliases: [/variables/taxonomy/] +--- diff --cc docs/content/en/methods/time/_index.md index 8114664d3,000000000..067d91a7e mode 100644,000000..100644 --- a/docs/content/en/methods/time/_index.md +++ b/docs/content/en/methods/time/_index.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: Time methods +linkTitle: Time - description: Use these methods with time.Time values. ++description: Use these methods with a time.Time value. +categories: [] +keywords: [] +--- diff --cc docs/content/en/quick-reference/glossary/build-artifacts.md index 000000000,000000000..c3c2dbd6a new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/build-artifacts.md @@@ -1,0 -1,0 +1,5 @@@ ++--- ++title: build artifacts ++--- ++ ++The _build artifacts_ are the static files produced during the [_build_](g) process. These assets are stored in the `public` directory by default and represent the final, ready-to-deploy output of the project. diff --cc docs/content/en/quick-reference/glossary/build.md index 9a4df3bb1,000000000..4d4f73cb4 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/build.md +++ b/docs/content/en/quick-reference/glossary/build.md @@@ -1,5 -1,0 +1,5 @@@ +--- +title: build +--- + - To _build_ (verb) a site is to generate HTML files and assets such as images, CSS files, and JavaScript files. The build process includes rendering and resource transformations. ++To _build_ (verb) is to generate the static files for a [_project_](g), including HTML, images, CSS, and JavaScript. This process involves rendering templates, transforming resources, and resolving the matrix of [_language_](g), [_role_](g), and [_version_](g) defined in your project configuration. diff --cc docs/content/en/quick-reference/glossary/canonical-output-format.md index 88842a11f,000000000..d360083ba mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/canonical-output-format.md +++ b/docs/content/en/quick-reference/glossary/canonical-output-format.md @@@ -1,14 -1,0 +1,14 @@@ +--- +title: canonical output format +--- + - The _canonical output format_ is the [_output format_](g) for the current page where the format's [`rel`][] property is set to `canonical` in your site configuration, if such a format exists. If there is only one _output format_ for the current page, that is the _canonical output format_, regardless of whether the format's `rel` property is set to `canonical`. ++The _canonical output format_ is the [_output format_](g) for the current page where the format's [`rel`][] property is set to `canonical` in your project configuration, if such a format exists. If there is only one _output format_ for the current page, that is the _canonical output format_, regardless of whether the format's `rel` property is set to `canonical`. + + By default, `html` is the only predefined _output format_ with this setting; the `rel` property for all others is set to `alternate`. If two or more _output formats_ for the current page have their `rel` property set to `canonical`, the _canonical output format_ is the first one specified in: + + - The [`outputs`][outputs_front_matter] front matter field of the current page, or - - The [`outputs`][outputs_site_config] section of your site configuration for the current [_page kind_](g). ++ - The [`outputs`][outputs_project_config] section of your project configuration for the current [_page kind_](g). + + [`rel`]: /configuration/output-formats/#rel + [outputs_front_matter]: /configuration/outputs/#outputs-per-page - [outputs_site_config]: /configuration/outputs/#outputs-per-page-kind ++ [outputs_project_config]: /configuration/outputs/#outputs-per-page-kind diff --cc docs/content/en/quick-reference/glossary/component.md index 11820608b,000000000..1843b1838 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/component.md +++ b/docs/content/en/quick-reference/glossary/component.md @@@ -1,18 -1,0 +1,16 @@@ +--- +title: component +--- + - A _component_ is a collection of related files, housed within the [_unified file system_](g), that fulfills a specific function in building a Hugo website. These components are categorized into seven types: [_archetypes_](g), assets, content, data, templates, [_translation tables_](g), and static files, and can be defined within the project or provided by [_modules_](g). - - Each component has a dedicated directory within the unified file system: ++A _component_ is a collection of related files, housed within the [_unified file system_](g), that fulfills a specific function in building a Hugo [_project_](g). These components are categorized into seven types: [_archetypes_](g), assets, content, data, templates, [_translation tables_](g), and static files, and can be defined within the project or provided by [_modules_](g). Each component has a dedicated directory within the unified file system: + + Component|Directory within the unified file system + :--|:-- + archetypes|`archetypes` + assets|`assets` + content|`content` + data|`data` + templates|`layouts` + translation tables|`i18n` + static files|`static` + {class="!mt-0"} diff --cc docs/content/en/quick-reference/glossary/default-language.md index 000000000,000000000..73f942c2f new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/default-language.md @@@ -1,0 -1,0 +1,9 @@@ ++--- ++title: default language ++--- ++ ++The _default language_ is is the value defined by the [`defaultContentLanguage`][] setting, falling back to the first language in the project, and finally to `en`. The first language is identified by the lowest [_weight_](g), using lexicographical order as the final fallback if weights are tied or undefined. ++ ++ See also: [_language_](g). ++ ++ [`defaultContentLanguage`]: /configuration/all/#defaultcontentlanguage diff --cc docs/content/en/quick-reference/glossary/default-role.md index 000000000,000000000..f065189c1 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/default-role.md @@@ -1,0 -1,0 +1,9 @@@ ++--- ++title: default role ++--- ++ ++The _default role_ is the value defined by the [`defaultContentRole`][] setting, falling back to the first role in the project, and finally to `guest`. The first role is identified by the lowest [_weight_](g), using lexicographical order as the final fallback if weights are tied or undefined. ++ ++ See also: [_role_](g). ++ ++ [`defaultContentRole`]: /configuration/all/#defaultcontentrole diff --cc docs/content/en/quick-reference/glossary/default-site.md index 664643cf9,000000000..3acad31d0 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/default-site.md +++ b/docs/content/en/quick-reference/glossary/default-site.md @@@ -1,7 -1,0 +1,5 @@@ +--- +title: default site +--- + - The _default site_ is the [_site_](g) identified by the primary value in each [_content dimension_](g). Specifically, it is the site that combines the first language, the first [_role_](g), and the first version defined in your site configuration. - - The "first" language and role are those with the lowest [weight](g). If weights are tied or undefined, Hugo defaults to lexicographical order. Similarly, the "first" version is the one with the lowest weight; if weights are tied or undefined, it is identified as the last version when sorted semantically. ++The _default site_ is the [_site_](g) with the [_default language_](g), [_default version_](g), and [_default role_](g). diff --cc docs/content/en/quick-reference/glossary/default-version.md index 000000000,000000000..dc2904725 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/default-version.md @@@ -1,0 -1,0 +1,9 @@@ ++--- ++title: default version ++--- ++ ++The _default version_ is the value defined by the [`defaultContentVersion`][] setting, falling back to the first version in the project, and finally to `v1.0.0`. The first version is identified by the lowest [_weight_](g), using a descending semantic sort as the final fallback if weights are tied or undefined. ++ ++ See also: [_version_](g). ++ ++ [`defaultContentVersion`]: /configuration/all/#defaultcontentversion diff --cc docs/content/en/quick-reference/glossary/dependency-graph.md index 000000000,000000000..946e5b197 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/dependency-graph.md @@@ -1,0 -1,0 +1,5 @@@ ++--- ++title: dependency graph ++--- ++ ++A _dependency graph_ visually represents the relationships between the [_modules_](g) used in a Hugo project. It shows how modules depend on each other, forming a network of dependencies. diff --cc docs/content/en/quick-reference/glossary/dimension.md index ba0bc5e8c,000000000..9db6d64b8 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/dimension.md +++ b/docs/content/en/quick-reference/glossary/dimension.md @@@ -1,5 -1,0 +1,5 @@@ +--- +title: dimension +--- + - A _dimension_ is a categorized axis of content variation that allows multiple variations of a logical page to exist simultaneously. The three dimensions are language, [_role_](g), and version. For example, a logical page may exist in 6 languages, 4 versions, and 2 _roles_. ++A _dimension_ is a categorized axis of content variation that allows multiple variations of a logical page to exist simultaneously. The three dimensions are [_language_](g), [_role_](g), and [_version_](g). For example, a logical page may exist in 6 languages, 4 versions, and 2 roles. diff --cc docs/content/en/quick-reference/glossary/environment.md index ebba0ccdf,000000000..0cfba95f7 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/environment.md +++ b/docs/content/en/quick-reference/glossary/environment.md @@@ -1,9 -1,0 +1,9 @@@ +--- +title: environment +--- + +Typically one of `development`, `staging`, or `production`, each _environment_ may exhibit different behavior depending on configuration and template logic. For example, in a production environment you might minify and fingerprint CSS, but that probably doesn't make sense in a development environment. + - When running the built-in development server with the `hugo server` command, the environment is set to `development`. When building your site with the `hugo` command, the environment is set to `production`. To override the environment value, use the `--environment` command line flag or the `HUGO_ENVIRONMENT` environment variable. ++ When running the built-in development server with the `hugo server` command, the environment is set to `development`. When building your project with the `hugo build` command, the environment is set to `production`. To override the environment value, use the `--environment` command line flag or the `HUGO_ENVIRONMENT` environment variable. + + To determine the current environment within a template, use the [`hugo.Environment`](/functions/hugo/environment/) function. diff --cc docs/content/en/quick-reference/glossary/glob-slice.md index faaa64581,000000000..df37718b1 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/glob-slice.md +++ b/docs/content/en/quick-reference/glossary/glob-slice.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: glob slice +--- + +A _glob slice_ is a [_slice_](g) of [_glob patterns_](g). Within the _slice_, a _glob_ can be negated by prefixing it with an exclamation mark (`!`) and one space. Matches in negated patterns short-circuit the evaluation of the rest of the _slice_, and are useful for early coarse grained exclusions. + - The following example illustrates how to use _glob slices_ to define a [_sites matrix_](g) in your site configuration: ++ The following example illustrates how to use _glob slices_ to define a [_sites matrix_](g) in your project configuration: + + ```toml + [sites.matrix] + languages = [ "! no", "**" ] + versions = [ "! v1.2.3", "v1.*.*", "v2.*.*" ] + roles = [ "{member, guest}" ] + ``` + + The `versions` example above evaluates as: `(not v1.2.3) AND (v1.*.* OR v2.*.*)`. diff --cc docs/content/en/quick-reference/glossary/language.md index 000000000,000000000..551dc691c new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/language.md @@@ -1,0 -1,0 +1,7 @@@ ++--- ++title: language ++--- ++ ++A _language_ is a [_dimension_](g) that facilitates the localization and internationalization of content. While [_version_](g) focuses on lifecycle and [_role_](g) focuses on audience, the language dimension allows a logical page to be represented in different locales across the project. ++ ++ See also: [_default language_](g). diff --cc docs/content/en/quick-reference/glossary/page-relative.md index 11c485aa0,000000000..d12327bb9 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/page-relative.md +++ b/docs/content/en/quick-reference/glossary/page-relative.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: page-relative +--- + - A _page-relative_ path is resolved relative to the current page's location in the content hierarchy. These paths do not begin with a leading slash. Examples include `old-name`, `./old-name`, and `../old-name`. ++A _page-relative_ path is resolved relative to the current page's location in the content hierarchy. These paths do not begin with a leading slash. Examples include `old-name`, `./old-name`, and `../old-name`. + + See also: [_site-relative_](g), [_server-relative_](g). diff --cc docs/content/en/quick-reference/glossary/project.md index 000000000,000000000..86a3f63d3 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/project.md @@@ -1,0 -1,0 +1,5 @@@ ++--- ++title: project ++--- ++ ++A _project_ is a collection of [_components_](g) used to generate one or more [sites](g). While a project may consist of only a single site, Hugo allows a single project to generate a matrix of sites based on [_language_](g), [role](g), and [_version_](g). The project serves as the parent container for the common assets and logic used across all sites within the build. diff --cc docs/content/en/quick-reference/glossary/regular-expression.md index 222f289d9,000000000..82f8d98f5 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/regular-expression.md +++ b/docs/content/en/quick-reference/glossary/regular-expression.md @@@ -1,8 -1,0 +1,8 @@@ +--- +title: regular expression +reference: +--- + - A _regular expression_, also known as a _regex_, is a sequence of characters that defines a search pattern. Use the [RE2 syntax] when defining regular expressions in your templates or site configuration. ++A _regular expression_, also known as a _regex_, is a sequence of characters that defines a search pattern. Use the [RE2 syntax] when defining regular expressions in your templates or in your project configuration. + + [RE2 syntax]: https://github.com/google/re2/wiki/syntax diff --cc docs/content/en/quick-reference/glossary/role.md index be85f656d,000000000..f491d3610 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/role.md +++ b/docs/content/en/quick-reference/glossary/role.md @@@ -1,5 -1,0 +1,7 @@@ +--- +title: role +--- + - A _role_ is a [_dimension_](g) that allows a logical page to be served in different forms depending on the target audience. Common use cases include user personas, access control, and intended audience. ++A _role_ is a [_dimension_](g) that allows a logical page to be served in different forms depending on the target audience. While [_language_](g) focuses on localization and [_version_](g) focuses on lifecycle, the role dimension allows a project to generate variations of a page without duplicating content. ++ ++ See also: [_default role_](g). diff --cc docs/content/en/quick-reference/glossary/server-relative.md index 4420ba504,000000000..8783a25af mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/server-relative.md +++ b/docs/content/en/quick-reference/glossary/server-relative.md @@@ -1,9 -1,0 +1,9 @@@ +--- +title: server-relative +--- + - A _server-relative_ path is the final path from the web server's root, used in the generated site. These paths always begin with a leading slash and account for the [`baseURL`] and [_content dimension_](g) prefixes such as language, [_role_](g), or version. For example, `/en/examples/old-name/` is a server-relative path. ++A _server-relative_ path is the final path from the web server's root, used in the generated site. These paths always begin with a leading slash and account for the [`baseURL`] and [_content dimension_](g) prefixes such as language, [_role_](g), or version. For example, `/en/examples/old-name/` is a server-relative path. + + See also: [_page-relative_](g), [_site-relative_](g). + + [`baseURL`]: /configuration/all/#baseurl diff --cc docs/content/en/quick-reference/glossary/site-relative.md index c6536a165,000000000..b434fd1c2 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/site-relative.md +++ b/docs/content/en/quick-reference/glossary/site-relative.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: site-relative +--- + - A _site-relative_ path is resolved relative to the root of the content directory. These paths begin with a leading slash. For example, `/old-name` is a site-relative path. ++A _site-relative_ path is resolved relative to the root of the content directory. These paths begin with a leading slash. For example, `/old-name` is a site-relative path. + + See also: [_page-relative_](g), [_server-relative_](g). diff --cc docs/content/en/quick-reference/glossary/site-root.md index 71c4477a8,000000000..1066acb4d mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/site-root.md +++ b/docs/content/en/quick-reference/glossary/site-root.md @@@ -1,13 -1,0 +1,13 @@@ +--- +title: site root +--- + - The _site root_ is the root directory of the current [_site_](g), relative to the [`publishDir`][]. The _site root_ may include one or more content [_dimension_](g) prefixes, such as language, [_role_](g), or version. ++The _site root_ is the root directory of the current [_site_](g), relative to the [`publishDir`][]. The _site root_ may include one or more content [_dimension_](g) prefixes, such as [_language_](g), [_role_](g), or [_version_](g). + + Project description|Site root examples + :--|:--|:-- + Monolingual|`/`, `/guest`, `/guest/v1.2.3` + Multilingual single-host|`/en`, `/guest/en`, `/guest/v1.2.3/en` + Multilingual multihost|`/en`, `/en/guest`, `/en/guest/v1.2.3` + + [`publishDir`]: /configuration/all/#publishdir diff --cc docs/content/en/quick-reference/glossary/site.md index 1d2d016dc,000000000..f3be3a1f3 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/site.md +++ b/docs/content/en/quick-reference/glossary/site.md @@@ -1,5 -1,0 +1,5 @@@ +--- +title: site +--- + - A _site_ is a specific instance of your project representing a unique combination of language, [_role_](g), and version. While a simple project may consist of only a single site, Hugo's multidimensional content model allows a single codebase to generate a matrix of sites simultaneously. Each site operates with its own configuration, set of pages, and output destination, allowing you to serve tailored content to different audiences from one unified source. ++A _site_ is a specific instance of your [_project_](g) representing a unique combination of [_language_](g), [_role_](g), and [_version_](g). While a simple project may consist of only a single site, Hugo's multidimensional content model allows a single codebase to generate a matrix of sites simultaneously. diff --cc docs/content/en/quick-reference/glossary/sites-complements.md index 5854f288c,000000000..80213e1f9 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/sites-complements.md +++ b/docs/content/en/quick-reference/glossary/sites-complements.md @@@ -1,5 -1,0 +1,5 @@@ +--- +title: sites complements +--- + - _sites complements_ is a configuration object defined in content front matter or a file mount. The links will point to the complementary sites. The configuration is structured as a map of [_glob slices_](g). ++A _sites complements_ is a configuration object defined in content front matter or a file mount. The links will point to the complementary [_sites_](g). The configuration is structured as a map of [_glob slices_](g). diff --cc docs/content/en/quick-reference/glossary/sites-matrix.md index 5900334e1,000000000..8e6838d4e mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/sites-matrix.md +++ b/docs/content/en/quick-reference/glossary/sites-matrix.md @@@ -1,9 -1,0 +1,7 @@@ +--- +title: sites matrix +--- + - _sites matrix_ is a configuration object defined in content front matter or a file mount to precisely control which sites the content should be generated for. When defined in a file mount for [_templates_](g), it controls which sites the template will be applied to. - - In Hugo's multidimensional content model, the matrix defines the intersection of three dimensions: language, role, and version. The configuration is structured as a map of [_glob slices_](g). ++A _sites matrix_ is a configuration object defined in content front matter or a file mount to precisely control which [_sites_](g) the content should be generated for. When defined in a file mount for templates, it controls which sites the template will be applied to. In Hugo multidimensional content model, the matrix defines the intersection of three dimensions: [_language_](g), [_role_](g), and [_version_](g). The configuration is structured as a map of [_glob slices_](g). + + See also [_sites complements_](g), [front matter: sites](/content-management/front-matter/#sites), [module mounts: sites](/configuration/module/#sites), and [segments: sites](/configuration/segments/#sites). diff --cc docs/content/en/quick-reference/glossary/version.md index 000000000,000000000..62eb8f35a new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/version.md @@@ -1,0 -1,0 +1,9 @@@ ++--- ++title: version ++--- ++ ++A _version_ is a [_dimension_](g) that represents a specific iteration, release, or lifecycle stage of content. While [_language_](g) focuses on localization and [_role_](g) focuses on audience, the version dimension allows you to maintain multiple states of the same content simultaneously using [semantic versioning]. ++ ++ See also: [_default version_](g). ++ ++ [semantic versioning]: https://semver.org/ diff --cc docs/content/en/quick-reference/glossary/workspace.md index 000000000,000000000..6eda9bab3 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/workspace.md @@@ -1,0 -1,0 +1,7 @@@ ++--- ++title: workspace ++params: ++ reference: /hugo-modules/use-modules/#workspace ++--- ++ ++A _workspace_ is a collection of [_modules_](g) on disk. diff --cc docs/content/en/quick-reference/glossary/wrapper-component.md index 938a0271d,000000000..ada5d466e mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/wrapper-component.md +++ b/docs/content/en/quick-reference/glossary/wrapper-component.md @@@ -1,7 -1,0 +1,7 @@@ +--- +title: wrapper component +--- + +A _wrapper component_ is an interface pattern that encloses other content through composition rather than fixed parameters. It provides a reusable shell to handle layout, styling, or logic, allowing the calling template to inject arbitrary content into the component's interior. + - See also: [_partial decorator_](g) ++ See also: [_partial decorator_](g). diff --cc docs/content/en/quick-reference/syntax-highlighting-styles.md index 76aa77bf4,000000000..3ba6fd833 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/syntax-highlighting-styles.md +++ b/docs/content/en/quick-reference/syntax-highlighting-styles.md @@@ -1,35 -1,0 +1,35 @@@ +--- +title: Syntax highlighting styles +description: Highlight code examples using one of these styles. +categories: [] +keywords: [highlight] +--- + +## Overview + +Hugo provides several methods to add syntax highlighting to code examples: + +- Use the [`transform.Highlight`] function within your templates +- Use the [`highlight`] shortcode with any [content format](g) +- Use [fenced code blocks] with the Markdown content format + +Regardless of method, use any of the syntax highlighting styles below. + - Set the default syntax highlighting style in your site configuration: ++Set the default syntax highlighting style in your project configuration: + +{{< code-toggle file=hugo >}} +[markup.highlight] +style = 'monokai' +{{< /code-toggle >}} + +See [configure Markup](/configuration/markup/#highlight). + +[`transform.Highlight`]: /functions/transform/highlight/ +[`highlight`]: /shortcodes/highlight/ +[fenced code blocks]: /content-management/syntax-highlighting/#fenced-code-blocks + +## Styles + +This gallery demonstrates the application of each syntax highlighting style with code examples written in different programming languages. + +{{% syntax-highlighting-styles %}} diff --cc docs/content/en/render-hooks/code-blocks.md index 136c3b6d7,000000000..5b226467b mode 100755,000000..100755 --- a/docs/content/en/render-hooks/code-blocks.md +++ b/docs/content/en/render-hooks/code-blocks.md @@@ -1,125 -1,0 +1,125 @@@ +--- +title: Code block render hooks +linkTitle: Code blocks +description: Create code block render hook templates to override the rendering of Markdown code blocks to HTML. +categories: [] +keywords: [] +--- + +## Markdown + +This Markdown example contains a fenced code block: + +````text {file="content/example.md"} - ```bash {class="my-class" id="my-codeblock" lineNos=inline tabWidth=2} ++```sh {class="my-class" id="my-codeblock" lineNos=inline tabWidth=2} +declare a=1 +echo "$a" +exit +``` +```` + +A fenced code block consists of: + +- A leading [code fence] +- An optional [info string] +- A code sample +- A trailing code fence + +In the previous example, the info string contains: + +- The language of the code sample (the first word) +- An optional space-delimited or comma-delimited list of attributes (everything within braces) + +The attributes in the info string can be generic attributes or highlighting options. + +In the example above, the _generic attributes_ are `class` and `id`. In the absence of special handling within a code block render hook, Hugo adds each generic attribute to the HTML element surrounding the rendered code block. Consistent with its content security model, Hugo removes HTML event attributes such as `onclick` and `onmouseover`. Generic attributes are typically global HTML attributes, but you may include custom attributes as well. + +In the example above, the _highlighting options_ are `lineNos` and `tabWidth`. Hugo uses the [Chroma] syntax highlighter to render the code sample. You can control the appearance of the rendered code by specifying one or more [highlighting options]. + +> [!note] +> Although `style` is a global HTML attribute, when used in an info string it is a highlighting option. + +## Context + +Code block _render hook_ templates receive the following [context](g): + +Attributes +: (`map`) The generic attributes from the info string. + +Inner +: (`string`) The content between the leading and trailing code fences, excluding the info string. + +Options +: (`map`) The highlighting options from the info string. This map is empty if [`Type`](#type) is an empty string or a code language that is not supported by the Chroma syntax highlighter. However, in this case, the highlighting options are available in the [`Attributes`](#attributes) map. + +Ordinal +: (`int`) The zero-based ordinal of the code block on the page. + +Page +: (`page`) A reference to the current page. + +PageInner +: (`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details). + +Position +: (`text.Position`) The position of the code block within the page content. + +Type +: (`string`) The first word of the info string, typically the code language. + +## Examples + +In its default configuration, Hugo renders fenced code blocks by passing the code sample through the Chroma syntax highlighter and wrapping the result. To create a render hook that does the same thing: + +```go-html-template {file="layouts/_markup/render-codeblock.html" copy=true} +{{ $result := transform.HighlightCodeBlock . }} +{{ $result.Wrapped }} +``` + +Although you can use one template with conditional logic to control the behavior on a per-language basis, you can also create language-specific templates. + +```text +layouts/ + └── _markup/ + ├── render-codeblock-mermaid.html + ├── render-codeblock-python.html + └── render-codeblock.html +``` + +For example, to create a code block render hook to render [Mermaid] diagrams: + +```go-html-template {file="layouts/_markup/render-codeblock-mermaid.html" copy=true} +
     +  {{ .Inner | htmlEscape | safeHTML }}
     +
    +{{ .Page.Store.Set "hasMermaid" true }} +``` + +Then include this snippet at the _bottom_ of your base template, before the closing `body` tag: + +```go-html-template {file="layouts/baseof.html" copy=true} +{{ if .Store.Get "hasMermaid" }} + +{{ end }} +``` + +See the [diagrams] page for details. + +## Embedded + +Hugo includes an [embedded code block render hook] to render [GoAT diagrams]. + +{{% include "/_common/render-hooks/pageinner.md" %}} + +[`RenderShortcodes`]: /methods/page/rendershortcodes +[Chroma]: https://github.com/alecthomas/chroma/ +[code fence]: https://spec.commonmark.org/current/#code-fence +[diagrams]: /content-management/diagrams/#mermaid-diagrams +[embedded code block render hook]: <{{% eturl render-codeblock-goat %}}> +[GoAT diagrams]: /content-management/diagrams/#goat-diagrams-ascii +[highlighting options]: /functions/transform/highlight/#options +[info string]: https://spec.commonmark.org/current/#info-string +[Mermaid]: https://mermaid.js.org/ diff --cc docs/content/en/render-hooks/images.md index e5f631cdc,000000000..c89ce1746 mode 100755,000000..100755 --- a/docs/content/en/render-hooks/images.md +++ b/docs/content/en/render-hooks/images.md @@@ -1,134 -1,0 +1,134 @@@ +--- +title: Image render hooks +linkTitle: Images +description: Create image render hook templates to override the rendering of Markdown images to HTML. +categories: [] +keywords: [] +--- + +## Markdown + +A Markdown image has three components: the image description, the image destination, and optionally the image title. + +```text +![white kitten](/images/kitten.jpg "A kitten!") + ------------ ------------------ --------- + description destination title +``` + +These components are passed into the render hook [context](g) as shown below. + +## Context + +Image _render hook_ templates receive the following context: + +Attributes +: (`map`) The [Markdown attributes], available if you configure your site as follows: + + {{< code-toggle file=hugo >}} + [markup.goldmark.parser] + wrapStandAloneImageWithinParagraph = false + [markup.goldmark.parser.attribute] + block = true + {{< /code-toggle >}} + +Destination +: (`string`) The image destination. + +IsBlock +: (`bool`) Reports whether a standalone image is not wrapped within a paragraph element. + +Ordinal +: (`int`) The zero-based ordinal of the image on the page. + +Page +: (`page`) A reference to the current page. + +PageInner +: (`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details). + +PlainText +: (`string`) The image description as plain text. + +Text +: (`template.HTML`) The image description. + +Title +: (`string`) The image title. + +## Examples + +> [!note] +> With inline elements such as images and links, remove leading and trailing whitespace using the `{{‑ ‑}}` delimiter notation to prevent whitespace between adjacent inline elements and text. + +In its default configuration, Hugo renders Markdown images according to the [CommonMark specification]. To create a render hook that does the same thing: + +```go-html-template {file="layouts/_markup/render-image.html" copy=true} +{{ . }} +{{- /* chomp trailing newline */ -}} +``` + +To render standalone images within `figure` elements: + +```go-html-template {file="layouts/_markup/render-image.html" copy=true} +{{- if .IsBlock -}} +
    + {{ . }} + {{- with .Title }}
    {{ . }}
    {{ end -}} +
    +{{- else -}} + {{ . }} +{{- end -}} +``` + - Note that the above requires the following site configuration: ++Note that the above requires the following project configuration: + +{{< code-toggle file=hugo >}} +[markup.goldmark.parser] +wrapStandAloneImageWithinParagraph = false +{{< /code-toggle >}} + +## Embedded + - Hugo includes an [embedded image render hook] to resolve Markdown image destinations. You can adjust its behavior in your site configuration. This is the default setting: ++Hugo includes an [embedded image render hook] to resolve Markdown image destinations. You can adjust its behavior in your project configuration. This is the default setting: + +{{< code-toggle file=hugo >}} +[markup.goldmark.renderHooks.image] +useEmbedded = 'auto' +{{< /code-toggle >}} + +When set to `auto` as shown above, Hugo automatically uses the embedded image render hook for multilingual single-host sites, specifically when the [duplication of shared page resources] feature is disabled. This is the default behavior for such sites. If custom image render hooks are defined by your project, modules, or themes, these will be used instead. + +You can also configure Hugo to `always` use the embedded image render hook, use it only as a `fallback`, or `never` use it. See [details](/configuration/markup/#renderhooksimageuseembedded). + +The embedded image render hook resolves internal Markdown destinations by looking for a matching [page resource](g), falling back to a matching [global resource](g). Remote destinations are passed through, and the render hook will not throw an error or warning if unable to resolve a destination. + - You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your site configuration: ++You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your project configuration: + +{{< code-toggle file=hugo >}} +[[module.mounts]] +source = 'assets' +target = 'assets' + +[[module.mounts]] +source = 'static' +target = 'assets' +{{< /code-toggle >}} + +Note that the embedded image render hook does not perform image processing. Its sole purpose is to resolve Markdown image destinations. + +{{% include "/_common/render-hooks/pageinner.md" %}} + +[`RenderShortcodes`]: /methods/page/rendershortcodes +[CommonMark specification]: https://spec.commonmark.org/current/ +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[embedded image render hook]: <{{% eturl render-image %}}> +[Markdown attributes]: /content-management/markdown-attributes/ diff --cc docs/content/en/render-hooks/links.md index d35869160,000000000..ee765c14b mode 100755,000000..100755 --- a/docs/content/en/render-hooks/links.md +++ b/docs/content/en/render-hooks/links.md @@@ -1,104 -1,0 +1,104 @@@ +--- +title: Link render hooks +linkTitle: Links +description: Create a link render hook to override the rendering of Markdown links to HTML. +categories: [] +keywords: [] +--- + +## Markdown + +A Markdown link has three components: the link text, the link destination, and optionally the link title. + +```text +[Post 1](/posts/post-1 "My first post") + ------ ------------- ------------- + text destination title +``` + +These components are passed into the render hook [context](g) as shown below. + +## Context + +Link _render hook_ templates receive the following context: + +Destination +: (`string`) The link destination. + +Page +: (`page`) A reference to the current page. + +PageInner +: (`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details). + +PlainText +: (`string`) The link description as plain text. + +Text +: (`template.HTML`) The link description. + +Title +: (`string`) The link title. + +## Examples + +> [!note] +> With inline elements such as images and links, remove leading and trailing whitespace using the `{{‑ ‑}}` delimiter notation to prevent whitespace between adjacent inline elements and text. + +In its default configuration, Hugo renders Markdown links according to the [CommonMark specification]. To create a render hook that does the same thing: + +```go-html-template {file="layouts/_markup/render-link.html" copy=true} + + {{- with .Text }}{{ . }}{{ end -}} + +{{- /* chomp trailing newline */ -}} +``` + +To include a `rel` attribute set to `external` for external links: + +```go-html-template {file="layouts/_markup/render-link.html" copy=true} +{{- $u := urls.Parse .Destination -}} + + {{- with .Text }}{{ . }}{{ end -}} + +{{- /* chomp trailing newline */ -}} +``` + +## Embedded + - Hugo includes an [embedded link render hook] to resolve Markdown link destinations. You can adjust its behavior in your site configuration. This is the default setting: ++Hugo includes an [embedded link render hook] to resolve Markdown link destinations. You can adjust its behavior in your project configuration. This is the default setting: + +{{< code-toggle file=hugo >}} +[markup.goldmark.renderHooks.link] +useEmbedded = 'auto' +{{< /code-toggle >}} + +When set to `auto` as shown above, Hugo automatically uses the embedded link render hook for multilingual single-host sites, specifically when the [duplication of shared page resources] feature is disabled. This is the default behavior for such sites. If custom link render hooks are defined by your project, modules, or themes, these will be used instead. + +You can also configure Hugo to `always` use the embedded link render hook, use it only as a `fallback`, or `never` use it. See [details](/configuration/markup/#renderhookslinkuseembedded). + +The embedded link render hook resolves internal Markdown destinations by looking for a matching page, falling back to a matching [page resource](g), then falling back to a matching [global resource](g). Remote destinations are passed through, and the render hook will not throw an error or warning if unable to resolve a destination. + - You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your site configuration: ++You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your project configuration: + +{{< code-toggle file=hugo >}} +[[module.mounts]] +source = 'assets' +target = 'assets' + +[[module.mounts]] +source = 'static' +target = 'assets' +{{< /code-toggle >}} + +{{% include "/_common/render-hooks/pageinner.md" %}} + +[`RenderShortcodes`]: /methods/page/rendershortcodes +[CommonMark specification]: https://spec.commonmark.org/current/ +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[embedded link render hook]: <{{% eturl render-link %}}> diff --cc docs/content/en/render-hooks/passthrough.md index 76643718f,000000000..7aada5713 mode 100755,000000..100755 --- a/docs/content/en/render-hooks/passthrough.md +++ b/docs/content/en/render-hooks/passthrough.md @@@ -1,128 -1,0 +1,128 @@@ +--- +title: Passthrough render hooks +linkTitle: Passthrough +description: Create passthrough render hook templates to override the rendering of text snippets captured by the Goldmark Passthrough extension. +categories: [] +keywords: [] +--- + +{{< new-in 0.132.0 />}} + +## Overview + +Hugo uses [Goldmark] to render Markdown to HTML. Goldmark supports custom extensions to extend its core functionality. The [Passthrough] extension captures and preserves raw Markdown within delimited snippets of text, including the delimiters themselves. These are known as _passthrough elements_. + +[Goldmark]: https://github.com/yuin/goldmark +[Passthrough]: /configuration/markup/#passthrough + +Depending on your choice of delimiters, Hugo will classify a passthrough element as either _block_ or _inline_. Consider this contrived example: + +```text {file="content/example.md"} +This is a + +\[block\] + +passthrough element with opening and closing block delimiters. + +This is an \(inline\) passthrough element with opening and closing inline delimiters. +``` + - Update your site configuration to enable the Passthrough extension and define opening and closing delimiters for each passthrough element type, either `block` or `inline`. For example: ++Update your project configuration to enable the Passthrough extension and define opening and closing delimiters for each passthrough element type, either `block` or `inline`. For example: + +{{< code-toggle file=hugo >}} +[markup.goldmark.extensions.passthrough] +enable = true +[markup.goldmark.extensions.passthrough.delimiters] +block = [['\[', '\]'], ['$$', '$$']] +inline = [['\(', '\)']] +{{< /code-toggle >}} + +In the example above there are two sets of `block` delimiters. You may use either one in your Markdown. + +The Passthrough extension is often used in conjunction with the MathJax or KaTeX display engine to render [mathematical expressions] written in the LaTeX markup language. + +[mathematical expressions]: /content-management/mathematics/ + +To enable custom rendering of passthrough elements, create a passthrough render hook. + +## Context + +Passthrough _render hook_ templates receive the following [context](g): + +Attributes +: (`map`) The [Markdown attributes], available if you configure your site as follows: + + {{< code-toggle file=hugo >}} + [markup.goldmark.parser.attribute] + block = true + {{< /code-toggle >}} + + Hugo populates the `Attributes` map for _block_ passthrough elements. Markdown attributes are not applicable to _inline_ elements. + +Inner +: (`string`) The inner content of the passthrough element, excluding the delimiters. + +Ordinal +: (`int`) The zero-based ordinal of the passthrough element on the page. + +Page +: (`page`) A reference to the current page. + +PageInner +: (`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details). + +Position +: (`string`) The position of the passthrough element within the page content. + +Type +: (`string`) The passthrough element type, either `block` or `inline`. + +[Markdown attributes]: /content-management/markdown-attributes/ +[`RenderShortcodes`]: /methods/page/rendershortcodes + +## Example + +Instead of client-side JavaScript rendering of mathematical markup using MathJax or KaTeX, create a passthrough render hook which calls the [`transform.ToMath`] function. + +[`transform.ToMath`]: /functions/transform/tomath/ + +```go-html-template {file="layouts/_markup/render-passthrough.html" copy=true} +{{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }} +{{- with try (transform.ToMath .Inner $opts) }} + {{- with .Err }} + {{- errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }} + {{- else }} + {{- .Value }} + {{- $.Page.Store.Set "hasMath" true }} + {{- end }} +{{- end -}} +``` + +Then, in your base template, conditionally include the KaTeX CSS within the head element: + +```go-html-template {file="layouts/baseof.html" copy=true} + + {{ $noop := .WordCount }} + {{ if .Page.Store.Get "hasMath" }} + + {{ end }} + +``` + +In the above, note the use of a [noop](g) statement to force content rendering before we check the value of `hasMath` with the `Store.Get` method. + +Although you can use one template with conditional logic as shown above, you can also create separate templates for each [`Type`](#type) of passthrough element: + +```text +layouts/ + └── _markup/ + ├── render-passthrough-block.html + └── render-passthrough-inline.html +``` + +{{% include "/_common/render-hooks/pageinner.md" %}} diff --cc docs/content/en/shortcodes/figure.md index 24d85064b,000000000..42438f7ad mode 100755,000000..100755 --- a/docs/content/en/shortcodes/figure.md +++ b/docs/content/en/shortcodes/figure.md @@@ -1,109 -1,0 +1,109 @@@ +--- +title: Figure shortcode +linkTitle: Figure +description: Insert an HTML figure element into your content using the figure shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `figure` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +With this markup: + +```text +{{}} +``` + +Hugo renders this HTML: + +```html +
    + + A photograph of Zion National Park + +
    +

    Zion National Park

    +
    +
    +``` + +Which looks like this in your browser: + +{{< figure + src="/images/examples/zion-national-park.jpg" + alt="A photograph of Zion National Park" + link="https://www.nps.gov/zion/index.htm" + caption="Zion National Park" + class="ma0 w-75" +>}} + +## Arguments + +src +: (`string`) The `src` attribute of the `img` element. Typically this is a [page resource](g) or a [global resource](g). + +alt +: (`string`) The `alt` attribute of the `img` element. + +width +: (`int`) The `width` attribute of the `img` element. + +height +: (`int`) The `height` attribute of the `img` element. + +loading +: (`string`) The `loading` attribute of the `img` element. + +class +: (`string`) The `class` attribute of the `figure` element. + +link +: (`string`) The `href` attribute of the anchor element that wraps the `img` element. + +target +: (`string`) The `target` attribute of the anchor element that wraps the `img` element. + +rel +: (`rel`) The `rel` attribute of the anchor element that wraps the `img` element. + +title +: (`string`) Within the `figurecaption` element, the title is at the top, wrapped within an `h4` element. + +caption +: (`string`) Within the `figurecaption` element, the caption is at the bottom and may contain plain text or markdown. + +attr +: (`string`) Within the `figurecaption` element, the attribution appears next to the caption and may contain plain text or markdown. + +attrlink +: (`string`) The `href` attribute of the anchor element that wraps the attribution. + +## Image location + +The `figure` shortcode resolves internal Markdown destinations by looking for a matching [page resource](g), falling back to a matching [global resource](g). Remote destinations are passed through, and the render hook will not throw an error or warning if unable to resolve a destination. + - You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your site configuration: ++You must place global resources in the `assets` directory. If you have placed your resources in the `static` directory, and you are unable or unwilling to move them, you must mount the `static` directory to the `assets` directory by including both of these entries in your project configuration: + +{{< code-toggle file=hugo >}} +[[module.mounts]] +source = 'assets' +target = 'assets' + +[[module.mounts]] +source = 'static' +target = 'assets' +{{< /code-toggle >}} + +[source code]: <{{% eturl figure %}}> diff --cc docs/content/en/shortcodes/highlight.md index c349e97be,000000000..d427da7cc mode 100755,000000..100755 --- a/docs/content/en/shortcodes/highlight.md +++ b/docs/content/en/shortcodes/highlight.md @@@ -1,107 -1,0 +1,107 @@@ +--- +title: Highlight shortcode +linkTitle: Highlight +description: Insert syntax-highlighted code into your content using the highlight shortcode. +categories: [] +keywords: [highlight] +--- + +> [!note] +> To override Hugo's embedded `highlight` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +> [!note] +> With the Markdown [content format], the `highlight` shortcode is rarely needed because, by default, Hugo automatically applies syntax highlighting to fenced code blocks. +> +> The primary use case for the `highlight` shortcode in Markdown is to apply syntax highlighting to inline code snippets. + +The `highlight` shortcode calls the [`transform.Highlight`] function which uses the [Chroma] syntax highlighter, supporting over 200 languages with more than 40 [highlighting styles]. + +## Arguments + +The `highlight` shortcode takes three arguments. + +```text +{{}} +CODE +{{}} +``` + +CODE +: (`string`) The code to highlight. + +LANG +: (`string`) The language of the code to highlight. Choose from one of the [supported languages]. This value is case-insensitive. + +OPTIONS - : (`string`) Zero or more space-separated key-value pairs wrapped in quotation marks. Set default values for each option in your [site configuration]. The key names are case-insensitive. ++: (`string`) Zero or more space-separated key-value pairs wrapped in quotation marks. Set default values for each option in your [project configuration]. The key names are case-insensitive. + +## Example + +```text +{{}} +package main + +import "fmt" + +func main() { + for i := 0; i < 3; i++ { + fmt.Println("Value of i:", i) + } +} +{{}} +``` + +Hugo renders this to: + +{{< highlight go "linenos=inline, hl_Lines=3 6-8, noClasses=true" >}} +package main + +import "fmt" + +func main() { + for i := 0; i < 3; i++ { + fmt.Println("Value of i:", i) + } +} +{{< /highlight >}} + +You can also use the `highlight` shortcode for inline code snippets: + +```text +This is some {{}}fmt.Println("inline"){{}} code. +``` + +Hugo renders this to: + +This is some {{< highlight go "hl_inline=true, noClasses=true" >}}fmt.Println("inline"){{< /highlight >}} code. + +Given the verbosity of the example above, if you need to frequently highlight inline code snippets, create your own shortcode using a shorter name with preset options. + +```go-html-template {file="layouts/_shortcodes/hl.html"} +{{ $code := .Inner | strings.TrimSpace }} +{{ $lang := or (.Get 0) "go" }} +{{ $opts := dict "hl_inline" true "noClasses" true }} +{{ transform.Highlight $code $lang $opts }} +``` + +```text +This is some {{}}fmt.Println("inline"){{}} code. +``` + +Hugo renders this to: + +This is some {{< hl >}}fmt.Println("inline"){{< /hl >}} code. + +## Options + - Pass the options when calling the shortcode. You can set their default values in your [site configuration]. ++Pass the options when calling the shortcode. You can set their default values in your [project configuration]. + +{{% include "_common/syntax-highlighting-options.md" %}} + +[`transform.Highlight`]: /functions/transform/highlight/ +[Chroma]: https://github.com/alecthomas/chroma +[content format]: /content-management/formats/ +[highlighting styles]: /quick-reference/syntax-highlighting-styles/ - [site configuration]: /configuration/markup/#highlight ++[project configuration]: /configuration/markup/#highlight +[source code]: <{{% eturl highlight %}}> +[supported languages]: /content-management/syntax-highlighting/#languages diff --cc docs/content/en/shortcodes/instagram.md index 9f8b4fd26,000000000..f3223e742 mode 100755,000000..100755 --- a/docs/content/en/shortcodes/instagram.md +++ b/docs/content/en/shortcodes/instagram.md @@@ -1,42 -1,0 +1,42 @@@ +--- +title: Instagram shortcode +linkTitle: Instagram +description: Embed an Instagram post in your content using the instagram shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `instagram` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +To display an Instagram post with this URL: + +```text +https://www.instagram.com/p/CxOWiQNP2MO/ +``` + +Include this in your Markdown: + +```text +{{}} +``` + +Huge renders this to: + +{{< instagram CxOWiQNP2MO >}} + +## Privacy + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.instagram />}} + +disable +: (`bool`) Whether to disable the shortcode. Default is `false`. + +simple +: (`bool`) Whether to enable simple mode for image card generation. If `true`, Hugo creates a static card without JavaScript. This mode only supports image cards, and the image is fetched directly from Instagram's servers. Default is `false`. + +[source code]: <{{% eturl instagram %}}> diff --cc docs/content/en/shortcodes/param.md index 967d12846,000000000..51310a2a1 mode 100755,000000..100755 --- a/docs/content/en/shortcodes/param.md +++ b/docs/content/en/shortcodes/param.md @@@ -1,38 -1,0 +1,38 @@@ +--- +title: Param shortcode +linkTitle: Param - description: Insert a parameter from front matter or site configuration into your content using the param shortcode. ++description: Insert a parameter from front matter or your project configuration into your content using the param shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `param` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +The `param` shortcode renders a parameter from front matter, falling back to a site parameter of the same name. The shortcode throws an error if the parameter does not exist. + +```text {file="content/example.md"} +--- +title: Example +date: 2025-01-15T23:29:46-08:00 +params: + color: red + size: medium +--- + +We found a {{%/* param "color" */%}} shirt. +``` + +Hugo renders this to: + +```html +

    We found a red shirt.

    +``` + +Access nested values by [chaining](g) the [identifiers](g): + +```text +{{%/* param my.nested.param */%}} +``` + +[source code]: <{{% eturl param %}}> diff --cc docs/content/en/shortcodes/vimeo.md index b09420018,000000000..d7ca7ee6c mode 100755,000000..100755 --- a/docs/content/en/shortcodes/vimeo.md +++ b/docs/content/en/shortcodes/vimeo.md @@@ -1,73 -1,0 +1,73 @@@ +--- +title: Vimeo shortcode +linkTitle: Vimeo +description: Embed a Vimeo video in your content using the vimeo shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `vimeo` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +To display a Vimeo video with this URL: + +```text +https://vimeo.com/channels/staffpicks/55073825 +``` + +Include this in your Markdown: + +```text +{{}} +``` + +Hugo renders this to: + +{{< vimeo 55073825 >}} + +## Arguments + +id +: (string) The video `id`. Optional if the `id` is the first and only positional argument. + +allowFullScreen +: {{< new-in 0.146.0 />}} +: (`bool`) Whether the `iframe` element can activate full screen mode. Default is `true`. + +class +: (`string`) The `class` attribute of the wrapping `div` element. Adding one or more CSS classes disables inline styling. + +loading +: {{< new-in 0.146.0 />}} +: (`string`) The loading attribute of the `iframe` element, either `eager` or `lazy`. Default is `eager`. + +title +: (`string`) The `title` attribute of the `iframe` element. + +Here's an example using some of the available arguments: + +```text +{{}} +``` + +## Privacy + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.vimeo />}} + +disable +: (`bool`) Whether to disable the shortcode. Default is `false`. + +enableDNT +: (`bool`) Whether to block the Vimeo player from tracking session data and analytics. Default is `false`. + +simple +: (`bool`) Whether to enable simple mode. If `true`, the video thumbnail is fetched from Vimeo and overlaid with a play button. Clicking the thumbnail opens the video in a new Vimeo tab. Default is `false`. + +The source code for the simple version of the shortcode is available [in this file]. + +[in this file]: <{{% eturl vimeo_simple %}}> +[source code]: <{{% eturl vimeo %}}> diff --cc docs/content/en/shortcodes/x.md index 967a526a8,000000000..1ca87949a mode 100755,000000..100755 --- a/docs/content/en/shortcodes/x.md +++ b/docs/content/en/shortcodes/x.md @@@ -1,54 -1,0 +1,54 @@@ +--- +title: X shortcode +linkTitle: X +description: Embed an X post in your content using the x shortcode. +categories: [] +keywords: [] +--- + +{{< new-in 0.141.0 />}} + +> [!note] +> To override Hugo's embedded `x` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +To display an X post with this URL: + +```txt +https://x.com/SanDiegoZoo/status/1453110110599868418 +``` + +Include this in your Markdown: + +```text +{{}} +``` + +Rendered: + +{{< x user="SanDiegoZoo" id="1453110110599868418" >}} + +## Privacy + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.x />}} + +disable +: (`bool`) Whether to disable the shortcode. Default is `false`. + +enableDNT +: (`bool`) Whether to prevent X from using post and embedded page data for personalized suggestions and ads. Default is `false`. + +simple +: (`bool`) Whether to enable simple mode. If `true`, Hugo builds a static version of the of the post without JavaScript. Default is `false`. + +The source code for the simple version of the shortcode is available [in this file]. + - If you enable simple mode you may want to disable the hardcoded inline styles by setting `disableInlineCSS` to `true` in your site configuration. The default value for this setting is `false`. ++If you enable simple mode you may want to disable the hardcoded inline styles by setting `disableInlineCSS` to `true` in your project configuration. The default value for this setting is `false`. + +{{< code-toggle config=services.x />}} + +[in this file]: <{{% eturl x_simple %}}> +[source code]: <{{% eturl x %}}> diff --cc docs/content/en/shortcodes/youtube.md index 1e72ee284,000000000..c76c5f308 mode 100755,000000..100755 --- a/docs/content/en/shortcodes/youtube.md +++ b/docs/content/en/shortcodes/youtube.md @@@ -1,83 -1,0 +1,83 @@@ +--- +title: YouTube shortcode +linkTitle: YouTube +description: Embed a YouTube video in your content using the youtube shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `youtube` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +To display a YouTube video with this URL: + +```text +https://www.youtube.com/watch?v=0RKpf3rK57I +``` + +Include this in your Markdown: + +```texts +{{}} +``` + +Hugo renders this to: + +{{< youtube 0RKpf3rK57I >}} + +## Arguments + +id +: (`string`) The video `id`. Optional if the `id` is the first and only positional argument. + +allowFullScreen +: (`bool`) Whether the `iframe` element can activate full screen mode. Default is `true`. + +autoplay +: (`bool`) Whether to automatically play the video. Forces `mute` to `true`. Default is `false`. + +class +: (`string`) The `class` attribute of the wrapping `div` element. When specified, removes the `style` attributes from the `iframe` element and its wrapping `div` element. + +controls +: (`bool`) Whether to display the video controls. Default is `true`. + +end +: (`int`) The time, measured in seconds from the start of the video, when the player should stop playing the video. + +loading +: (`string`) The loading attribute of the `iframe` element, either `eager` or `lazy`. Default is `eager`. + +loop +: (`bool`) Whether to indefinitely repeat the video. Ignores the `start` and `end` arguments after the first play. Default is `false`. + +mute +: (`bool`) Whether to mute the video. Always `true` when `autoplay` is `true`. Default is `false`. + +start +: (`int`) The time, measured in seconds from the start of the video, when the player should start playing the video. + +title +: (`string`) The `title` attribute of the `iframe` element. Defaults to "YouTube video". + +Here's an example using some of the available arguments: + +```text +{{}} +``` + +## Privacy + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.youTube />}} + +disable +: (`bool`) Whether to disable the shortcode. Default is `false`. + +privacyEnhanced +: (`bool`) Whether to block YouTube from storing information about visitors on your website unless the user plays the embedded video. Default is `false`. + +[source code]: {{% eturl youtube %}} diff --cc docs/content/en/templates/embedded.md index 1ab5e04e7,000000000..d8de3061a mode 100644,000000..100644 --- a/docs/content/en/templates/embedded.md +++ b/docs/content/en/templates/embedded.md @@@ -1,224 -1,0 +1,219 @@@ +--- +title: Embedded partial templates +description: Hugo provides embedded partial templates for common use cases. +categories: [] +keywords: [] +weight: 180 +aliases: [/templates/internal] +--- + +{{< newtemplatesystem >}} + +## Disqus + +> [!note] +> To override Hugo's embedded Disqus template, copy the [source code](<{{% eturl disqus %}}>) to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "disqus.html" . }}` + +Hugo includes an embedded template for [Disqus], a popular commenting system for both static and dynamic websites. To effectively use Disqus, secure a Disqus "shortname" by [signing up] for the free service. + +To include the embedded template: + +```go-html-template +{{ partial "disqus.html" . }} +``` + +### Configuration {#configuration-disqus} + +To use Hugo's Disqus template, first set up a single configuration value: + +{{< code-toggle file=hugo >}} +[services.disqus] +shortname = 'your-disqus-shortname' +{{}} + +Hugo's Disqus template accesses this value with: + +```go-html-template +{{ .Site.Config.Services.Disqus.Shortname }} +``` + +You can also set the following in the front matter for a given piece of content: + +- `disqus_identifier` +- `disqus_title` +- `disqus_url` + +### Privacy {#privacy-disqus} + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.disqus />}} + +disable +: (`bool`) Whether to disable the template. Default is `false`. + +## Google Analytics + +> [!note] +> To override Hugo's embedded Google Analytics template, copy the [source code](<{{% eturl google_analytics %}}>) to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "google_analytics.html" . }}` + +Hugo includes an embedded template supporting [Google Analytics 4]. + +To include the embedded template: + +```go-html-template +{{ partial "google_analytics.html" . }} +``` + +### Configuration {#configuration-google-analytics} + +Provide your tracking ID in your configuration file: + +{{< code-toggle file=hugo >}} +[services.googleAnalytics] +id = "G-MEASUREMENT_ID" +{{}} + +To use this value in your own template, access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`. + +### Privacy {#privacy-google-analytics} + - Adjust the relevant privacy settings in your site configuration. ++Adjust the relevant privacy settings in your project configuration. + +{{< code-toggle config=privacy.googleAnalytics />}} + +disable +: (`bool`) Whether to disable the template. Default is `false`. + +respectDoNotTrack +: (`bool`) Whether to respect the browser's "do not track" setting. Default is `true`. + +## Open Graph + +> [!note] +> To override Hugo's embedded Open Graph template, copy the [source code](<{{% eturl opengraph %}}>) to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "opengraph.html" . }}` + +Hugo includes an embedded template for the [Open Graph protocol](https://ogp.me/), metadata that enables a page to become a rich object in a social graph. +This format is used for Facebook and some other sites. + +To include the embedded template: + +```go-html-template +{{ partial "opengraph.html" . }} +``` + +### Configuration {#configuration-open-graph} + +Hugo's Open Graph template is configured using a mix of configuration settings and [front matter](/content-management/front-matter/) on individual pages. + +{{< code-toggle file=hugo >}} +[params] + description = 'Text about my cool site' + images = ['site-feature-image.jpg'] + title = 'My cool site' + [params.social] + facebook_admin = 'jsmith' +[taxonomies] + series = 'series' +{{}} + +{{< code-toggle file=content/blog/my-post.md fm=true >}} +title = "Post title" +description = "Text about this post" +date = 2024-03-08T08:18:11-08:00 +images = ["post-cover.png"] +audio = [] +videos = [] +series = [] +tags = [] +{{}} + - Hugo uses the page title and description for the title and description metadata. - The first 6 URLs from the `images` array are used for image metadata. - If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata. ++Hugo uses the page title and description for the title and description metadata. The first 6 URLs from the `images` array are used for image metadata. If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata. + +Various optional metadata can also be set: + +- Date, published date, and last modified data are used to set the published time metadata if specified. +- `audio` and `videos` are URL arrays like `images` for the audio and video metadata tags, respectively. +- The first 6 `tags` on the page are used for the tags metadata. +- The `series` taxonomy is used to specify related "see also" pages by placing them in the same series. + +If using YouTube this will produce a og:video tag like ``. Use the `https://youtu.be/` format with YouTube videos (example: `https://youtu.be/qtIqKaDlqXo`). + +## Pagination + +See [details](/templates/pagination/). + +## Schema + +> [!note] +> To override Hugo's embedded Schema template, copy the [source code](<{{% eturl schema %}}>) to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "schema.html" . }}` + +Hugo includes an embedded template to render [microdata] `meta` elements within the `head` element of your templates. + +To include the embedded template: + +```go-html-template +{{ partial "schema.html" . }} +``` + +## X (Twitter) Cards + +> [!note] +> To override Hugo's embedded Twitter Cards template, copy the [source code](<{{% eturl twitter_cards %}}>) to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "twitter_cards.html" . }}` + - Hugo includes an embedded template for [X (Twitter) Cards](https://developer.x.com/en/docs/twitter-for-websites/cards/overview/abouts-cards), - metadata used to attach rich media to Tweets linking to your site. ++Hugo includes an embedded template for [X (Twitter) Cards](https://developer.x.com/en/docs/twitter-for-websites/cards/overview/abouts-cards), metadata used to attach rich media to Tweets linking to your site. + +To include the embedded template: + +```go-html-template +{{ partial "twitter_cards.html" . }} +``` + +### Configuration {#configuration-x-cards} + +Hugo's X (Twitter) Card template is configured using a mix of configuration settings and [front-matter](/content-management/front-matter/) values on individual pages. + +{{< code-toggle file=hugo >}} +[params] + images = ["site-feature-image.jpg"] + description = "Text about my cool site" +{{}} + +{{< code-toggle file=content/blog/my-post.md fm=true >}} +title = "Post title" +description = "Text about this post" +images = ["post-cover.png"] +{{}} + - If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata. - If no image resources with those names are found, the images defined in the [site config](/configuration/) are used instead. - If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`. ++If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata. If no image resources with those names are found, the images defined in your [project configuration](/configuration/) are used instead. If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`. + +Hugo uses the page title and description for the card's title and description fields. The page summary is used if no description is given. + - Set the value of `twitter:site` in your site configuration: ++Set the value of `twitter:site` in your project configuration: + +{{< code-toggle file=hugo >}} +[params.social] +twitter = "GoHugoIO" +{{}} + +NOTE: The `@` will be added for you + +```html + +``` + +[`partial`]: /functions/partials/include/ +[Disqus]: https://disqus.com +[Google Analytics 4]: https://support.google.com/analytics/answer/10089681 +[microdata]: https://html.spec.whatwg.org/multipage/microdata.html#microdata +[signing up]: https://disqus.com/profile/signup/ diff --cc docs/content/en/templates/introduction.md index 57a1ac1b7,000000000..fcc7d445e mode 100644,000000..100644 --- a/docs/content/en/templates/introduction.md +++ b/docs/content/en/templates/introduction.md @@@ -1,579 -1,0 +1,579 @@@ +--- +title: Introduction to templating +linkTitle: Introduction +description: An introduction to Hugo's templating syntax. +categories: [] +keywords: [] +weight: 10 +--- + +{{< newtemplatesystem >}} + +{{% glossary-term template %}} + +Templates use [variables], [functions], and [methods] to transform your content, resources, and data into a published page. + +> [!note] +> Hugo uses Go's [text/template] and [html/template] packages. +> +> The text/template package implements data-driven templates for generating textual output, while the html/template package implements data-driven templates for generating HTML output safe against code injection. +> +> By default, Hugo uses the html/template package when rendering HTML files. + +For example, this HTML template initializes the `$v1` and `$v2` variables, then displays them and their product within an HTML paragraph. + +```go-html-template +{{ $v1 := 6 }} +{{ $v2 := 7 }} +

    The product of {{ $v1 }} and {{ $v2 }} is {{ mul $v1 $v2 }}.

    +``` + +While HTML templates are the most common, you can create templates for any [output format](g) including CSV, JSON, RSS, and plain text. + +## Context + +The most important concept to understand before creating a template is _context_, the data passed into each template. The data may be a simple value, or more commonly [objects](g) and associated [methods](g). + +For example, a _page_ template receives a `Page` object, and the `Page` object provides methods to return values or perform actions. + +### Current context + +Within a template, the dot (`.`) represents the current context. + +```go-html-template {file="layouts/page.html"} +

    {{ .Title }}

    +``` + +In the example above the dot represents the `Page` object, and we call its [`Title`] method to return the title as defined in [front matter]. + +The current context may change within a template. For example, at the top of a template the context might be a `Page` object, but we rebind the context to another value or object within [`range`] or [`with`] blocks. + +```go-html-template {file="layouts/page.html"} +

    {{ .Title }}

    + +{{ range slice "foo" "bar" }} +

    {{ . }}

    +{{ end }} + +{{ with "baz" }} +

    {{ . }}

    +{{ end }} +``` + +In the example above, the context changes as we `range` through the [slice](g) of values. In the first iteration the context is "foo", and in the second iteration the context is "bar". Inside of the `with` block the context is "baz". Hugo renders the above to: + +```html +

    My Page Title

    +

    foo

    +

    bar

    +

    baz

    +``` + +### Template context + +Within a `range` or `with` block you can access the context passed into the template by prepending a dollar sign (`$`) to the dot: + +```go-html-template {file="layouts/page.html"} +{{ with "foo" }} +

    {{ $.Title }} - {{ . }}

    +{{ end }} +``` + +Hugo renders this to: + +```html +

    My Page Title - foo

    +``` + +> [!note] +> Make sure that you thoroughly understand the concept of _context_ before you continue reading. The most common templating errors made by new users relate to context. + +## Actions + +In the examples above, the paired opening and closing braces represent the beginning and end of a template action, a data evaluation or control structure within a template. + +A template action may contain literal values ([boolean](g), [string](g), [integer](g), and [float](g)), the [current context](#current-context), [variables](#variables), [functions](#functions), [methods](#methods), and the [`nil`](#nil) keyword. + +```go-html-template {file="layouts/page.html"} +{{ $convertToLower := true }} +{{ if $convertToLower }} +

    {{ strings.ToLower .Title }}

    +{{ end }} +``` + +In the example above: + +- `$convertToLower` is a variable +- `true` is a literal boolean value +- `if` is the beginning of a control structure +- `strings.ToLower` is a function that converts all characters to lowercase +- `Title` is a method on a the `Page` object +- `end` is the end of a control structure + +Hugo renders the above to: + +```html {trim=false} + + +

    my page title

    + +``` + +### Whitespace + +Notice the blank lines and indentation in the previous example? Although irrelevant in production when you typically minify the output, you can remove the adjacent whitespace by using template action delimiters with hyphens: + +```go-html-template {file="layouts/page.html"} +{{- $convertToLower := true -}} +{{- if $convertToLower -}} +

    {{ strings.ToLower .Title }}

    +{{- end -}} +``` + +Hugo renders this to: + +```html +

    my page title

    +``` + +Whitespace includes spaces, horizontal tabs, carriage returns, and newlines. + +### Quote characters + +Hugo templates use different quote characters to define how text and characters are processed. + +Use double quotes for [interpreted string literals](g). These interpret backslashes as special instructions: + +```go-html-template +{{ print "Hello world\u0021" }} → Hello world! +``` + +Use backticks for [raw string literals](g). These ignore backslashes and treat every character literally: + +```go-html-template +{{ print `Hello world\u0021` }} → Hello world\u0021 +``` + +Use single quotes for [rune literals](g). Unlike strings, these represent a single character as its numerical Unicode value: + +```go-html-template +{{ print '!' }} → 33 +``` + +In practical terms, you will rarely, if ever, use rune literals in your template code. They are most commonly used in low-level programming; in a Hugo template, you will almost always want a string instead. + +### Pipes + +Within a template action you may [pipe](g) a value to a function or method. The piped value becomes the final argument to the function or method. For example, these are equivalent: + +```go-html-template +{{ strings.ToLower "Hugo" }} → hugo +{{ "Hugo" | strings.ToLower }} → hugo +``` + +You can pipe the result of one function or method into another. For example, these are equivalent: + +```go-html-template +{{ strings.TrimSuffix "o" (strings.ToLower "Hugo") }} → hug +{{ "Hugo" | strings.ToLower | strings.TrimSuffix "o" }} → hug +``` + +These are also equivalent: + +```go-html-template +{{ mul 6 (add 2 5) }} → 42 +{{ 5 | add 2 | mul 6 }} → 42 +``` + +> [!note] +> Remember that the piped value becomes the final argument to the function or method to which you are piping. + +### Line splitting + +You can split a template action over two or more lines. For example, these are equivalent: + +```go-html-template +{{ $v := or $arg1 $arg2 }} + +{{ $v := or + $arg1 + $arg2 +}} +``` + +You can also split [raw string literals](g) over two or more lines. For example, these are equivalent: + +```go-html-template +{{ $msg := "This is line one.\nThis is line two." }} + +{{ $msg := `This is line one. +This is line two.` +}} +``` + +### Nil + +Other than using the `nil` keyword in comparisons, you may not use it as an argument to any function or method, nor may you assign it to a variable. For example, these are valid uses of the `nil` keyword: + +```go-html-template +{{ if gt 42 nil }} +

    42 is greater than nil

    +{{ end }} + +{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }} +``` + +These, on the other hand, are invalid: + +```go-html-template +{{ $a := nil }} +{{ add 3 nil }} +{{ nil | print}} +``` + +The actions above throw an error. + +## Variables + +A variable is a user-defined [identifier](g) prepended with a dollar sign (`$`), representing a value of any data type, initialized or assigned within a template action. For example, `$foo` and `$bar` are variables. + +Variables may contain [scalars](g), [slices](g), [maps](g), or [objects](g). + +Use `:=` to initialize a variable, and use `=` to assign a value to a variable that has been previously initialized. For example: + +```go-html-template +{{ $total := 3 }} +{{ range slice 7 11 21 }} + {{ $total = add $total . }} +{{ end }} +{{ $total }} → 42 +``` + +Variables initialized inside of an `if`, `range`, or `with` block are scoped to the block. Variables initialized outside of these blocks are scoped to the template. + +With variables that represent a slice or map, use the [`index`] function to return the desired value. + +```go-html-template +{{ $slice := slice "foo" "bar" "baz" }} +{{ index $slice 2 }} → baz + +{{ $map := dict "a" "foo" "b" "bar" "c" "baz" }} +{{ index $map "c" }} → baz +``` + +> [!note] +> Slices and arrays are zero-based; element 0 is the first element. + +With variables that represent a map or object, [chain](g) identifiers to return the desired value or to access the desired method. + +```go-html-template +{{ $map := dict "a" "foo" "b" "bar" "c" "baz" }} +{{ $map.c }} → baz + +{{ $homePage := .Site.Home }} +{{ $homePage.Title }} → My Homepage +``` + +> [!note] +> As seen above, object and method names are capitalized. Although not required, to avoid confusion we recommend beginning variable and map key names with a lowercase letter or underscore. + +## Functions + +Used within a template action, a function takes one or more arguments and returns a value. Unlike methods, functions are not associated with an object. + +Go's text/template and html/template packages provide a small set of functions, operators, and statements for general use. See the [go-templates] section of the function documentation for details. + +Hugo provides hundreds of custom [functions] categorized by namespace. For example, the `strings` namespace includes these and other functions: + +Function|Alias +:--|:-- +[`strings.ToLower`](/functions/strings/tolower)|`lower` +[`strings.ToUpper`](/functions/strings/toupper)|`upper` +[`strings.Replace`](/functions/strings/replace)|`replace` + +As shown above, frequently used functions have an alias. Use aliases in your templates to reduce code length. + +When calling a function, separate the arguments from the function, and from each other, with a space. For example: + +```go-html-template +{{ $total := add 1 2 3 4 }} +``` + +## Methods + +Used within a template action and associated with an object, a method takes zero or more arguments and either returns a value or performs an action. + +The most commonly accessed objects are the [`Page`] and [`Site`] objects. This is a small sampling of the [methods] available to each object. + +Object|Method|Description +:--|:--|:-- +`Page`|[`Date`](methods/page/date/)|Returns the date of the given page. +`Page`|[`Params`](methods/page/params/)|Returns a map of custom parameters as defined in the front matter of the given page. +`Page`|[`Title`](methods/page/title/)|Returns the title of the given page. +`Site`|[`Data`](methods/site/data/)|Returns a data structure composed from the files in the `data` directory. - `Site`|[`Params`](methods/site/params/)|Returns a map of custom parameters as defined in the site configuration. - `Site`|[`Title`](methods/site/title/)|Returns the title as defined in the site configuration. ++`Site`|[`Params`](methods/site/params/)|Returns a map of custom parameters as defined in your project configuration. ++`Site`|[`Title`](methods/site/title/)|Returns the title as defined in the your project configuration. + +Chain the method to its object with a dot (`.`) as shown below, remembering that the leading dot represents the [current context]. + +```go-html-template {file="layouts/page.html"} +{{ .Site.Title }} → My Site Title +{{ .Page.Title }} → My Page Title +``` + +The context passed into most templates is a `Page` object, so this is equivalent to the previous example: + +```go-html-template {file="layouts/page.html"} +{{ .Site.Title }} → My Site Title +{{ .Title }} → My Page Title +``` + +Some methods take an argument. Separate the argument from the method with a space. For example: + +```go-html-template {file="layouts/page.html"} +{{ $page := .Page.GetPage "/books/les-miserables" }} +{{ $page.Title }} → Les Misérables +``` + +## Comments + +> [!note] +> Do not attempt to use HTML comment delimiters to comment out template code. +> +> Hugo strips HTML comments when rendering a page, but first evaluates any template code within the HTML comment delimiters. Depending on the template code within the HTML comment delimiters, this could cause unexpected results or fail the build. + +Template comments are similar to template actions. Paired opening and closing braces represent the beginning and end of a comment. For example: + +```text +{{/* This is an inline comment. */}} +{{- /* This is an inline comment with adjacent whitespace removed. */ -}} +``` + +Code within a comment is not parsed, executed, or displayed. Comments may be inline, as shown above, or in block form: + +```text +{{/* +This is a block comment. +*/}} + +{{- /* +This is a block comment with +adjacent whitespace removed. +*/ -}} +``` + +You may not nest one comment inside of another. + +To render an HTML comment, pass a string through the [`safeHTML`] template function. For example: + +```go-html-template +{{ "" | safeHTML }} +{{ printf "" .Site.Title | safeHTML }} +``` + +## Include + +Use the [`template`] function to include one or more of Hugo's [embedded templates]: + +```go-html-template +{{ partial "google_analytics.html" . }} +{{ partial "opengraph" . }} +{{ partial "pagination.html" . }} +{{ partial "schema.html" . }} +{{ partial "twitter_cards.html" . }} +``` + +Use the [`partial`] or [`partialCached`] function to include one or more [partial templates]: + +```go-html-template +{{ partial "breadcrumbs.html" . }} +{{ partialCached "css.html" . }} +``` + +Create your _partial_ templates in the `layouts/_partials` directory. + +> [!note] +> In the examples above, note that we are passing the current context (the dot) to each of the templates. + +## Examples + +This limited set of contrived examples demonstrates some of concepts described above. Please see the [functions], [methods], and [templates] documentation for specific examples. + +### Conditional blocks + +See documentation for [`if`], [`else`], and [`end`]. + +```go-html-template +{{ $var := 42 }} +{{ if eq $var 6 }} + {{ print "var is 6" }} +{{ else if eq $var 7 }} + {{ print "var is 7" }} +{{ else if eq $var 42 }} + {{ print "var is 42" }} +{{ else }} + {{ print "var is something else" }} +{{ end }} +``` + +### Logical operators + +See documentation for [`and`] and [`or`]. + +```go-html-template +{{ $v1 := true }} +{{ $v2 := false }} +{{ $v3 := false }} +{{ $result := false }} + +{{ if and $v1 $v2 $v3 }} + {{ $result = true }} +{{ end }} +{{ $result }} → false + +{{ if or $v1 $v2 $v3 }} + {{ $result = true }} +{{ end }} +{{ $result }} → true +``` + +### Loops + +See documentation for [`range`], [`else`], and [`end`]. + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} +{{ range $s }} +

    {{ . }}

    +{{ else }} +

    The collection is empty

    +{{ end }} +``` + +To loop a specified number of times: + +```go-html-template +{{ $s := slice }} +{{ range 3 }} + {{ $s = $s | append . }} +{{ end }} +{{ $s }} → [0 1 2] +``` + +### Rebind context + +See documentation for [`with`], [`else`], and [`end`]. + +```go-html-template +{{ $var := "foo" }} +{{ with $var }} + {{ . }} → foo +{{ else }} + {{ print "var is falsy" }} +{{ end }} +``` + +To test multiple conditions: + +```go-html-template +{{ $v1 := 0 }} +{{ $v2 := 42 }} +{{ with $v1 }} + {{ . }} +{{ else with $v2 }} + {{ . }} → 42 +{{ else }} + {{ print "v1 and v2 are falsy" }} +{{ end }} +``` + +### Access site parameters + +See documentation for the [`Params`](/methods/site/params/) method on a `Site` object. + - With this site configuration: ++With this project configuration: + +{{< code-toggle file=hugo >}} +title = 'ABC Widgets' +baseURL = 'https://example.org' +[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 site parameters by chaining the identifiers: + +```go-html-template +{{ .Site.Params.subtitle }} → The Best Widgets on Earth +{{ .Site.Params.author.name }} → John Smith + +{{ $layout := .Site.Params.layouts.rfc_1123 }} +{{ .Site.Lastmod.Format $layout }} → Tue, 17 Oct 2023 13:21:02 PDT +``` + +### Access page parameters + +See documentation for the [`Params`](/methods/page/params/) method on a `Page` object. + +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 +``` + +[`and`]: /functions/go-template/and +[`else`]: /functions/go-template/else/ +[`end`]: /functions/go-template/end/ +[`if`]: /functions/go-template/if/ +[`index`]: /functions/collections/indexfunction/ +[`or`]: /functions/go-template/or +[`Page`]: /methods/page/ +[`partial`]: /functions/partials/include/ +[`partialCached`]: /functions/partials/includecached/ +[`range`]: /functions/go-template/range/ +[`safeHTML`]: /functions/safe/html +[`Site`]: /methods/site/ +[`template`]: /functions/go-template/template/ +[`Title`]: /methods/page/title +[`with`]: /functions/go-template/with/ +[current context]: #current-context +[embedded templates]: /templates/embedded/ +[front matter fields]: /content-management/front-matter/#fields +[front matter]: /content-management/front-matter/ +[functions]: /functions/ +[go-templates]: /functions/go-template/ +[html/template]: https://pkg.go.dev/html/template +[methods]: /methods/ +[partial templates]: /templates/types/#partial +[templates]: /templates/ +[text/template]: https://pkg.go.dev/text/template +[variables]: #variables diff --cc docs/content/en/templates/menu.md index aa0e7c673,000000000..976e9f832 mode 100644,000000..100644 --- a/docs/content/en/templates/menu.md +++ b/docs/content/en/templates/menu.md @@@ -1,127 -1,0 +1,127 @@@ +--- +title: Menu templates +description: Create templates to render one or more menus. +categories: [] +keywords: [] +weight: 150 +aliases: [/templates/menus/,/templates/menu-templates/] +--- + +## Overview + +After [defining menu entries], use [menu methods] to render a menu. + +Three factors determine how to render a menu: + - 1. The method used to define the menu entries: [automatic], [in front matter], or [in site configuration] ++1. The method used to define the menu entries: [automatic], in [front matter], or in your [project configuration] +1. The menu structure: flat or nested - 1. The method used to [localize the menu entries]: site configuration or translation tables ++1. The method used to [localize the menu entries]: project configuration or translation tables + +The example below handles every combination. + +## Example + +This _partial_ template recursively "walks" a menu structure, rendering a localized, accessible nested list. + +```go-html-template {file="layouts/_partials/menu.html" copy=true} +{{- $page := .page }} +{{- $menuID := .menuID }} + +{{- with index site.Menus $menuID }} + +{{- end }} + +{{- define "_partials/inline/menu/walk.html" }} + {{- $page := .page }} + {{- range .menuEntries }} + {{- $attrs := dict "href" .URL }} + {{- if $page.IsMenuCurrent .Menu . }} + {{- $attrs = merge $attrs (dict "class" "active" "aria-current" "page") }} + {{- else if $page.HasMenuCurrent .Menu .}} + {{- $attrs = merge $attrs (dict "class" "ancestor" "aria-current" "true") }} + {{- end }} + {{- $name := .Name }} + {{- with .Identifier }} + {{- with T . }} + {{- $name = . }} + {{- end }} + {{- end }} +
  • + {{ $name }} + {{- with .Children }} +
      + {{- partial "inline/menu/walk.html" (dict "page" $page "menuEntries" .) }} +
    + {{- end }} +
  • + {{- end }} +{{- end }} +``` + +Call the partial above, passing a menu ID and the current page in context. + +```go-html-template {file="layouts/page.html"} +{{ partial "menu.html" (dict "menuID" "main" "page" .) }} +{{ partial "menu.html" (dict "menuID" "footer" "page" .) }} +``` + +## Page references + +Regardless of how you [define menu entries], an entry associated with a page has access to page context. + +This simplistic example renders a page parameter named `version` next to each entry's `name`. Code defensively using `with` or `if` to handle entries where (a) the entry points to an external resource, or (b) the `version` parameter is not defined. + +```go-html-template {file="layouts/page.html"} +{{- range site.Menus.main }} + + {{ .Name }} + {{- with .Page }} + {{- with .Params.version -}} + ({{ . }}) + {{- end }} + {{- end }} + +{{- end }} +``` + +## Menu entry parameters + - When you define menu entries [in site configuration] or [in front matter], you can include a `params` key as shown in these examples: ++When you define menu entries in your [project configuration] or in [front matter], you can include a `params` key as shown in these examples: + - - [Menu entry defined in site configuration] ++- [Menu entry defined in your project configuration] +- [Menu entry defined in front matter] + +This simplistic example renders a `class` attribute for each anchor element. Code defensively using `with` or `if` to handle entries where `params.class` is not defined. + +```go-html-template {file="layouts/_partials/menu.html"} +{{- range site.Menus.main }} + + {{ .Name }} + +{{- end }} +``` + +## Localize + +Hugo provides two methods to localize your menu entries. See [multilingual]. + +[automatic]: /content-management/menus/#define-automatically +[define menu entries]: /content-management/menus/ +[defining menu entries]: /content-management/menus/ - [in front matter]: /content-management/menus/#define-in-front-matter - [in site configuration]: /content-management/menus/#define-in-site-configuration ++[front matter]: /content-management/menus/#define-in-front-matter +[localize the menu entries]: /content-management/multilingual/#menus +[menu entry defined in front matter]: /content-management/menus/#example - [menu entry defined in site configuration]: /configuration/menus ++[menu entry defined in your project configuration]: /configuration/menus +[menu methods]: /methods/menu/ +[multilingual]: /content-management/multilingual/#menus ++[project configuration]: /content-management/menus/#define-in-project-configuration diff --cc docs/content/en/templates/pagination.md index a1174980d,000000000..3891da574 mode 100644,000000..100644 --- a/docs/content/en/templates/pagination.md +++ b/docs/content/en/templates/pagination.md @@@ -1,240 -1,0 +1,240 @@@ +--- +title: Pagination +description: Split a list page into two or more subsets. +categories: [] +keywords: [] +weight: 160 +aliases: [/extras/pagination,/doc/pagination/] +--- + +Displaying a large page collection on a list page is not user-friendly: + +- A massive list can be intimidating and difficult to navigate. Users may get lost in the sheer volume of information. +- Large pages take longer to load, which can frustrate users and lead to them abandoning the site. +- Without any filtering or organization, finding a specific item becomes a tedious scrolling exercise. + +Improve usability by paginating `home`, `section`, `taxonomy`, and `term` pages. + +> [!note] +> The most common templating mistake related to pagination is invoking pagination more than once for a given list page. See the [caching](#caching) section below. + +## Terminology + +paginate +: To split a [list page](g) into two or more subsets. + +pagination +: The process of paginating a list page. + +pager +: Created during pagination, a pager contains a subset of a list page and navigation links to other pagers. + +paginator +: A collection of pagers. + +## Configuration + +See [configure pagination](/configuration/pagination). + +## Methods + +To paginate a `home`, `section`, `taxonomy`, or `term` page, invoke either of these methods on the `Page` object in the corresponding template: + +- [`Paginate`] +- [`Paginator`] + +The `Paginate` method is more flexible, allowing you to: + +- Paginate any page collection +- Filter, sort, and group the page collection - - Override the number of pages per pager as defined in your site configuration ++- Override the number of pages per pager as defined in your project configuration + +By comparison, the `Paginator` method paginates the page collection passed into the template, and you cannot override the number of pages per pager. + +## Examples + +To paginate a list page using the `Paginate` method: + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate $pages.ByTitle 7 }} + +{{ range $paginator.Pages }} +

    {{ .LinkTitle }}

    +{{ end }} + +{{ partial "pagination.html" . }} +``` + +In the example above, we: + +1. Build a page collection +1. Sort the page collection by title +1. Paginate the page collection, with 7 pages 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 + +To paginate a list page using the `Paginator` method: + +```go-html-template +{{ range .Paginator.Pages }} +

    {{ .LinkTitle }}

    +{{ end }} + +{{ partial "pagination.html" . }} +``` + +In the example above, we: + +1. Paginate the page collection passed into the template, with the default number of pages 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 + +## Caching + +> [!note] +> The most common templating mistake related to pagination is invoking pagination more than once for a given list page. + +Regardless of pagination method, the initial invocation is cached and cannot be changed. If you invoke pagination more than once for a given list page, subsequent invocations use the cached result. This means that subsequent invocations will not behave as written. + +When paginating conditionally, do not use the `compare.Conditional` function due to its eager evaluation of arguments. Use an `if-else` construct instead. + +## Grouping + +Use pagination with any of the [grouping methods]. For example: + +```go-html-template +{{ $pages := where site.RegularPages "Type" "posts" }} +{{ $paginator := .Paginate ($pages.GroupByDate "Jan 2006") }} + +{{ range $paginator.PageGroups }} +

    {{ .Key }}

    + {{ range .Pages }} +

    {{ .LinkTitle }}

    + {{ end }} +{{ end }} + +{{ partial "pagination.html" . }} +``` + +## Navigation + +As shown in the examples above, the easiest way to add navigation between pagers is with Hugo's embedded pagination template: + +```go-html-template +{{ partial "pagination.html" . }} +``` + +The embedded pagination template has two formats: `default` and `terse`. The above is equivalent to: + +```go-html-template +{{ partial "pagination.html" (dict "page" . "format" "default") }} +``` + +The `terse` format has fewer controls and page slots, consuming less space when styled as a horizontal list. To use the `terse` format: + +```go-html-template +{{ partial "pagination.html" (dict "page" . "format" "terse") }} +``` + +> [!note] +> To override Hugo's embedded pagination template, copy the [source code] to a file with the same name in the `layouts/_partials` directory, then call it from your templates using the [`partial`] function: +> +> `{{ partial "pagination.html" . }}` + +Create custom navigation components using any of the `Pager` methods: + +{{% list-pages-in-section path=/methods/pager %}} + +## Structure + +The example below depicts the published site structure when paginating a list page. + +With this content: + +```text +content/ +├── posts/ +│ ├── _index.md +│ ├── post-1.md +│ ├── post-2.md +│ ├── post-3.md +│ └── post-4.md +└── _index.md +``` + - And this site configuration: ++And this project configuration: + +{{< code-toggle file=hugo >}} +[pagination] + disableAliases = false + pagerSize = 2 + path = 'page' +{{< /code-toggle >}} + +And this _section_ template: + +```go-html-template {file="layouts/section.html"} +{{ range (.Paginate .Pages).Pages }} +

    {{ .LinkTitle }}

    +{{ end }} + +{{ partial "pagination.html" . }} +``` + +The published site has this structure: + +```text +public/ +├── posts/ +│ ├── page/ +│ │ ├── 1/ +│ │ │ └── index.html <-- alias to public/posts/index.html +│ │ └── 2/ +│ │ └── index.html +│ ├── post-1/ +│ │ └── index.html +│ ├── post-2/ +│ │ └── index.html +│ ├── post-3/ +│ │ └── index.html +│ ├── post-4/ +│ │ └── index.html +│ └── index.html +└── index.html +``` + - To disable alias generation for the first pager, change your site configuration: ++To disable alias generation for the first pager, change your project configuration: + +{{< code-toggle file=hugo >}} +[pagination] + disableAliases = true + pagerSize = 2 + path = 'page' +{{< /code-toggle >}} + +Now the published site will have this structure: + +```text +public/ +├── posts/ +│ ├── page/ +│ │ └── 2/ +│ │ └── index.html +│ ├── post-1/ +│ │ └── index.html +│ ├── post-2/ +│ │ └── index.html +│ ├── post-3/ +│ │ └── index.html +│ ├── post-4/ +│ │ └── index.html +│ └── index.html +└── index.html +``` + +[`Paginate`]: /methods/page/paginate/ +[`Paginator`]: /methods/page/paginator/ +[`partial`]: /functions/partials/include/ +[grouping methods]: /quick-reference/page-collections/#group +[source code]: <{{% eturl pagination %}}> diff --cc docs/content/en/templates/robots.md index 75bd8bbce,000000000..00ca20e41 mode 100644,000000..100644 --- a/docs/content/en/templates/robots.md +++ b/docs/content/en/templates/robots.md @@@ -1,52 -1,0 +1,52 @@@ +--- +title: robots.txt template +linkTitle: robots.txt templates +description: Hugo can generate a customized robots.txt in the same way as any other template. +categories: [] +keywords: [] +weight: 190 +aliases: [/extras/robots-txt/] +--- + - To generate a robots.txt file from a template, change the [site configuration]: ++To generate a robots.txt file from a template, change your [project configuration]: + +{{< code-toggle file=hugo >}} +enableRobotsTXT = true +{{< /code-toggle >}} + +By default, Hugo generates robots.txt using an [embedded template]. + +```text +User-agent: * +``` + +Search engines that honor the Robots Exclusion Protocol will interpret this as permission to crawl everything on the site. + +## robots.txt template lookup order + +You may overwrite the internal template with a custom template. Hugo selects the template using this lookup order: + +1. `/layouts/robots.txt` +1. `/themes//layouts/robots.txt` + +## robots.txt template example + +```text {file="layouts/robots.txt"} +User-agent: * +{{ range .Pages }} +Disallow: {{ .RelPermalink }} +{{ end }} +``` + +This template creates a robots.txt file with a `Disallow` directive for each page on the site. Search engines that honor the Robots Exclusion Protocol will not crawl any page on the site. + +> [!note] +> To create a robots.txt file without using a template: +> - > 1. Set `enableRobotsTXT` to `false` in the site configuration. ++> 1. Set `enableRobotsTXT` to `false` in your project configuration. +> 1. Create a robots.txt file in the `static` directory. +> - > Remember that Hugo copies everything in the static director to the root of `publishDir` (typically `public`) when you build your site. ++> Remember that Hugo copies everything in the static director to the root of `publishDir` (typically `public`) when you build your project. + +[embedded template]: <{{% eturl robots %}}> - [site configuration]: /configuration/ ++[project configuration]: /configuration/ diff --cc docs/content/en/templates/rss.md index cbc393a03,000000000..e0c64e421 mode 100644,000000..100644 --- a/docs/content/en/templates/rss.md +++ b/docs/content/en/templates/rss.md @@@ -1,75 -1,0 +1,75 @@@ +--- +title: RSS templates +description: Use the embedded RSS template, or create your own. +categories: [] +keywords: [] +weight: 140 +--- + +## Configuration + - By default, when you build your site, Hugo generates RSS feeds for home, section, taxonomy, and term pages. Control feed generation in your site configuration. For example, to generate feeds for home and section pages, but not for taxonomy and term pages: ++By default, when you build your project, Hugo generates RSS feeds for home, section, taxonomy, and term pages. Control feed generation in your project configuration. For example, to generate feeds for home and section pages, but not for taxonomy and term pages: + +{{< code-toggle file=hugo >}} +[outputs] +home = ['html', 'rss'] +section = ['html', 'rss'] +taxonomy = ['html'] +term = ['html'] +{{< /code-toggle >}} + +To disable feed generation for all [page kinds](g): + +{{< code-toggle file=hugo >}} +disableKinds = ['rss'] +{{< /code-toggle >}} + - By default, the number of items in each feed is unlimited. Change this as needed in your site configuration: ++By default, the number of items in each feed is unlimited. Change this as needed in your project configuration: + +{{< code-toggle file=hugo >}} +[services.rss] +limit = 42 +{{< /code-toggle >}} + +Set `limit` to `-1` to generate an unlimited number of items per feed. + - The built-in RSS template will render the following values, if present, from your site configuration: ++The built-in RSS template will render the following values, if present, from your project configuration: + +{{< code-toggle file=hugo >}} +copyright = '© 2023 ABC Widgets, Inc.' +[params.author] +name = 'John Doe' +email = 'jdoe@example.org' +{{< /code-toggle >}} + +## Include feed reference + +To include a feed reference in the `head` element of your rendered pages, place this within the `head` element of your templates: + +```go-html-template +{{ with .OutputFormats.Get "rss" }} + {{ printf `` .Rel .MediaType.Type .Permalink site.Title | safeHTML }} +{{ end }} +``` + +Hugo will render this to: + +```html + +``` + +## Custom templates + +Override Hugo's [embedded RSS template] by creating one or more of your own. For example, to use different templates for home, section, taxonomy, and term pages: + +```text +layouts/ + ├── home.rss.xml + ├── section.rss.xml + ├── taxonomy.rss.xml + └── term.rss.xml +``` + +RSS templates receive the `.Page` and `.Site` objects in context. + +[embedded RSS template]: <{{% eturl rss %}}> diff --cc docs/content/en/templates/sitemap.md index a79ec7bba,000000000..221cb6c0f mode 100644,000000..100644 --- a/docs/content/en/templates/sitemap.md +++ b/docs/content/en/templates/sitemap.md @@@ -1,54 -1,0 +1,54 @@@ +--- +title: Sitemap templates +description: Hugo provides built-in sitemap templates. +categories: [] +keywords: [] +weight: 130 +aliases: [/layout/sitemap/,/templates/sitemap-template/] +--- + +## Overview + +Hugo's embedded sitemap templates conform to v0.9 of the [sitemap protocol]. + +With a monolingual project, Hugo generates a sitemap.xml file in the root of the [`publishDir`] using the [embedded sitemap template]. + +With a multilingual project, Hugo generates: + +- A sitemap.xml file in the root of each site (language) using the [embedded sitemap template] +- A sitemap.xml file in the root of the [`publishDir`] using the [embedded sitemapindex template] + +## Configuration + +See [configure sitemap](/configuration/sitemap). + +## Override default values + +Override the default values for a given page in front matter. + +{{< code-toggle file=news.md fm=true >}} +title = 'News' +[sitemap] + changefreq = 'weekly' + disable = true + priority = 0.8 +{{}} + +## Override built-in templates + +To override the built-in sitemap.xml template, create a new `layouts/sitemap.xml` file. When ranging through the page collection, access the _change frequency_ and _priority_ with `.Sitemap.ChangeFreq` and `.Sitemap.Priority` respectively. + +To override the built-in sitemapindex.xml template, create a new `layouts/sitemapindex.xml` file. + +## Disable sitemap generation + - You may disable sitemap generation in your site configuration: ++You may disable sitemap generation in your project configuration: + +{{< code-toggle file=hugo >}} +disableKinds = ['sitemap'] +{{}} + +[`publishDir`]: /configuration/all/#publishdir +[embedded sitemap template]: <{{% eturl sitemap %}}> +[embedded sitemapindex template]: <{{% eturl sitemapindex %}}> +[sitemap protocol]: https://www.sitemaps.org/protocol.html diff --cc docs/content/en/tools/other.md index 489d78506,000000000..052041c7a mode 100644,000000..100644 --- a/docs/content/en/tools/other.md +++ b/docs/content/en/tools/other.md @@@ -1,20 -1,0 +1,20 @@@ +--- +title: Other community projects +linkTitle: Other projects +description: Some interesting projects developed by the Hugo community that don't quite fit into our other developer tool categories. +categories: [] +keywords: [] +weight: 50 +--- + +And for all the other community projects around Hugo: + +- [diego](https://github.com/ttybitnik/diego) - A CLI tool that integrates with Hugo to assist in importing and utilizing exported social media data from popular services on Hugo websites. - - [Emacs Easy Hugo](https://github.com/masasam/emacs-easy-hugo) - Emacs package for writing blog posts in Markdown or org-mode and building your site with Hugo. ++- [Emacs Easy Hugo](https://github.com/masasam/emacs-easy-hugo) - Emacs package for writing blog posts in Markdown or org-mode and building your project with Hugo. +- [Hugo SFTP Upload](https://github.com/thomasmey/HugoSftpUpload) - Sync the local build of your Hugo website with your remote web server via SFTP. +- [HugoPhotoSwipe](https://github.com/GjjvdBurg/HugoPhotoSwipe) - Make it easy to create image galleries using PhotoSwipe. +- [JAMStack Themes](https://jamstackthemes.dev/ssg/hugo/) - A collection of site themes filterable by static site generator and supported CMS to help build CMS-connected sites using Hugo (linking to Hugo-specific themes). +- [flickr-hugo-embed](https://github.com/nikhilm/flickr-hugo-embed) - Print shortcodes to embed a set of images from an album on Flickr into Hugo. +- [hugo-gallery](https://github.com/icecreammatt/hugo-gallery) - Create an image gallery for Hugo sites. +- [hugo-openapispec-shortcode](https://github.com/tenfourty/hugo-openapispec-shortcode) - A shortcode that allows you to include [Open API Spec](https://openapis.org) (formerly known as Swagger Spec) in a page. +- [plausible-hugo](https://github.com/divinerites/plausible-hugo) - Easy Hugo integration for Plausible Analytics, a simple, open-source, lightweight and privacy-friendly web analytics alternative to Google Analytics. diff --cc docs/content/en/troubleshooting/audit/index.md index 2efad55e3,000000000..a20b33651 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/audit/index.md +++ b/docs/content/en/troubleshooting/audit/index.md @@@ -1,68 -1,0 +1,68 @@@ +--- +title: Site audit +linkTitle: Audit +description: Run this audit before deploying your production site. +categories: [] +keywords: [] +--- + +There are several conditions that can produce errors in your published site which are not detected during the build. Run this audit before your final build. + +```text {copy=true} +HUGO_MINIFY_TDEWOLFF_HTML_KEEPCOMMENTS=true HUGO_ENABLEMISSINGTRANSLATIONPLACEHOLDERS=true hugo && grep -inorE "<\!-- raw HTML omitted -->|ZgotmplZ|\[i18n\]|\(\)|(<nil>)|hahahugo" public/ +``` + +_Tested with GNU Bash 5.1 and GNU grep 3.7._ + +## Example output + +![site audit terminal output](screen-capture.png) + +## Explanation + +### Environment variables + +`HUGO_MINIFY_TDEWOLFF_HTML_KEEPCOMMENTS=true` - : Retain HTML comments even if minification is enabled. This takes precedence over `minify.tdewolff.html.keepComments` in the site configuration. If you minify without keeping HTML comments when performing this audit, you will not be able to detect when raw HTML has been omitted. ++: Retain HTML comments even if minification is enabled. This takes precedence over `minify.tdewolff.html.keepComments` in your project configuration. If you minify without keeping HTML comments when performing this audit, you will not be able to detect when raw HTML has been omitted. + +`HUGO_ENABLEMISSINGTRANSLATIONPLACEHOLDERS=true` - : Show a placeholder instead of the default value or an empty string if a translation is missing. This takes precedence over `enableMissingTranslationPlaceholders` in the site configuration. ++: Show a placeholder instead of the default value or an empty string if a translation is missing. This takes precedence over `enableMissingTranslationPlaceholders` in your project configuration. + +### Grep options + +`-i, --ignore-case` +: Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. + +`-n, --line-number` +: Prefix each line of output with the 1-based line number within its input file. + +`-o, --only-matching` +: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. + +`-r, --recursive` +: Read all files under each directory, recursively, following symbolic links only if they are on the command line. + +`-E, --extended-regexp` +: Interpret PATTERNS as extended regular expressions. + +### Patterns + +`` +: By default, Hugo strips raw HTML from your Markdown prior to rendering, and leaves this HTML comment in its place. + +`ZgotmplZ` +: ZgotmplZ is a special value that indicates that unsafe content reached a CSS or URL context at runtime. See [details]. + +[details]: https://pkg.go.dev/html/template + +`[i18n]` +: This is the placeholder produced instead of the default value or an empty string if a translation is missing. + +`()` +: This string will appear in the rendered HTML when passing a nil value to the `printf` function. + +`(<nil>)` +: Same as above when the value returned from the `printf` function has not been passed through `safeHTML`. + +`HAHAHUGO` +: Under certain conditions a rendered shortcode may include all or a portion of the string HAHAHUGOSHORTCODE in either uppercase or lowercase. This is difficult to detect in all circumstances, but a case-insensitive search of the output for `HAHAHUGO` is likely to catch the majority of cases without producing false positives. diff --cc docs/content/en/troubleshooting/deprecation.md index f2e5259a6,000000000..a627a0e36 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/deprecation.md +++ b/docs/content/en/troubleshooting/deprecation.md @@@ -1,51 -1,0 +1,51 @@@ +--- +title: Deprecation +description: The Hugo project follows a formal and consistent process to deprecate functions, methods, and configuration settings. +categories: [] +keywords: [] +--- + +When a project _deprecates_ something, they are telling its users: + +1. Don't use Thing One anymore. +1. Use Thing Two instead. +1. We're going to remove Thing One at some point in the future. + +[reasons for deprecation]: https://en.wikipedia.org/wiki/Deprecation + +Common [reasons for deprecation]: + +- A feature has been replaced by a more powerful alternative. +- A feature contains a design flaw. +- A feature is considered extraneous, and will be removed in the future in order to simplify the system as a whole. +- A future version of the software will make major structural changes, making it impossible or impractical to support older features. +- Standardization or increased consistency in naming. +- A feature that once was available only independently is now combined with its co-feature. + +After the project team deprecates something in code, Hugo will: + +1. Log an INFO message for 3 minor releases[^1] +1. Log a WARN message for another 12 minor releases +1. Log an ERROR message and fail the build thereafter + +The project team will: + +1. On the deprecation date, update the documentation with a note describing the deprecation and any relevant alternatives. +1. Remove the code six or more minor releases after Hugo begins logging ERROR messages and failing the build. At that point, Hugo will throw an error, but the error message will no longer mention the deprecation. +1. Remove the corresponding documentation two years after the deprecation date. + +To see the INFO messages, you must use the `--logLevel` command line flag: + +```text - hugo --logLevel info ++hugo build --logLevel info +``` + +To limit the output to deprecation notices: + +```text - hugo --logLevel info | grep deprecate ++hugo build --logLevel info | grep deprecate +``` + +Run the above command every time you upgrade Hugo. + +[^1]: For example, v0.1.1 => v0.2.0 is a minor release. diff --cc docs/content/en/troubleshooting/logging.md index 0cd25d1ae,000000000..2a98633d7 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/logging.md +++ b/docs/content/en/troubleshooting/logging.md @@@ -1,65 -1,0 +1,65 @@@ +--- +title: Logging - description: Enable logging to inspect events while building your site. ++description: Enable logging to inspect events while building your project. +categories: [] +keywords: [] +--- + +## Command line + +Enable console logging with the `--logLevel` command line flag. + +Hugo has four logging levels: + +error +: Display error messages only. + + ```sh - hugo --logLevel error ++ hugo build --logLevel error + ``` + +warn +: Display warning and error messages. + + ```sh - hugo --logLevel warn ++ hugo build --logLevel warn + ``` + +info +: Display information, warning, and error messages. + + ```sh - hugo --logLevel info ++ hugo build --logLevel info + ``` + +debug +: Display debug, information, warning, and error messages. + + ```sh - hugo --logLevel debug ++ hugo build --logLevel debug + ``` + +> [!note] +> If you do not specify a logging level with the `--logLevel` flag, warnings and errors are always displayed. + +## Template functions + +You can also use template functions to print warnings or errors to the console. These functions are typically used to report data validation errors, missing files, etc. + +{{% list-pages-in-section path=/functions/fmt filter=functions_fmt_logging filterType=include %}} + +## LiveReload + +To log Hugo's LiveReload requests in your browser, add this query string to the URL when running Hugo's development server: + +```text +debug=LR-verbose +``` + +For example: + +```text +http://localhost:1313/?debug=LR-verbose +``` + +Then monitor the reload requests in your browser's dev tools console. Make sure the dev tools "preserve log" option is enabled. diff --cc docs/content/en/troubleshooting/performance.md index c52dc6966,000000000..45be5c7be mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/performance.md +++ b/docs/content/en/troubleshooting/performance.md @@@ -1,102 -1,0 +1,102 @@@ +--- +title: Performance +description: Tools and suggestions for evaluating and improving performance. +categories: [] +keywords: [] +aliases: [/troubleshooting/build-performance/] +--- + +## Virus scanning + +Virus scanners are an essential component of system protection, but the performance impact can be severe for applications like Hugo that frequently read and write to disk. For example, with Microsoft Defender Antivirus, build times for some sites may increase by 400% or more. + +Before building a site, your virus scanner has already evaluated the files in your project directory. Scanning them again while building the site is superfluous. To improve performance, add Hugo's executable to your virus scanner's process exclusion list. + +For example, with Microsoft Defender Antivirus: + +**Start** > **Settings** > **Privacy & security** > **Windows Security** > **Open Windows Security** > **Virus & threat protection** > **Manage settings** > **Add or remove exclusions** > **Add an exclusion** > **Process** + +Then type `hugo.exe` add press the **Add** button. + +> [!note] +> Virus scanning exclusions are common, but use caution when changing these settings. See the [Microsoft Defender Antivirus documentation] for details. + +Other virus scanners have similar exclusion mechanisms. See their respective documentation. + +## Template metrics + +Hugo is fast, but inefficient templates impede performance. Enable template metrics to determine which templates take the most time, and to identify caching opportunities: + +```sh - hugo --templateMetrics --templateMetricsHints ++hugo build --templateMetrics --templateMetricsHints +``` + +The result will look something like this: + +```text +Template Metrics: + + cumulative average maximum cache percent cached total + duration duration duration potential cached count count template + ---------- -------- -------- --------- ------- ------ ----- -------- + 36.037476822s 135.990478ms 225.765245ms 11 0 0 265 _partials/head.html + 35.920040902s 164.018451ms 233.475072ms 0 0 0 219 articles/page.html + 34.163268129s 128.917992ms 224.816751ms 23 0 0 265 _partials/head/meta/opengraph.html + 1.041227437s 3.92916ms 186.303376ms 47 0 0 265 _partials/head/meta/schema.html + 805.628827ms 27.780304ms 114.678523ms 0 0 0 29 section.html + 624.08354ms 15.221549ms 108.420729ms 8 0 0 41 _partials/utilities/render-page-collection.html + 545.968801ms 775.523µs 105.045775ms 0 0 0 704 summary.html + 334.680981ms 1.262947ms 127.412027ms 100 0 0 265 _partials/head/js.html + 272.763205ms 2.050851ms 24.371757ms 0 0 0 133 _markup/render-codeblock.html + 163.951469ms 14.904679ms 70.267953ms 0 0 0 11 articles/section.html + 153.07021ms 577.623µs 73.593597ms 100 0 0 265 _partials/head/init.html + 150.910984ms 150.910984ms 150.910984ms 0 0 0 1 page.html + 146.785804ms 146.785804ms 146.785804ms 0 0 0 1 contact.html + 115.364617ms 115.364617ms 115.364617ms 0 0 0 1 authors/term.html + 87.392071ms 329.781µs 10.687132ms 100 0 0 265 _partials/head/css.html + 86.803122ms 86.803122ms 86.803122ms 0 0 0 1 home.html +``` + +From left to right, the columns represent: + +cumulative duration +: The cumulative time spent executing the template. + +average duration +: The average time spent executing the template. + +maximum duration +: The maximum time spent executing the template. + +cache potential +: Displayed as a percentage, any _partial_ template with a 100% cache potential should be called with the [`partialCached`] function instead of the [`partial`] function. See the [caching](#caching) section below. + +percent cached +: The number of times the rendered templated was cached divided by the number of times the template was executed. + +cached count +: The number of times the rendered templated was cached. + +total count +: The number of times the template was executed. + +template +: The path to the template, relative to the `layouts` directory. + +> [!note] +> Hugo builds pages in parallel where multiple pages are generated simultaneously. Because of this parallelism, the sum of "cumulative duration" values is usually greater than the actual time it takes to build a site. + +## Caching + +Some _partial_ templates such as sidebars or menus are executed many times during a site build. Depending on the content within the _partial_ template and the desired output, the template may benefit from caching to reduce the number of executions. The [`partialCached`] template function provides caching capabilities for _partial_ templates. + +> [!note] +> Note that you can create cached variants of each partial by passing additional arguments to `partialCached` beyond the initial context. See the `partialCached` documentation for more details. + +## Timers + +Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottlenecks in templates. See [details](/functions/debug/timer/). + +[`partial`]: /functions/partials/include/ +[`partialCached`]: /functions/partials/includecached/ +[Microsoft Defender Antivirus documentation]: https://support.microsoft.com/en-us/topic/how-to-add-a-file-type-or-process-exclusion-to-windows-security-e524cbc2-3975-63c2-f9d1-7c2eb5331e53 diff --cc docs/layouts/_markup/render-codeblock.html index 0f1d09d1f,000000000..f9a7d8ddf mode 100644,000000..100644 --- a/docs/layouts/_markup/render-codeblock.html +++ b/docs/layouts/_markup/render-codeblock.html @@@ -1,112 -1,0 +1,112 @@@ +{{/* prettier-ignore-start */}} +{{/* +Renders a highlighted code block using the given options and attributes. + +In addition to the options available to the transform.Highlight function, you +may also specify the following parameters: + +@param {bool} [copy=false] Whether to display a copy-to-clipboard button. +@param {string} [file] The file name to display above the rendered code. +@param {bool} [details=false] Whether to wrap the highlighted code block within a details element. +@param {bool} [open=false] Whether to initially display the content of the details element. +@param {string} [summary=Details] The content of the details summary element rendered from Markdown to HTML. +@param {bool} [trim=true] Whether to trim leading and trailing whitespace from the content of the code block. + +@returns {template.HTML} + +@examples + + ```go + fmt.Println("Hello world!") + ``` + + ```go {linenos=true file="layouts/index.html" copy=true} + fmt.Println("Hello world!") + ``` +*/}} +{{/* prettier-ignore-end */}} + +{{- $copy := false }} +{{- $file := or .Attributes.file "" }} +{{- $details := false }} +{{- $open := "" }} +{{- $summary := or .Attributes.summary "Details" | .Page.RenderString }} +{{- $trim := true }} +{{- $ext := strings.TrimPrefix "." (path.Ext $file) }} +{{- $lang := or .Type $ext "text" }} +{{- if in (slice "html" "gotmpl") $lang }} + {{- $lang = "go-html-template" }} +{{- end }} +{{- if eq $lang "md" }} + {{- $lang = "text" }} +{{- end }} + +{{- if collections.IsSet .Attributes "copy" }} + {{- if in (slice true "true" 1) .Attributes.copy }} + {{- $copy = true }} + {{- else if in (slice false "false" 0) .Attributes.copy }} + {{- $copy = false }} + {{- end }} +{{- end }} + +{{- if collections.IsSet .Attributes "details" }} + {{- if in (slice true "true" 1) .Attributes.details }} + {{- $details = true }} + {{- else if in (slice false "false" 0) .Attributes.details }} + {{- $details = false }} + {{- end }} +{{- end }} + +{{- if collections.IsSet .Attributes "open" }} + {{- if in (slice true "true" 1) .Attributes.open }} + {{- $open = "open" }} + {{- else if in (slice false "false" 0) .Attributes.open }} + {{- $open = "" }} + {{- end }} +{{- end }} + +{{- if collections.IsSet .Attributes "trim" }} + {{- if in (slice true "true" 1) .Attributes.trim }} + {{- $trim = true }} + {{- else if in (slice false "false" 0) .Attributes.trim }} + {{- $trim = false }} + {{- end }} +{{- end }} + +{{- if $details }} +
    + {{ $summary }} +{{- end }} + +
    ++ class="render-hook-codeblock font-mono not-prose relative mt-6 mb-8 border border-gray-200 dark:border-gray-800 bg-light dark:bg-dark"> + {{- $fileSelectClass := "select-none" }} + {{- if $copy }} + {{- $fileSelectClass = "select-text" }} + + + + {{- end }} + {{- with $file }} +
    + {{ . }} +
    + {{- end }} + +
    + {{- $content := .Inner }} + {{- if $trim }} + {{- $content = strings.TrimSpace .Inner }} + {{- end }} + {{- transform.Highlight $content $lang .Options }} +
    +
    + +{{- if $details }} +
    +{{- end }} diff --cc docs/layouts/_partials/helpers/validation/validate-keywords.html index 3447ec4ef,000000000..58500c0a4 mode 100644,000000..100644 --- a/docs/layouts/_partials/helpers/validation/validate-keywords.html +++ b/docs/layouts/_partials/helpers/validation/validate-keywords.html @@@ -1,22 -1,0 +1,22 @@@ +{{/* prettier-ignore-start */ -}} +{{- /* +We use the front matter keywords field to determine related content. To ensure +consistency, during site build we validate each keyword against the entries in +data/keywords.yaml. + +As of March 5, 2025, this feature is experimental, pending usability +assessment. We anticipate that the number of additions to data/keywords.yaml +will decrease over time, though the initial implementation will require some +effort. +*/}} +{{/* prettier-ignore-end */ -}} +{{- $t := debug.Timer "validateKeywords" }} - {{- $allowedKeywords := collections.Apply site.Data.keywords "strings.ToLower" "." }} ++{{- $allowedKeywords := collections.Apply hugo.Data.keywords "strings.ToLower" "." }} +{{- range $p := site.Pages }} + {{- range .Params.keywords }} + {{- if not (in $allowedKeywords (lower .)) }} + {{- warnf "The word or phrase %q is not in the keywords data file. See %s." . $p.Page.String }} + {{- end }} + {{- end }} +{{- end }} +{{- $t.Stop }} diff --cc docs/layouts/_partials/layouts/home/sponsors.html index 1f391e1ec,000000000..465106de6 mode 100644,000000..100644 --- a/docs/layouts/_partials/layouts/home/sponsors.html +++ b/docs/layouts/_partials/layouts/home/sponsors.html @@@ -1,44 -1,0 +1,44 @@@ +{{ $gtag := .gtag | default "unknown" }} +{{ $gtag := .gtag | default "unknown" }} +{{ $isFooter := (eq $gtag "footer") }} +{{ $utmSource := cond $isFooter "hugofooter" "hugohome" }} +{{ $containerClass := .containerClass | default "mx-auto max-w-7xl px-6 lg:px-8" }} - {{ with .ctx.Site.Data.sponsors }} ++{{ with hugo.Data.sponsors }} +
    +

    Hugo Sponsors

    +
    + {{ range .banners }} +
    + {{ $query_params := .query_params | default "" }} + {{ $url := .link }} + {{ if not .no_query_params }} + {{ $url = printf "%s?%s%s" .link $query_params (querify "utm_source" (.utm_source | default $utmSource ) "utm_medium" (.utm_medium | default "banner") "utm_campaign" (.utm_campaign | default "hugosponsor") "utm_content" (.utm_content | default "gohugoio")) | safeURL }} + {{ end }} + {{ $logo := resources.Get .logo }} + {{ $gtagID := printf "Sponsor %s %s" .name $gtag | title }} + + + +
    + {{ end }} +
    +
    +{{ end }} diff --cc docs/layouts/_shortcodes/chroma-lexers.html index fd7130501,000000000..95bc944b6 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/chroma-lexers.html +++ b/docs/layouts/_shortcodes/chroma-lexers.html @@@ -1,28 -1,0 +1,28 @@@ +{{/* prettier-ignore-start */ -}} +{{- /* +Renders an HTML template of Chroma lexers and their aliases. + +@example {{< chroma-lexers >}} +*/ -}} +{{/* prettier-ignore-end */ -}} +
    + + + + + + - {{- range site.Data.docs.chroma.lexers }} ++ {{- range hugo.Data.docs.chroma.lexers }} + + + + + {{- end }} + +
    LanguageIdentifiers
    {{ .Name }} + {{- range $k, $_ := .Aliases }} + {{- if $k }},{{ end }} + {{ . }} + {{- end }} +
    +
    diff --cc docs/layouts/_shortcodes/code-toggle.html index a22c378be,000000000..48a83b3d3 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/code-toggle.html +++ b/docs/layouts/_shortcodes/code-toggle.html @@@ -1,120 -1,0 +1,120 @@@ +{{/* prettier-ignore-start */ -}} +{{- /* +Renders syntax-highlighted configuration data in JSON, TOML, and YAML formats. + - @param {string} [config] The section of site.Data.docs.config to render. ++@param {string} [config] The section of hugo.Data.docs.config to render. +@param {bool} [copy=false] Whether to display a copy-to-clipboard button. - @param {string} [dataKey] The section of site.Data.docs to render. ++@param {string} [dataKey] The section of hugo.Data.docs to render. +@param {string} [file] The file name to display above the rendered code. +@param {bool} [fm=false] Whether to render the code as front matter. - @param {bool} [skipHeader=false] Whether to omit top level key(s) when rendering a section of site.Data.docs.config. ++@param {bool} [skipHeader=false] Whether to omit top level key(s) when rendering a section of hugo.Data.docs.config. + +@example {{< code-toggle file=hugo config=build />}} + +@example {{< code-toggle file=content/example.md fm="true" }} + title='Example' + draft='false + {{< /code-toggle }} +*/ -}} +{{/* prettier-ignore-end */ -}} +{{- /* Initialize. */}} +{{- $config := "" }} +{{- $copy := false }} +{{- $dataKey := "" }} +{{- $file := "" }} +{{- $fm := false }} +{{- $skipHeader := false }} + +{{- /* Get parameters. */}} +{{- $config = .Get "config" }} +{{- $dataKey = .Get "dataKey" }} +{{- $file = .Get "file" }} +{{- if in (slice "false" false 0) (.Get "copy") }} + {{- $copy = false }} +{{- else if in (slice "true" true 1) (.Get "copy") }} + {{- $copy = true }} +{{- end }} +{{- if in (slice "false" false 0) (.Get "fm") }} + {{- $fm = false }} +{{- else if in (slice "true" true 1) (.Get "fm") }} + {{- $fm = true }} +{{- end }} +{{- if in (slice "false" false 0) (.Get "skipHeader") }} + {{- $skipHeader = false }} +{{- else if in (slice "true" true 1) (.Get "skipHeader") }} + {{- $skipHeader = true }} +{{- end }} + +{{- /* Define constants. */}} +{{- $delimiters := dict "toml" "+++" "yaml" "---" }} +{{- $langs := slice "yaml" "toml" "json" }} +{{- $placeHolder := "#-hugo-placeholder-#" }} + +{{- /* Render. */}} +{{- $code := "" }} +{{- if $config }} + {{- $file = $file | default "hugo" }} + {{- $sections := (split $config ".") }} - {{- $configSection := index $.Site.Data.docs.config $sections }} ++ {{- $configSection := index hugo.Data.docs.config $sections }} + {{- $code = dict $sections $configSection }} + {{- if $skipHeader }} + {{- $code = $configSection }} + {{- end }} +{{- else if $dataKey }} + {{- $file = $file | default $dataKey }} + {{- $sections := (split $dataKey ".") }} - {{- $code = index $.Site.Data.docs $sections }} ++ {{- $code = index hugo.Data.docs $sections }} +{{- else }} + {{- $code = $.Inner }} +{{- end }} + + +
    + {{- if $copy }} + + + + {{- end }} + + {{- if $code }} + {{- range $i, $lang := $langs }} +
    + {{- $hCode := $code | transform.Remarshal . }} + {{- if and $fm (in (slice "toml" "yaml") .) }} + {{- $hCode = printf "%s\n%s\n%s" $placeHolder $hCode $placeHolder }} + {{- end }} + {{- $hCode = $hCode | replaceRE `\n+` "\n" }} + {{- highlight $hCode . "" | replaceRE $placeHolder (index $delimiters .) | safeHTML }} +
    + {{- end }} + {{- end }} +
    diff --cc docs/layouts/_shortcodes/datatable.html index f135d841c,000000000..0ee540d83 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/datatable.html +++ b/docs/layouts/_shortcodes/datatable.html @@@ -1,39 -1,0 +1,39 @@@ +{{ $package := (index .Params 0) }} +{{ $listname := (index .Params 1) }} - {{ $list := (index (index .Site.Data.docs $package) $listname) }} ++{{ $list := (index (index hugo.Data.docs $package) $listname) }} +{{ $fields := after 2 .Params }} + + +
    + + + + {{ range $fields }} + {{ $s := . }} + {{ if eq $s "_key" }} + {{ $s = "type" }} + {{ end }} + + {{ end }} + + + + {{ range $k1, $v1 := $list }} + + {{ range $k2, $v2 := . }} + {{ $.Scratch.Set $k2 $v2 }} + {{ end }} + {{ range $fields }} + {{ $s := "" }} + {{ if eq . "_key" }} + {{ $s = $k1 }} + {{ else }} + {{ $s = $.Scratch.Get . }} + {{ end }} + + {{ end }} + + {{ end }} + +
    {{ $s }}
    {{ $s }}
    +
    diff --cc docs/layouts/_shortcodes/eturl.html index a0237dbe0,000000000..41faf98c7 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/eturl.html +++ b/docs/layouts/_shortcodes/eturl.html @@@ -1,26 -1,0 +1,26 @@@ +{{/* prettier-ignore-start */ -}} +{{- /* +Renders an absolute URL to the source code for an embedded template. + +Accepts either positional or named parameters, and depends on the +embedded_templates.toml file in the data directory. + +@param {string} filename The embedded template's file name, excluding extension. + +@example {{% et robots.txt %}} +@example {{% et filename=robots.txt %}} +*/ -}} +{{/* prettier-ignore-end */ -}} +{{- with $filename := or (.Get "filename") (.Get 0) }} - {{- with site.Data.embedded_template_urls }} ++ {{- with hugo.Data.embedded_template_urls }} + {{- with index . $filename }} - {{- urls.JoinPath site.Data.embedded_template_urls.base_url . }} ++ {{- urls.JoinPath hugo.Data.embedded_template_urls.base_url . }} + {{- else }} + {{- errorf "The %q shortcode was unable to find a URL for the embedded template named %q. Check the name. See %s" $.Name $filename $.Position }} + {{- end }} + {{- else }} + {{- errorf "The %q shortcode was unable to find the embedded_template_urls data file in the site's data directory. See %s" $.Name $.Position }} + {{- end }} +{{- else }} + {{- errorf "The %q shortcodes requires a named or positional parameter, the file name of the embedded template, excluding its extension. See %s" .Name .Position }} +{{- end -}} diff --cc docs/layouts/_shortcodes/list-pages-in-section.html index df06d53ca,000000000..cf74bd93a mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/list-pages-in-section.html +++ b/docs/layouts/_shortcodes/list-pages-in-section.html @@@ -1,70 -1,0 +1,70 @@@ +{{- /* +Renders a description list of the pages in the given section. + +Render a subset of the pages in the section by specifying a predefined filter, +and whether to include those pages. + +Filters are defined in the data directory, in the file named page_filters. Each +filter is an array of paths to a file, relative to the root of the content +directory. Hugo will throw an error if the specified filter does not exist, or +if any of the pages in the filter do not exist. + +@param {string} path The path to the section. +@param {string} [filter=""] The name of filter list. +@param {string} [filterType=""] The type of filter, either include or exclude. +@param {string} [titlePrefix=""] The string to prepend to the link title. + +@example {{% list-pages-in-section path=/methods/resources %}} +@example {{% list-pages-in-section path=/functions/images filter=some_filter filterType=exclude %}} +@example {{% list-pages-in-section path=/functions/images filter=some_filter filterType=exclude titlePrefix=foo %}} +*/}} + +{{/* Initialize. */}} +{{ $filter := or "" (.Get "filter" | lower) }} +{{ $filterType := or (.Get "filterType") "none" | lower }} +{{ $filteredPages := slice }} +{{ $titlePrefix := or (.Get "titlePrefix") "" }} + +{{/* Build slice of filtered pages. */}} +{{ with $filter }} - {{ with index site.Data.page_filters . }} ++ {{ with index hugo.Data.page_filters . }} + {{ range . }} + {{ with site.GetPage . }} + {{ $filteredPages = $filteredPages | append . }} + {{ else }} + {{ errorf "The %q shortcode was unable to find %q as specified in the page_filters data file. See %s" $.Name . $.Position }} + {{ end }} + {{ end }} + {{ else }} + {{ errorf "The %q shortcode was unable to find the %q filter in the page_filters data file. See %s" $.Name . $.Position }} + {{ end }} +{{ end }} + +{{/* Render. */}} +{{ with $sectionPath := .Get "path" }} + {{ with site.GetPage . }} + {{ with .RegularPages }} + {{ range $page := .ByTitle }} + {{ if or + (and (eq $filterType "include") (in $filteredPages $page)) + (and (eq $filterType "exclude") (not (in $filteredPages $page))) + (eq $filterType "none") + }} + {{ $linkTitle := .LinkTitle }} + {{ with $titlePrefix }} + {{ $linkTitle = printf "%s%s" . $linkTitle }} + {{ end }} +{{/* Use page Path as the link destination for render hook to resolve correctly. */}} +[{{ $linkTitle }}]({{ $page.Path }}){{/* Do not indent. */}} +: {{ $page.Description }}{{/* Do not indent. */}} + {{ end }} + {{ end }} + {{ else }} + {{ warnf "The %q shortcode found no pages in the %q section. See %s" $.Name $sectionPath $.Position }} + {{ end }} + {{ else }} + {{ errorf "The %q shortcode was unable to find %q. See %s" $.Name $sectionPath $.Position }} + {{ end }} +{{ else }} + {{ errorf "The %q shortcode requires a 'path' parameter indicating the path to the section. See %s" $.Name $.Position }} +{{ end }} diff --cc docs/layouts/_shortcodes/root-configuration-keys.html index 46a6e074f,000000000..a9c685fc3 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/root-configuration-keys.html +++ b/docs/layouts/_shortcodes/root-configuration-keys.html @@@ -1,45 -1,0 +1,45 @@@ +{{/* prettier-ignore-start */ -}} +{{/* +Renders a comma-separated list of links to the root key configuration pages. + +@example {{< root-configuration-keys >}} +*/ -}} +{{/* prettier-ignore-end */ -}} +{{- /* Create scratch map of key:filename. */}} +{{- $s := newScratch }} - {{- range $k, $v := site.Data.docs.config }} ++{{- range $k, $v := hugo.Data.docs.config }} + {{- if or (reflect.IsMap .) (reflect.IsSlice .) }} + {{- $s.Set $k ($k | humanize | anchorize) }} + {{- end }} +{{- end }} + +{{/* Deprecated. */}} +{{- $s.Delete "author" }} + +{{/* Use mounts instead. */}} +{{- $s.Delete "staticDir" }} +{{- $s.Delete "ignoreFiles" }} + +{{/* This key is "HTTPCache" not "httpCache". */}} +{{- $s.Set "HTTPCache" "http-cache" }} + +{{/* This key is "frontmatter" not "frontMatter" */}} +{{- $s.Set "frontmatter" "front-matter" }} + +{{/* The page title is "Related content" not "related". */}} +{{- $s.Set "related" "related-content" }} + +{{/* It can be configured as bool or map; we want to show map. */}} +{{- $s.Set "uglyURLs" "ugly-urls" }} + +{{- $links := slice }} +{{- range $k, $v := $s.Values }} + {{- $path := printf "/configuration/%s" $v }} + {{- with site.GetPage $path }} + {{- $links = $links | append (printf "%s" .RelPermalink $k) }} + {{- else }} + {{- errorf "The %q shortcode was unable to find the page %s. See %s." $.Name $path $.Position }} + {{- end }} +{{- end }} + +{{- delimit $links ", " ", and " | safeHTML -}} diff --cc docs/layouts/_shortcodes/syntax-highlighting-styles.html index 297849cef,000000000..de6bbdb3b mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/syntax-highlighting-styles.html +++ b/docs/layouts/_shortcodes/syntax-highlighting-styles.html @@@ -1,70 -1,0 +1,70 @@@ +{{- /* +Renders a gallery a Chroma syntax highlighting styles. + +@example {{% syntax-highlighting-styles %}} +*/ -}} +{{- $examples := slice }} + +{{- /* Example: css */}} +{{- $example := dict "lang" "css" "code" ` +body { + font-size: 16px; /* comment */ +} +`}} +{{- $examples = $examples | append $example }} + +{{- /* Example: html */}} +{{- $example = dict "lang" "html" "code" ` +Example +`}} +{{- $examples = $examples | append $example }} + +{{- /* Example: go-html-template */}} +{{- $example = dict "lang" "go-html-template" "code" ` +{{ with $.Page.Params.content }} + {{ . | $.Page.RenderString }} {{/* comment */}} +{{ end }} +`}} +{{- $examples = $examples | append $example }} + +{{- /* Example: javascript */}} +{{- $example = dict "lang" "javascript" "code" ` +if ([1,"one",2,"two"].includes(value)){ + console.log("Number is either 1 or 2."); // comment +} +`}} +{{- $examples := $examples | append $example }} + +{{- /* Example: markdown */}} +{{- $example = dict "lang" "markdown" "code" ` +{{< figure src="kitten.jpg" >}} +[example](https://example.org "An example") +`}} +{{- $examples := $examples | append $example }} + +{{- /* Example: toml */}} +{{- $example = dict "lang" "toml" "code" ` +[params] +bool = true # comment +string = 'foo' +`}} +{{- $examples := $examples | append $example }} + +{{- /* Render */}} - {{- with site.Data.docs.chroma.styles }} ++{{- with hugo.Data.docs.chroma.styles }} + {{- range $style := . }} + +### {{ $style }} {class="!mt-7 !mb-6"}{{/* Do not indent. */}} + + {{- range $examples }} + +{{ .lang }}{{/* Do not indent. */}} +{class="text-sm !-mt-3 !-mb-5"}{{/* Do not indent. */}} + +```{{ .lang }} {noClasses=true style="{{ $style }}"}{{/* Do not indent. */}} +{{- .code | safeHTML -}}{{/* Do not indent. */}} +```{{/* Do not indent. */}} + + {{- end }} + {{- end }} +{{- end }} diff --cc docs/netlify.toml index 290bbd32d,000000000..c49f06d41 mode 100644,000000..100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@@ -1,55 -1,0 +1,55 @@@ +[build] + publish = "public" + command = "npm ls && hugo --gc --minify" + + [build.environment] - HUGO_VERSION = "0.155.3" ++ HUGO_VERSION = "0.156.0" + +[context.production.environment] + HUGO_ENV = "production" + HUGO_ENABLEGITINFO = "true" + +[context.split1] + command = "npm ls && hugo --gc --minify --enableGitInfo" + + [context.split1.environment] + HUGO_ENV = "production" + +[context.deploy-preview] + command = "npm ls && hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL --enableGitInfo" + +[context.branch-deploy] + command = "npm ls && hugo --gc --minify -b $DEPLOY_PRIME_URL" + +[context.next.environment] + HUGO_ENABLEGITINFO = "true" + +[[headers]] + for = "/*.jpg" + + [headers.values] + Cache-Control = "public, max-age=31536000" + +[[headers]] + for = "/*.png" + + [headers.values] + Cache-Control = "public, max-age=31536000" + +[[headers]] + for = "/*.css" + + [headers.values] + Cache-Control = "public, max-age=31536000" + +[[headers]] + for = "/*.js" + + [headers.values] + Cache-Control = "public, max-age=31536000" + +[[headers]] + for = "/*.ttf" + + [headers.values] + Cache-Control = "public, max-age=31536000"