From: Bjørn Erik Pedersen Date: Fri, 19 Dec 2025 09:07:30 +0000 (+0100) Subject: Merge commit '08e1ea5c709d3d49bdc3ce3c21e8fa05a33150d0' X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=70ce2446b593a67f8871ce78cf250a95062af9e0;p=brevno-suite%2Fhugo Merge commit '08e1ea5c709d3d49bdc3ce3c21e8fa05a33150d0' --- 70ce2446b593a67f8871ce78cf250a95062af9e0 diff --cc docs/.cspell.json index 28dba57be,000000000..c41b857fd mode 100644,000000..100644 --- a/docs/.cspell.json +++ b/docs/.cspell.json @@@ -1,197 -1,0 +1,200 @@@ +{ + "version": "0.2", + "allowCompoundWords": true, + "overrides": [ + { + "filename": "**/*", + "enabled": false + }, + { + "filename": "**/*.md", + "enabled": true + } + ], + "flagWords": [ + "alot", + "hte", + "langauge", + "reccommend", + "seperate", + "teh" + ], + "ignorePaths": [ + "**/emojis.md", + "**/commands/*", + "**/showcase/*", - "**/tools/*" ++ "**/tools/*", ++ "data/docs.yaml" + ], + "ignoreRegExpList": [ + "# cspell: ignore fenced code blocks", + "^(\\s*`{3,}).*[\\s\\S]*?^\\1$", + "# cspell: ignore words joined with dot", + "\\w+\\.\\w+", + "# cspell: ignore strings within backticks", + "`.+`", + "# cspell: ignore strings within double quotes", + "\".+\"", + "# cspell: ignore strings within brackets", + "\\[.+\\]", + "# cspell: ignore strings within parentheses", + "\\(.+\\)", + "# cspell: ignore words that begin with a slash", + "/\\w+", + "# cspell: ignore everything within action delimiters", + "\\{\\{.+\\}\\}", + "# cspell: ignore everything after a right arrow", + "\\s+→\\s+.+" + ], + "language": "en", + "words": [ + "composability", + "configurators", + "defang", + "deindent", + "downscale", + "downscaling", + "exif", + "geolocalized", + "grayscale", + "marshal", + "marshaling", + "multihost", - "multiplatfom", ++ "multiplatform", + "performantly", + "preconfigured", + "prerendering", + "redirection", + "redirections", ++ "slugified", ++ "slugify", + "subexpression", + "suppressible", + "synchronisation", + "templating", + "transpile", + "unmarshal", + "unmarshaled", + "unmarshaling", + "unmarshals", + "# ----------------------------------------------------------------------", + "# cspell: ignore hugo terminology", + "# ----------------------------------------------------------------------", + "alignx", + "aligny", + "attrlink", + "canonify", + "codeowners", + "dynacache", + "eturl", + "getenv", + "gohugo", + "gohugoio", + "keyvals", + "leftdelim", + "linkify", + "numworkermultiplier", + "rightdelim", + "shortcode", + "stringifier", + "struct", + "toclevels", + "unmarshal", + "unpublishdate", + "zgotmplz", + "# ----------------------------------------------------------------------", + "# cspell: ignore foreign language words", + "# ----------------------------------------------------------------------", + "bezpieczeństwo", + "blatt", + "buch", + "descripción", + "dokumentation", + "erklärungen", + "español", + "français", + "libros", + "mercredi", + "miesiąc", - "miesiąc", + "miesiąca", + "miesiące", + "miesięcy", + "misérables", + "mittwoch", + "muchos", + "novembre", + "otro", + "pocos", + "produkte", + "projekt", + "prywatność", + "referenz", + "régime", + "# ----------------------------------------------------------------------", + "# cspell: ignore names", + "# ----------------------------------------------------------------------", + "Atishay", + "Cosette", + "Eliott", + "Furet", + "Gregor", + "Jaco", + "Lanczos", + "Ninke", + "Noll", + "Pastorius", + "Samsa", + "Stucki", + "Thénardier", ++ "Vitter", + "WASI", + "# ----------------------------------------------------------------------", + "# cspell: ignore operating systems and software packages", + "# ----------------------------------------------------------------------", + "asciidoctor", + "brotli", + "cifs", + "corejs", + "disqus", + "docutils", + "dpkg", + "doas", + "eopkg", + "forgejo", + "gitee", + "goldmark", + "katex", + "kubuntu", + "lubuntu", + "mathjax", + "nosql", + "pandoc", + "pkgin", + "rclone", + "xubuntu", + "# ----------------------------------------------------------------------", + "# cspell: ignore miscellaneous", + "# ----------------------------------------------------------------------", + "achristie", + "ccpa", + "cpra", + "ddmaurier", + "dring", + "fleqn", + "inor", + "jausten", + "jdoe", + "jsmith", + "leqno", + "milli", + "monokai", + "mysanityprojectid", + "rgba", + "rsmith", + "tdewolff", + "tjones", + "vcard", + "wcag", + "xfeff" + ] +} diff --cc docs/.markdownlint-cli2.yaml index 1ededafd0,000000000..c8f5b7bd3 mode 100644,000000..100644 --- a/docs/.markdownlint-cli2.yaml +++ b/docs/.markdownlint-cli2.yaml @@@ -1,91 -1,0 +1,91 @@@ +# Glob patterns to include +globs: + - "content/**/*.md" + +# Glob patterns to exclude +ignores: + - "content/**/commands/**" + - "content/en/about/license.md" + - "content/LICENSE.md" + +# Markdownlint rules and configuration +# https://github.com/DavidAnson/markdownlint?tab=readme-ov-file#rules--aliases +config: + MD001: true + # MD002 deprecated + MD003: + style: atx + MD004: + style: dash + MD005: true + # MD006 deprecated + MD007: false # if enabled, throws errors when definition descriptions contain list items + # MD008 deprecated + MD009: true + MD010: true + MD011: true + MD012: true + MD013: false + MD014: true + # MD015 deprecated + # MD016 deprecated + # MD017 deprecated + MD018: true + MD019: true + MD020: true + MD021: true + MD022: true + MD023: true + MD024: true + MD025: true + MD026: true + MD027: true + MD028: false + MD029: + style: one + MD030: true + MD031: true + MD032: true + MD033: true + MD034: false + MD035: + style: --- + MD036: true + MD037: true + MD038: true + MD039: true + MD040: true + MD041: false + MD042: true + MD043: false + MD044: false + MD045: true + MD046: false + MD047: true + MD048: + style: backtick + MD049: + style: underscore + MD050: + style: asterisk + MD051: false + MD052: true + MD053: true + MD054: + autolink: true + collapsed: true + full: true + inline: true + shortcut: true - url_inline: true ++ url_inline: false + MD055: + style: consistent + MD056: true + # MD057 deprecated + MD058: true + MD059: + prohibited_texts: + - click here + - here + - link + - more diff --cc docs/assets/css/styles.css index 6665a7e2b,000000000..05304a93b mode 100644,000000..100644 --- a/docs/assets/css/styles.css +++ b/docs/assets/css/styles.css @@@ -1,131 -1,0 +1,136 @@@ +@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", ui-sans-serif, system-ui, 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) { + .px-main { + padding-left: max(env(safe-area-inset-left), 2rem); + padding-right: max(env(safe-area-inset-right), 2rem); + } +} + +@media screen(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; ++} diff --cc docs/assets/images/sponsors/cloudcannon-cms-logo.svg index 000000000,000000000..9860c5999 new file mode 100644 --- /dev/null +++ b/docs/assets/images/sponsors/cloudcannon-cms-logo.svg @@@ -1,0 -1,0 +1,13 @@@ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ diff --cc docs/assets/js/head-early.js index 250bdd6cb,000000000..b21eb58a2 mode 100644,000000..100644 --- a/docs/assets/js/head-early.js +++ b/docs/assets/js/head-early.js @@@ -1,16 -1,0 +1,20 @@@ +import { scrollToActive } from 'js/helpers/index'; ++import { initColorScheme } from './alpinejs/stores/index'; + +(function () { ++ // This allows us to initialize the color scheme before AlpineJS etc. is loaded. ++ initColorScheme(); ++ + // Now we know that the browser has JS enabled. + document.documentElement.classList.remove('no-js'); + + // Add os-macos class to body if user is using macOS. + if (navigator.userAgent.indexOf('Mac') > -1) { + document.documentElement.classList.add('os-macos'); + } + + // Wait for the DOM to be ready. + document.addEventListener('DOMContentLoaded', function () { + scrollToActive('DOMContentLoaded'); + }); +})(); diff --cc docs/assets/js/main.js index 14440044b,000000000..c12be19fa mode 100644,000000..100644 --- a/docs/assets/js/main.js +++ b/docs/assets/js/main.js @@@ -1,89 -1,0 +1,81 @@@ +import Alpine from 'alpinejs'; +import { registerMagics } from './alpinejs/magics/index'; +import { navbar, search, toc } from './alpinejs/data/index'; +import { navStore, initColorScheme } from './alpinejs/stores/index'; +import { bridgeTurboAndAlpine } from './helpers/index'; +import persist from '@alpinejs/persist'; +import focus from '@alpinejs/focus'; + +var debug = 0 ? console.log.bind(console, '[index]') : function () {}; + - // Turbolinks init. - (function () { - document.addEventListener('turbo:render', function (e) { - // This is also called right after the body start. This is added to prevent flicker on navigation. - initColorScheme(); - }); - })(); - +// Set up and start Alpine. +(function () { + // Register AlpineJS plugins. + { + Alpine.plugin(focus); + Alpine.plugin(persist); + } + // Register AlpineJS magics and directives. + { + // Handles copy to clipboard etc. + registerMagics(Alpine); + } + + // Register AlpineJS controllers. + { + // Register AlpineJS data controllers. + let searchConfig = { + index: 'hugodocs', + app_id: 'D1BPLZHGYQ', + api_key: '6df94e1e5d55d258c56f60d974d10314', + }; + + Alpine.data('navbar', () => navbar(Alpine)); + Alpine.data('search', () => search(Alpine, searchConfig)); + Alpine.data('toc', () => toc(Alpine)); + } + + // Register AlpineJS stores. + { + Alpine.store('nav', navStore(Alpine)); + } + + // Start AlpineJS. + Alpine.start(); + + // Start the Turbo-Alpine bridge. + bridgeTurboAndAlpine(Alpine); + + { + let containerScrollTops = {}; + + // To preserve scroll position in scrolling elements on navigation add data-turbo-preserve-scroll-container="somename" to the scrolling container. + addEventListener('turbo:click', () => { + document.querySelectorAll('[data-turbo-preserve-scroll-container]').forEach((el2) => { + containerScrollTops[el2.dataset.turboPreserveScrollContainer] = el2.scrollTop; + }); + }); + + addEventListener('turbo:render', () => { + document.querySelectorAll('[data-turbo-preserve-scroll-container]').forEach((ele) => { + const containerScrollTop = containerScrollTops[ele.dataset.turboPreserveScrollContainer]; + if (containerScrollTop) { + ele.scrollTop = containerScrollTop; + } else { + let els = ele.querySelectorAll('.scroll-active'); + if (els.length) { + els.forEach((el) => { + // Avoid scrolling if el is already in view. + if (el.offsetTop >= ele.scrollTop && el.offsetTop <= ele.scrollTop + ele.clientHeight) { + return; + } + ele.scrollTop = el.offsetTop - ele.offsetTop; + }); + } + } + }); + + containerScrollTops = {}; + }); + } +})(); diff --cc docs/content/en/_common/installation/02-prerequisites.md index f27d9d56b,000000000..2a0b1ac09 mode 100644,000000..100644 --- a/docs/content/en/_common/installation/02-prerequisites.md +++ b/docs/content/en/_common/installation/02-prerequisites.md @@@ -1,40 -1,0 +1,42 @@@ +--- +_comment: Do not remove front matter. +--- + +## Prerequisites + +Although not required in all cases, [Git], [Go], and [Dart Sass] are commonly used when working with Hugo. + +Git is required to: + +- Build Hugo from source +- Use the [Hugo Modules] feature +- Install a theme as a Git submodule +- Access [commit information] from a local Git repository +- Host your site with services such as [CloudCannon], [Cloudflare Pages], [GitHub Pages], [GitLab Pages], and [Netlify] + +Go is required to: + +- Build Hugo from source +- Use the Hugo Modules feature + +Dart Sass is required to transpile Sass to CSS when using the latest features of the Sass language. + +Please refer to the relevant documentation for installation instructions: + +- [Git][git install] +- [Go][go install] +- [Dart Sass][dart sass install] + +[cloudcannon]: https://cloudcannon.com/ +[cloudflare pages]: https://pages.cloudflare.com/ ++[commit information]: /methods/page/GitInfo +[dart sass install]: /functions/css/sass/#dart-sass +[dart sass]: https://sass-lang.com/dart-sass +[git install]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[git]: https://git-scm.com/ +[github pages]: https://pages.github.com/ +[gitlab pages]: https://docs.gitlab.com/ee/user/project/pages/ +[go install]: https://go.dev/doc/install +[go]: https://go.dev/ ++[hugo modules]: /hugo-modules/ +[netlify]: https://www.netlify.com/ diff --cc docs/content/en/_common/installation/03-prebuilt-binaries.md index c72a68bee,000000000..aa8268fcd mode 100644,000000..100644 --- a/docs/content/en/_common/installation/03-prebuilt-binaries.md +++ b/docs/content/en/_common/installation/03-prebuilt-binaries.md @@@ -1,17 -1,0 +1,19 @@@ +--- +_comment: Do not remove front matter. +--- + +## Prebuilt binaries + +Prebuilt binaries are available for a variety of operating systems and architectures. Visit the [latest release] page, and scroll down to the Assets section. + +1. Download the archive for the desired edition, operating system, and architecture +1. Extract the archive +1. Move the executable to the desired directory +1. Add this directory to the PATH environment variable +1. Verify that you have _execute_ permission on the file + +Please consult your operating system documentation if you need help setting file permissions or modifying your PATH environment variable. + +If you do not see a prebuilt binary for the desired edition, operating system, and architecture, install Hugo using one of the methods described below. ++ ++[latest release]: https://github.com/gohugoio/hugo/releases/latest diff --cc docs/content/en/_common/installation/04-build-from-source.md index 3ce245f4a,000000000..fb2588d8a mode 100644,000000..100644 --- a/docs/content/en/_common/installation/04-build-from-source.md +++ b/docs/content/en/_common/installation/04-build-from-source.md @@@ -1,38 -1,0 +1,38 @@@ +--- +_comment: Do not remove front matter. +--- + +## Build from source + +To build the extended or extended/deploy edition from source you must: + +1. Install [Git] - 1. Install [Go] version 1.23.0 or later ++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] + +> The install directory is controlled by the `GOPATH` and `GOBIN` environment variables. If `GOBIN` is set, binaries are installed to that directory. If `GOPATH` is set, binaries are installed to the bin subdirectory of the first directory in the `GOPATH` list. Otherwise, binaries are installed to the bin subdirectory of the default `GOPATH` (`$HOME/go` or `%USERPROFILE%\go`). + +To build the standard edition: + +```sh +go install github.com/gohugoio/hugo@latest +``` + +To build the extended edition: + +```sh +CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@latest +``` + +To build the extended/deploy edition: + +```sh +CGO_ENABLED=1 go install -tags extended,withdeploy github.com/gohugoio/hugo@latest +``` + +[Clang]: https://clang.llvm.org/ +[GCC]: https://gcc.gnu.org/ +[Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[Go documentation]: https://go.dev/doc/code#Command +[Go]: https://go.dev/doc/install diff --cc docs/content/en/_common/installation/homebrew.md index 14f48174e,000000000..bc7902c00 mode 100644,000000..100644 --- a/docs/content/en/_common/installation/homebrew.md +++ b/docs/content/en/_common/installation/homebrew.md @@@ -1,13 -1,0 +1,13 @@@ +--- +_comment: Do not remove front matter. +--- + +### Homebrew + - [Homebrew] is a free and open-source package manager for macOS and Linux. To install the extended edition of Hugo: ++[Homebrew] is a free and open-source package manager for macOS and Linux. To install the extended/deploy edition of Hugo: + +```sh +brew install hugo +``` + +[Homebrew]: https://brew.sh/ diff --cc docs/content/en/_common/permalink-tokens.md index 62b4b0d0c,000000000..aac412576 mode 100644,000000..100644 --- a/docs/content/en/_common/permalink-tokens.md +++ b/docs/content/en/_common/permalink-tokens.md @@@ -1,75 -1,0 +1,77 @@@ +--- +_comment: Do not remove front matter. +--- + +`:year` +: The 4-digit year as defined in the front matter `date` field. + +`:month` +: The 2-digit month as defined in the front matter `date` field. + +`:monthname` +: The name of the month as defined in the front matter `date` field. + +`:day` +: The 2-digit day as defined in the front matter `date` field. + +`:weekday` +: The 1-digit day of the week as defined in the front matter `date` field (Sunday = `0`). + +`:weekdayname` +: The name of the day of the week as defined in the front matter `date` field. + +`:yearday` +: The 1- to 3-digit day of the year as defined in the front matter `date` field. + +`:section` +: The content's section. + +`:sectionslug` ++: {{< new-in 0.149.0 />}} +: The content's section using slugified section name. The slugified section name is the `slug` as defined in front matter, else the `title` as defined in front matter, else the automatic title. + +`:sections` +: The content's sections hierarchy. You can use a selection of the sections using _slice syntax_: `:sections[1:]` includes all but the first, `:sections[:last]` includes all but the last, `:sections[last]` includes only the last, `:sections[1:2]` includes section 2 and 3. Note that this slice access will not throw any out-of-bounds errors, so you don't have to be exact. + +`:sectionslugs` ++: {{< new-in 0.149.0 />}} +: The content's sections hierarchy using slugified section names. The slugified section name is the `slug` as defined in front matter, else the `title` as defined in front matter, else the automatic title. You can use a selection of the sections using _slice syntax_: `:sectionslugs[1:]` includes all but the first, `:sectionslugs[:last]` includes all but the last, `:sectionslugs[last]` includes only the last, `:sectionslugs[1:2]` includes section 2 and 3. Note that this slice access will not throw any out-of-bounds errors, so you don't have to be exact. + +`:title` +: The `title` as defined in front matter, else the automatic title. Hugo generates titles automatically for section, taxonomy, and term pages that are not backed by a file. + +`:slug` +: The `slug` as defined in front matter, else the `title` as defined in front matter, else the automatic title. Hugo generates titles automatically for section, taxonomy, and term pages that are not backed by a file. + +`:filename` +: The content's file name without extension, applicable to the `page` page kind. + + {{< deprecated-in v0.144.0 >}} + The `:filename` token has been deprecated. Use `:contentbasename` instead. + {{< /deprecated-in >}} + +`:slugorfilename` +: The `slug` as defined in front matter, else the content's file name without extension, applicable to the `page` page kind. + + {{< deprecated-in v0.144.0 >}} + The `:slugorfilename` token has been deprecated. Use `:slugorcontentbasename` instead. + {{< /deprecated-in >}} + +`:contentbasename` +: {{< new-in 0.144.0 />}} +: The [content base name]. + +[content base name]: /methods/page/file/#contentbasename + +`:slugorcontentbasename` +: {{< new-in 0.144.0 />}} +: The `slug` as defined in front matter, else the [content base name]. + +For time-related values, you can also use the layout string components defined in Go's [time package]. For example: + +[time package]: https://pkg.go.dev/time#pkg-constants + +{{< code-toggle file=hugo >}} +permalinks: + posts: /:06/:1/:2/:title/ +{{< /code-toggle >}} diff --cc docs/content/en/_common/render-hooks/pageinner.md index 3efbc9ce3,000000000..2068b28db mode 100644,000000..100644 --- a/docs/content/en/_common/render-hooks/pageinner.md +++ b/docs/content/en/_common/render-hooks/pageinner.md @@@ -1,47 -1,0 +1,47 @@@ +--- +_comment: Do not remove front matter. +--- + +## PageInner details + +{{< new-in 0.125.0 />}} + +The primary use case for `PageInner` is to resolve links and [page resources](g) relative to an included `Page`. For example, create an "include" shortcode to compose a page from multiple content files, while preserving a global context for footnotes and the table of contents: + +```go-html-template {file="layouts/_shortcodes/include.html" copy=true} +{{ with .Get 0 }} + {{ with $.Page.GetPage . }} + {{- .RenderShortcodes }} + {{ else }} + {{ errorf "The %q shortcode was unable to find %q. See %s" $.Name . $.Position }} + {{ end }} +{{ else }} + {{ errorf "The %q shortcode requires a positional parameter indicating the logical path of the file to include. See %s" .Name .Position }} +{{ end }} +``` + +Then call the shortcode in your Markdown: + +```text {file="content/posts/post-1.md"} +{{%/* include "/posts/post-2" */%}} +``` + +Any render hook triggered while rendering `/posts/post-2` will get: + +- `/posts/post-1` when calling `Page` +- `/posts/post-2` when calling `PageInner` + +`PageInner` falls back to the value of `Page` if not relevant, and always returns a value. + +> [!note] +> The `PageInner` method is only relevant for shortcodes that invoke the [`RenderShortcodes`] method, and you must call the shortcode using [Markdown notation]. + +As a practical example, Hugo's embedded link and image render hooks use the `PageInner` method to resolve markdown link and image destinations. See the source code for each: + +- [Embedded link render hook] +- [Embedded image render hook] + +[`RenderShortcodes`]: /methods/page/rendershortcodes/ +[Markdown notation]: /content-management/shortcodes/#notation - [Embedded link render hook]: {{% eturl render-link %}} - [Embedded image render hook]: {{% eturl render-image %}} ++[Embedded link render hook]: <{{% eturl render-link %}}> ++[Embedded image render hook]: <{{% eturl render-image %}}> diff --cc docs/content/en/about/introduction.md index 9586d08f8,000000000..3d56b9570 mode 100644,000000..100644 --- a/docs/content/en/about/introduction.md +++ b/docs/content/en/about/introduction.md @@@ -1,34 -1,0 +1,34 @@@ +--- +title: Introduction +description: Hugo is a static site generator written in Go, optimized for speed and designed for flexibility. +categories: [] +keywords: [] +weight: 10 +aliases: [/about/what-is-hugo/,/about/benefits/] +--- + +Hugo is a [static site generator] written in [Go], optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less. + +Due to its flexible framework, multilingual support, and powerful taxonomy system, Hugo is widely used to create: + +- Corporate, government, nonprofit, education, news, event, and project sites +- Documentation sites +- Image portfolios +- Landing pages +- Business, professional, and personal blogs +- Resumes and CVs + +Use Hugo's embedded web server during development to instantly see changes to content, structure, behavior, and presentation. Then deploy the site to your host, or push changes to your Git provider for automated builds and deployment. + +And with [Hugo Modules], you can share content, assets, data, translations, themes, templates, and configuration with other projects via public or private Git repositories. + +Learn more about Hugo's [features], [privacy protections], and [security model]. + +[Go]: https://go.dev +[Hugo Modules]: /hugo-modules/ +[static site generator]: https://en.wikipedia.org/wiki/Static_site_generator +[features]: /about/features/ - [security model]: about/security/ ++[security model]: /about/security/ +[privacy protections]: /configuration/privacy + +{{< youtube 0RKpf3rK57I >}} diff --cc docs/content/en/commands/hugo_gen_chromastyles.md index 2863e46b4,000000000..78cc62f88 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_gen_chromastyles.md +++ b/docs/content/en/commands/hugo_gen_chromastyles.md @@@ -1,50 -1,0 +1,52 @@@ +--- +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_new.md index 2788ef168,000000000..56ab4aef9 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,50 @@@ +--- +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. + +Ensure you run this within the root directory of your site. + +### 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 new content](/commands/hugo_new_content/) - Create new content - * [hugo new site](/commands/hugo_new_site/) - Create a new site (skeleton) - * [hugo new theme](/commands/hugo_new_theme/) - Create a new theme (skeleton) ++* [hugo new site](/commands/hugo_new_site/) - Create a new site ++* [hugo new theme](/commands/hugo_new_theme/) - Create a new theme + diff --cc docs/content/en/commands/hugo_new_site.md index 0f0096ae4,000000000..ccf74bc6f mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_new_site.md +++ b/docs/content/en/commands/hugo_new_site.md @@@ -1,48 -1,0 +1,46 @@@ +--- +title: "hugo new site" +slug: hugo_new_site +url: /commands/hugo_new_site/ +--- +## hugo new site + - Create a new site (skeleton) ++Create a new site + +### Synopsis + - Create a new site in the provided directory. - The new site will have the correct structure, but no content or theme yet. - Use `hugo new [contentPath]` to create new content. ++Create a new site at the specified path. + +``` +hugo new site [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 site +``` + +### 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 b1c937bae,000000000..140660077 mode 100644,000000..100644 --- a/docs/content/en/commands/hugo_new_theme.md +++ b/docs/content/en/commands/hugo_new_theme.md @@@ -1,47 -1,0 +1,46 @@@ +--- +title: "hugo new theme" +slug: hugo_new_theme +url: /commands/hugo_new_theme/ +--- +## hugo new theme + - Create a new theme (skeleton) ++Create a new theme + +### Synopsis + - Create a new theme (skeleton) called [name] in ./themes. - New theme is a skeleton. Please add content to the touched files. Add your - name to the copyright line in the license and adjust the theme.toml file - according to your needs. ++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 + +``` - -h, --help help for theme ++ --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/configuration/all.md index c733e0a99,000000000..2d6178e5b mode 100644,000000..100644 --- a/docs/content/en/configuration/all.md +++ b/docs/content/en/configuration/all.md @@@ -1,361 -1,0 +1,361 @@@ +--- +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](/configuration/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](/configuration/caches/). + +canonifyURLs +: (`bool`) See [details](/content-management/urls/#canonical-urls) before enabling this feature. Default is `false`. + +capitalizeListTitles +: {{< new-in 0.123.3 />}} +: (`bool`) Whether to capitalize automatic list titles. Applicable to section, taxonomy, and term pages. Default is `true`. Use the [`titleCaseStyle`](#titlecasestyle) setting to configure capitalization rules. + +cascade +: See [configure cascade](/configuration/cascade/). + +cleanDestinationDir - : (`bool`) Whether to remove files from the site's destination directory that do not have corresponding files in the `static` directory during the build. Default is `false`. ++: (`bool`) Whether to remove files from the [`publishDir`](#publishdir) that do not exist in the [`staticDir`](#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 project's default language key, 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 language site to a subdirectory matching the `defaultContentLanguage`. 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](/configuration/deployment/). + +disableAliases +: (`bool`) Whether to disable generation of alias redirects. Even if this option is enabled, the defined aliases will still be present on the page. This allows you to manage redirects separately, for example, by generating 301 redirects in an `.htaccess` file or a Netlify `_redirects` file using a custom output format. Default is `false`. + +disableDefaultLanguageRedirect +: {{< new-in 0.140.0 />}} +: (`bool`) Whether to disable generation of the alias redirect to the default language when `DefaultContentLanguageInSubdir` is `true`. 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. + +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`. + +frontmatter +: See [configure front matter](/configuration/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](/configuration/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](g) pattern matching the module paths to exclude from the `_vendor` directory. + +imaging +: See [configure imaging](/configuration/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](/configuration/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](/configuration/markup/). + +mediaTypes +: See [configure media types](/configuration/media-types/). + +menus +: See [configure menus](/configuration/menus/). + +minify +: See [configure minify](/configuration/minify/). + +module +: See [configure modules](/configuration/module/). + +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](/configuration/output-formats/). + +outputs +: See [configure outputs](/configuration/outputs/). + +page +: See [configure page](/configuration/page/). + +pagination +: See [configure pagination](/configuration/pagination/). + +panicOnWarning +: (`bool`) Whether to panic on the first WARNING. Default is `false`. + +params +: See [configure params](/configuration/params/). + +permalinks +: See [configure permalinks](/configuration/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](/configuration/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](/configuration/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](https://www.compart.com/en/unicode/category/Mn) from [composite characters](https://en.wikipedia.org/wiki/Precomposed_character) in content paths. Default is `false`. + +renderSegments +: {{< new-in 0.124.0 />}} +: (`[]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. + +resourceDir +: (`string`) The designated directory for caching output from [asset pipelines](g). Default is `resources`. + +security +: See [configure security](/configuration/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](/configuration/segments/). + +server +: See [configure server](/configuration/server/). + +services +: See [configure services](/configuration/services/). + +sitemap +: See [configure sitemap](/configuration/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. ++: (`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](/configuration/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](/configuration/ugly-urls/). + +## 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) vendors, please read their documentation. For an 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](/configuration/languages/#localized-settings). + +[`cacheDir`]: #cachedir +[`disabled`]: /configuration/languages/#disabled +[`erroridf`]: /functions/fmt/erroridf/ +[`FuzzyWordCount`]: /methods/page/fuzzywordcount/ +[`GitInfo`]: /methods/page/gitinfo/ +[`MainSections`]: /methods/site/mainsections/ +[`segments`]: /configuration/segments/ +[`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/ +[Associated Press Stylebook]: https://www.apstylebook.com/ +[automatic summaries]: /content-management/summaries/#automatic-summary +[Chicago Manual of Style]: https://www.chicagomanualofstyle.org/home.html +[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 %}} ++[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 +[module mounts]: /configuration/module/#mounts +[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/cascade.md index 85b221df2,000000000..9a1fda4c6 mode 100644,000000..100644 --- a/docs/content/en/configuration/cascade.md +++ b/docs/content/en/configuration/cascade.md @@@ -1,77 -1,0 +1,76 @@@ +--- +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 >}} - title = 'Home' +[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](g) pattern matching the build [environment](g). For example: `{staging,production}`. + +kind +: (`string`) A [glob](g) pattern matching the [page kind](g). For example: `{taxonomy,term}`. + +lang +: (`string`) A [glob](g) pattern matching the [page language]. For example: `{en,de}`. + +path +: (`string`) A [glob](g) pattern 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/**}' ++path = '/books/**' +kind = 'page' +lang = '{en,de}' +[[cascade]] +[cascade.params] +color = 'blue' +[cascade.target] - path = '{/films/**}' ++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 a97648b61,000000000..edffd302d mode 100644,000000..100644 --- a/docs/content/en/configuration/front-matter.md +++ b/docs/content/en/configuration/front-matter.md @@@ -1,102 -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. + + 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. + +## Example + +Consider this site configuration: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = [':filename', ':default'] ++publishDate = [':filename', ':default'] +lastmod = ['lastmod', ':fileModTime'] +{{< /code-toggle >}} + - To determine `date`, Hugo tries to extract the date from the file name, falling back to the default ordered sequence of date fields. ++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/http-cache.md index 788d22a08,000000000..c48c9cbcd mode 100644,000000..100644 --- a/docs/content/en/configuration/http-cache.md +++ b/docs/content/en/configuration/http-cache.md @@@ -1,107 -1,0 +1,129 @@@ +--- +title: Configure the HTTP cache +linkTitle: HTTP cache +description: Configure the HTTP cache. +categories: [] +keywords: [] +--- + +> [!note] +> This configuration is only relevant when using the [`resources.GetRemote`] function. + +## Layered caching + +Hugo employs a layered caching system. + +```goat {.w-40} + .-----------. +| dynacache | + '-----+-----' + | + v + .----------. +| HTTP cache | + '-----+----' + | + v + .----------. +| file cache | + '-----+----' +``` + +Dynacache +: An in-memory cache employing a Least Recently Used (LRU) eviction policy. Entries are removed from the cache when changes occur, when they match [cache-busting] patterns, or under low-memory conditions. + +HTTP Cache +: An HTTP cache for remote resources as specified in [RFC 9111]. Optimal performance is achieved when resources include appropriate HTTP cache headers. The HTTP cache utilizes the file cache for storage and retrieval of cached resources. + +File cache +: See [configure file caches]. + +The HTTP cache involves two key aspects: determining which content to cache (the caching process itself) and defining the frequency with which to check for updates (the polling strategy). + +## HTTP caching + +The HTTP cache behavior is defined for a configured set of resources. Stale resources will be refreshed from the file cache, even if their configured Time-To-Live (TTL) has not expired. If HTTP caching is disabled for a resource, Hugo will bypass the cache and access the file directly. + - The default configuration disables everything: ++This is the default configuration for HTTP caching: + - {{< code-toggle file=hugo >}} - [HTTPCache.cache.for] - excludes = ['**'] - includes = [] - {{< /code-toggle >}} ++{{< code-toggle config=HTTPCache />}} ++ ++respectCacheControlNoStoreInRequest ++: {{< new-in 0.151.0 />}} ++: (`bool`) Whether to respect the `no-store` directive in the server's `Cache-Control` request header when fetching remote resources via the [`resources.GetRemote`][] function. Default is `true`. ++ ++respectCacheControlNoStoreInResponse ++: {{< new-in 0.151.0 />}} ++: (`bool`) Whether to respect the `no-store` directive in the server's `Cache-Control` response header when fetching remote resources via the [`resources.GetRemote`][] function. Default is `false`. + +cache.for.excludes - : (`string`) A list of [glob](g) patterns to exclude from caching. ++: (`string`) A list of [glob](g) patterns to exclude from caching. In its default configuration HTTP caching excludes all files. + +cache.for.includes +: (`string`) A list of [glob](g) patterns to cache. + ++polls ++: A slice of polling configurations. ++ ++polls.disable ++: (`bool`) Whether to disable polling for this configuration. Default is `true`. ++ ++polls.high ++: (`string`) The maximum polling interval expressed as a [duration](g). This is used when the resource is considered stable. Default is `0s`. ++ ++polls.low ++: (`string`) The minimum polling interval expressed as a [duration](g). This is used after a recent change and gradually increases towards `polls.high`. Default is `0s`. ++ ++polls.for.excludes ++: (`string`) A list of [glob](g) patterns to exclude from polling for this configuration. ++ ++polls.for.includes ++: (`string`) A list of [glob](g) patterns to include in polling for this configuration. ++ +## HTTP polling + +Polling is used in watch mode (e.g., `hugo server`) to detect changes in remote resources. Polling can be enabled even if HTTP caching is disabled. Detected changes trigger a rebuild of pages using the affected resource. Polling can be disabled for specific resources, typically those known to be static. + +The default configuration disables everything: + +{{< code-toggle file=hugo >}} +[[HTTPCache.polls]] +disable = true +high = '0s' +low = '0s' +[HTTPCache.polls.for] +includes = ['**'] +excludes = [] +{{< /code-toggle >}} + +polls +: A slice of polling configurations. + +polls.disable - : (`bool`) Whether to disable polling for this configuration. - - polls.low - : (`string`) The minimum polling interval expressed as a [duration](g). This is used after a recent change and gradually increases towards `polls.high`. ++: (`bool`) Whether to disable polling for this configuration. Default is `true`. + +polls.high - : (`string`) The maximum polling interval expressed as a [duration](g). This is used when the resource is considered stable. ++: (`string`) The maximum polling interval expressed as a [duration](g). This is used when the resource is considered stable. Default is `0s`. ++ ++polls.low ++: (`string`) The minimum polling interval expressed as a [duration](g). This is used after a recent change and gradually increases towards `polls.high`. Default is `0s`. + +polls.for.excludes +: (`string`) A list of [glob](g) patterns to exclude from polling for this configuration. + +polls.for.includes +: (`string`) A list of [glob](g) patterns to include in polling for this configuration. + +## Behavior + +Polling and HTTP caching interact as follows: + +- With polling enabled, rebuilds are triggered only by actual changes, detected via `eTag` changes (Hugo generates an MD5 hash if the server doesn't provide one). +- If polling is enabled but HTTP caching is disabled, the remote is checked for changes only after the file cache's TTL expires (e.g., a `maxAge` of `10h` with a `1s` polling interval is inefficient). +- If both polling and HTTP caching are enabled, changes are checked for even before the file cache's TTL expires. Cached `eTag` and `last-modified` values are sent in `if-none-match` and `if-modified-since` headers, respectively, and a cached response is returned on HTTP [304]. + +[`resources.GetRemote`]: /functions/resources/getremote/ +[304]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304 +[cache-busting]: /configuration/build/#cache-busters +[configure file caches]: /configuration/caches/ +[RFC 9111]: https://datatracker.ietf.org/doc/html/rfc9111 diff --cc docs/content/en/configuration/languages.md index 540cfd34f,000000000..72fee25d3 mode 100644,000000..100644 --- a/docs/content/en/configuration/languages.md +++ b/docs/content/en/configuration/languages.md @@@ -1,193 -1,0 +1,193 @@@ +--- +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 project's default language key, conforming to the syntax described in [RFC 5646]. This value must match one of the defined [language keys](#language-keys). Default is `en`. + +defaultContentLanguageInSubdir +: (`bool`) Whether to publish the default language site to a subdirectory matching the `defaultContentLanguage`. Default is `false`. + +disableDefaultLanguageRedirect +: {{< new-in 0.140.0 />}} +: (`bool`) Whether to disable generation of the alias redirect to the default language when `DefaultContentLanguageInSubdir` is `true`. 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 value does not affect localization or URLs. Hugo 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] + + 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. + +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. + +## 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. + +## 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 +``` + +[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir +[`Language.LanguageCode`]: /methods/site/language/#languagecode +[`Language.LanguageDirection`]: /methods/site/language/#languagedirection +[`Language.LanguageName`]: /methods/site/language/#languagename +[`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 %}} ++[embedded alias template]: <{{% eturl alias %}}> ++[embedded OpenGraph template]: <{{% eturl opengraph %}}> ++[embedded RSS template]: <{{% eturl rss %}}> +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 +[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7 +[translating by file name]: /content-management/multilingual/#translation-by-file-name diff --cc docs/content/en/configuration/markup.md index bf5aac374,000000000..a34074ae5 mode 100644,000000..100644 --- a/docs/content/en/configuration/markup.md +++ b/docs/content/en/configuration/markup.md @@@ -1,357 -1,0 +1,371 @@@ +--- +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. + +`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. + - #### Passthrough ++#### 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`. + - {{< new-in 0.122.0 />}} ++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 +: {{< new-in 0.123.0 />}} +: (`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 +: {{< new-in 0.123.0 />}} +: 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`: Automatically use 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. + - `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. In this case, the embedded hook takes precedence. + - `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 +: {{< new-in 0.123.0 />}} +: Deprecated in v0.148.0. Use `renderHooks.link.useEmbedded` instead. + +renderHooks.link.useEmbedded +: {{< new-in 0.148.0 />}} +: (`string`) When to use the [embedded link render hook]. One of `auto`, `never`, `always`, or `fallback`. Default is `auto`. + + - `auto`: Automatically use 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. + - `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. In this case, the embedded hook takes precedence. + - `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 array`) An array of enabled extensions, one or more of `asciidoctor-html5s`, `asciidoctor-bibtex`, `asciidoctor-diagram`, `asciidoctor-interdoc-reftext`, `asciidoctor-katex`, `asciidoctor-latex`, `asciidoctor-mathematical`, or `asciidoctor-question`. ++: (`string array`) 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: + + {{< 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: + +```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/minify.md index a530cb73d,000000000..3f010f974 mode 100644,000000..100644 --- a/docs/content/en/configuration/minify.md +++ b/docs/content/en/configuration/minify.md @@@ -1,15 -1,0 +1,20 @@@ +--- +title: Configure minify +linkTitle: Minify +description: Configure minify. +categories: [] +keywords: [] +--- + +This is the default configuration: + +{{< code-toggle config=minify />}} + - See the [tdewolff/minify] project page for details. ++See the [tdewolff/minify] project page for details, but note the following: ++ ++- `css.inline` is for internal use. Changing this setting has no effect. ++- `css.keepCSS2` has been deprecated. Use `css.version` instead. ++- `html.keepConditionalComments` has been deprecated. Use `html.keepSpecialComments` instead. ++- `svg.inline` is for internal use. Changing this setting has no effect. + +[tdewolff/minify]: https://github.com/tdewolff/minify diff --cc docs/content/en/configuration/module.md index 4a7267bd6,000000000..76fc034de mode 100644,000000..100644 --- a/docs/content/en/configuration/module.md +++ b/docs/content/en/configuration/module.md @@@ -1,179 -1,0 +1,183 @@@ +--- +title: Configure modules +linkTitle: Modules +description: Configure modules. +categories: [] +keywords: [] +aliases: [/hugo-modules/configuration/] +--- + ++{{% include "/_common/gomodules-info.md" %}} ++ +## Top-level options + +This is the default configuration: + + +{{< code-toggle file=hugo >}} +[module] +noProxy = 'none' +noVendor = '' +private = '*.*' +proxy = 'direct' +vendorClosest = false +workspace = 'off' +{{< /code-toggle >}} + + +auth +: {{< new-in 0.144.0 />}} +: (`string`) Configures `GOAUTH` when running the Go command for module operations. This is a semicolon-separated list of authentication commands for go-import and HTTPS module mirror interactions. This is useful for private repositories. See `go help goauth` for more information. + +noProxy +: (`string`) A comma-separated list of [glob](g) patterns matching paths that should not use the [configured proxy server](#proxy). + +noVendor +: (`string`) A [glob](g) pattern matching module paths to skip when vendoring. + +private +: (`string`) A comma-separated list of [glob](g) patterns matching paths that should be treated as private. + +proxy +: (`string`) The proxy server to use to download remote modules. Default is `direct`, which means `git clone` and similar. + +replacements - : (`string`) Primarily useful for local module development, a comma-separated list of mappings from module paths to directories. Paths may be absolute or relative to the [`themesDir`]. ++: (`string`) Primarily useful for local module development, a comma-separated list of mappings from module paths to directories. Paths may be absolute or relative to the [`themesDir`][]. + + {{< code-toggle file=hugo >}} + [module] + replacements = 'github.com/bep/my-theme -> ../..,github.com/bep/shortcodes -> /some/path' + {{< /code-toggle >}} + +vendorClosest +: (`bool`) Whether to pick the vendored module closest to the module using it. The default behavior is to pick the first. Note that there can still be only one dependency of a given module path, so once it is in use it cannot be redefined. Default is `false`. + +workspace +: (`string`) The Go workspace file to use, either as an absolute path or a path relative to the current working directory. Enabling this activates Go workspace mode and requires Go 1.18 or later. The default is `off`. + +You may also use environment variables to set any of the above. For example: + +```sh +export HUGO_MODULE_PROXY="https://proxy.example.org" +export HUGO_MODULE_REPLACEMENTS="github.com/bep/my-theme -> ../.." +export HUGO_MODULE_WORKSPACE="/my/hugo.work" +``` + - {{% include "/_common/gomodules-info.md" %}} - +## Hugo version + +You can specify a required Hugo version for your module in the `module` section. Users will then receive a warning if their Hugo version is incompatible. + +This is the default configuration: + +{{< code-toggle config=module.hugoVersion />}} + +You can omit any of the settings above. + +extended +: (`bool`) Whether the extended edition of Hugo is required, satisfied by installing either the extended or extended/deploy edition. + +max - : (`string`) The maximum Hugo version supported, for example `0.148.0`. ++: (`string`) The maximum Hugo version supported, for example `0.152.2`. + +min +: (`string`) The minimum Hugo version supported, for example `0.102.0`. + +## Imports + +{{< code-toggle file=hugo >}} +[[module.imports]] +disable = false +ignoreConfig = false +ignoreImports = false +path = "github.com/gohugoio/hugoTestModules1_linux/modh1_2_1v" +[[module.imports]] +path = "my-shortcodes" +{{< /code-toggle >}} + +disable +: (`bool`) Whether to disable the module but keep version information in the `go.*` files. Default is `false`. + +ignoreConfig +: (`bool`) Whether to ignore module configuration files, for example, `hugo.toml`. This will also prevent loading of any transitive module dependencies. Default is `false`. + +ignoreImports +: (`bool`) Whether to ignore module imports. Default is `false`. + +noMounts +: (`bool`) Whether to disable directory mounting for this import. Default is `false`. + +noVendor +: (`bool`) Whether to disable vendoring for this import. This setting is restricted to the main project. Default is `false`. + +path - : (`string`) The module path, either a valid Go module path (e.g., `github.com/gohugoio/myShortcodes`) or the directory name if stored in the [`themesDir`]. ++: (`string`) The module path, either a valid Go module path (e.g., `github.com/gohugoio/myShortcodes`) or the directory name if stored in the [`themesDir`][]. + - {{% include "/_common/gomodules-info.md" %}} ++version ++: {{< new-in 0.150.0 />}} ++: If set to a [version query](https://go.dev/ref/mod#version-queries), this import becomes a direct dependency, in contrast to dependencies managed by Go Modules. See [this issue](https://github.com/gohugoio/hugo/pull/13966) for more information. + +## Mounts + - Before Hugo v0.56.0, custom component paths could only be configured by setting [`archetypeDir`], [`assetDir`], [`contentDir`], [`dataDir`], [`i18nDir`], [`layoutDi`], or [`staticDir`] in the site configuration. Module mounts offer greater flexibility than these legacy settings, but - you cannot use both. ++{{% glossary-term mount %}} + - [`archetypeDir`]: /configuration/all/ - [`assetDir`]: /configuration/all/ - [`contentDir`]: /configuration/all/ - [`dataDir`]: /configuration/all/ - [`i18nDir`]: /configuration/all/ - [`layoutDi`]: /configuration/all/ - [`staticDir`]: /configuration/all/ ++> [!important] ++> If you define one or more mounts to map a file system path to a component path, do not use these legacy configuration settings: [`archetypeDir`][], [`assetDir`][], [`contentDir`][], [`dataDir`][], [`i18nDir`][], [`layoutDir`][], or [`staticDir`][]. + - > [!note] - > If you use module mounts do not use the legacy settings. ++[`archetypeDir`]: /configuration/all/#archetypedir ++[`assetDir`]: /configuration/all/#assetdir ++[`contentDir`]: /configuration/all/#contentdir ++[`dataDir`]: /configuration/all/#datadir ++[`i18nDir`]: /configuration/all/#i18ndir ++[`layoutDir`]: /configuration/all/#layoutdir ++[`staticDir`]: /configuration/all/#staticdir + +### Default mounts + - > [!note] - > Adding a new mount to a target root will cause the existing default mount for that root to be ignored. If you still need the default mount, you must explicitly add it along with the new mount. ++Within a project, if you define a mount to map a file system path to a component path, the corresponding default mount for that component will be removed. This action essentially overwrites the standard, automatic mapping for that specific component with your custom one. ++ ++Within a module, if you define a mount to map a file system path to a component path, all of the default mounts will be removed. Defining a mount at the module level is a more sweeping change, causing all default mappings within that module to be discarded. ++ ++In either case, if you still need one of the default mounts, you must explicitly add it along with the new mount. Because custom mounts override defaults, any necessary default mappings must be re-added manually after you introduce your custom configuration. + - The are the default mounts: ++These are the default mounts: + +{{< code-toggle config=module.mounts />}} + +source +: (`string`) The source directory of the mount. For the main project, this can be either project-relative or absolute. For other modules it must be project-relative. + +target - : (`string`) Where the mount will reside within Hugo's virtual file system. It must begin with one of Hugo's component directories: `archetypes`, `assets`, `content`, `data`, `i18n`, `layouts`, or `static`. For example, `content/blog`. ++: (`string`) Where the mount will reside within Hugo's [unified file system](g). It must begin with one of Hugo's [component](g) directories: archetypes, assets, content, data, i18n, layouts, or static. For example, content/blog. + +disableWatch +: {{< new-in 0.128.0 />}} +: (`bool`) Whether to disable watching in watch mode for this mount. Default is `false`. + +lang +: (`string`) The language code, e.g. "en". Relevant for `content` mounts, and `static` mounts when in multihost mode. + +includeFiles +: (`string` or `[]string`) One or more [glob](g) patterns matching files or directories to include. If `excludeFiles` is not set, the files matching `includeFiles` will be the files mounted. + + The glob patterns are matched against file names relative to the source root. Use Unix-style forward slashes (`/`), even on Windows. A single forward slash (`/`) matches the mount root, and double asterisks (`**`) act as a recursive wildcard, matching all directories and files beneath a given point (e.g., `/posts/**.jpg`). The search is case-insensitive. + +excludeFiles +: (`string` or `[]string`) One or more [glob](g) patterns matching files to exclude. + +### Example + +{{< code-toggle file=hugo >}} +[module] +[[module.mounts]] + source="content" + target="content" + excludeFiles="docs/*" +[[module.mounts]] + source="node_modules" + target="assets" +[[module.mounts]] + source="assets" + target="assets" +{{< /code-toggle >}} + +[`themesDir`]: /configuration/all/#themesdir diff --cc docs/content/en/content-management/archetypes.md index db0838504,000000000..5f7d1ece4 mode 100644,000000..100644 --- a/docs/content/en/content-management/archetypes.md +++ b/docs/content/en/content-management/archetypes.md @@@ -1,186 -1,0 +1,186 @@@ +--- +title: Archetypes +description: An archetype is a template for new content. +categories: [] +keywords: [] +aliases: [/content/archetypes/] +--- + +## Overview + +A content file consists of [front matter](g) and markup. The markup is typically Markdown, but Hugo also supports other [content formats](g). Front matter can be TOML, YAML, or JSON. + +The `hugo new content` command creates a new file in the `content` directory, using an archetype as a template. This is the default archetype: + +{{< code-toggle file=archetypes/default.md fm=true >}} +title = '{{ replace .File.ContentBaseName `-` ` ` | title }}' +date = '{{ .Date }}' +draft = true +{{< /code-toggle >}} + +When you create new content, Hugo evaluates the [template actions](g) within the archetype. For example: + +```sh +hugo new content posts/my-first-post.md +``` + +With the default archetype shown above, Hugo creates this content file: + +{{< code-toggle file=content/posts/my-first-post.md fm=true >}} +title = 'My First Post' +date = '2023-08-24T11:49:46-07:00' +draft = true +{{< /code-toggle >}} + +You can create an archetype for one or more [content types](g). For example, use one archetype for posts, and use the default archetype for everything else: + +```text +archetypes/ +├── default.md +└── posts.md +``` + +## Lookup order + +Hugo looks for archetypes in the `archetypes` directory in the root of your project, falling back to the `archetypes` directory in themes or installed modules. An archetype for a specific content type takes precedence over the default archetype. + - For example, with this command: ++For example, if you have enabled a theme named `my-theme` and you run this command: + +```sh +hugo new content posts/my-first-post.md +``` + +The archetype lookup order is: + +1. `archetypes/posts.md` - 1. `archetypes/default.md` +1. `themes/my-theme/archetypes/posts.md` ++1. `archetypes/default.md` +1. `themes/my-theme/archetypes/default.md` + +If none of these exists, Hugo uses a built-in default archetype. + +## Functions and context + +You can use any template [function](g) within an archetype. As shown above, the default archetype uses the [`replace`](/functions/strings/replace) function to replace hyphens with spaces when populating the title in front matter. + +Archetypes receive the following [context](g): + +Date +: (`string`) The current date and time, formatted in compliance with RFC3339. + +File +: (`hugolib.fileInfo`) Returns file information for the current page. See [details](/methods/page/file). + +Type +: (`string`) The [content type](g) inferred from the top-level directory name, or as specified by the `--kind` flag passed to the `hugo new content` command. + +Site +: (`page.Site`) The current site object. See [details](/methods/site/). + +## Date format + +To insert date and time with a different format, use the [`time.Now`] function: + +[`time.Now`]: /functions/time/now/ + +{{< code-toggle file=archetypes/default.md fm=true >}} +title = '{{ replace .File.ContentBaseName `-` ` ` | title }}' +date = '{{ time.Now.Format "2006-01-02" }}' +draft = true +{{< /code-toggle >}} + +## Include content + +Although typically used as a front matter template, you can also use an archetype to populate content. + +For example, in a documentation site you might have a section (content type) for functions. Every page within this section should follow the same format: a brief description, the function signature, examples, and notes. We can pre-populate the page to remind content authors of the standard format. + +````text {file="archetypes/functions.md"} +--- +date: '{{ .Date }}' +draft: true +title: '{{ replace .File.ContentBaseName `-` ` ` | title }}' +--- + +A brief description of what the function does, using simple present tense in the third person singular form. For example: + +`someFunction` returns the string `s` repeated `n` times. + +## Signature + +```text +func someFunction(s string, n int) string +``` + +## Examples + +One or more practical examples, each within a fenced code block. + +## Notes + +Additional information to clarify as needed. +```` + +Although you can include [template actions](g) within the content body, remember that Hugo evaluates these once---at the time of content creation. In most cases, place template actions in a [template](g) where Hugo evaluates the actions every time you [build](g) the site. + +## Leaf bundles + +You can also create archetypes for [leaf bundles](g). + +For example, in a photography site you might have a section (content type) for galleries. Each gallery is leaf bundle with content and images. + +Create an archetype for galleries: + +```text +archetypes/ +├── galleries/ +│ ├── images/ +│ │ └── .gitkeep +│ └── index.md <-- same format as default.md +└── default.md +``` + +Subdirectories within an archetype must contain at least one file. Without a file, Hugo will not create the subdirectory when you create new content. The name and size of the file are irrelevant. The example above includes a `.gitkeep` file, an empty file commonly used to preserve otherwise empty directories in a Git repository. + +To create a new gallery: + +```sh +hugo new galleries/bryce-canyon +``` + +This produces: + +```text +content/ +├── galleries/ +│ └── bryce-canyon/ +│ ├── images/ +│ │ └── .gitkeep +│ └── index.md +└── _index.md +``` + +## Specify archetype + +Use the `--kind` command line flag to specify an archetype when creating content. + +For example, let's say your site has two sections: articles and tutorials. Create an archetype for each content type: + +```text +archetypes/ +├── articles.md +├── default.md +└── tutorials.md +``` + +To create an article using the articles archetype: + +```sh +hugo new content articles/something.md +``` + +To create an article using the tutorials archetype: + +```sh +hugo new content --kind tutorials articles/something.md +``` diff --cc docs/content/en/content-management/diagrams.md index 3bcecb60b,000000000..763fce2d6 mode 100644,000000..100644 --- a/docs/content/en/content-management/diagrams.md +++ b/docs/content/en/content-management/diagrams.md @@@ -1,260 -1,0 +1,260 @@@ +--- +title: Diagrams +description: Use fenced code blocks and Markdown render hooks to include diagrams in your content. +categories: [] +keywords: [] +--- + +## GoAT diagrams (ASCII) + +Hugo natively supports [GoAT] diagrams with an [embedded code block render hook]. This means that this code block: + +````txt +```goat + . . . .--- 1 .-- 1 / 1 + / \ | | .---+ .-+ + + / \ .---+---. .--+--. | '--- 2 | '-- 2 / \ 2 + + + | | | | ---+ ---+ + + / \ / \ .-+-. .-+-. .+. .+. | .--- 3 | .-- 3 \ / 3 + / \ / \ | | | | | | | | '---+ '-+ + + 1 2 3 4 1 2 3 4 1 2 3 4 '--- 4 '-- 4 \ 4 + +``` +```` + +Will be rendered as: + +```goat + + . . . .--- 1 .-- 1 / 1 + / \ | | .---+ .-+ + + / \ .---+---. .--+--. | '--- 2 | '-- 2 / \ 2 + + + | | | | ---+ ---+ + + / \ / \ .-+-. .-+-. .+. .+. | .--- 3 | .-- 3 \ / 3 + / \ / \ | | | | | | | | '---+ '-+ + + 1 2 3 4 1 2 3 4 1 2 3 4 '--- 4 '-- 4 \ 4 +``` + +## Mermaid diagrams + +Hugo does not provide a built-in template for Mermaid diagrams. Create your own using a [code block render hook]: + +```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 }} +``` + +With that you can use the `mermaid` language in Markdown code blocks: + +````text {copy=true} +```mermaid +sequenceDiagram + participant Alice + participant Bob + Alice->>John: Hello John, how are you? + loop Healthcheck + John->>John: Fight against hypochondria + end + Note right of John: Rational thoughts
prevail! + John-->>Alice: Great! + John->>Bob: How about you? + Bob-->>John: Jolly good! +``` +```` + +## Goat ASCII diagram examples + +### Graphics + +```goat + . + 0 3 P * Eye / ^ / + *-------* +y \ +) \ / Reflection + 1 /| 2 /| ^ \ \ \ v + *-------* | | v0 \ v3 --------*-------- + | |4 | |7 | *----\-----* + | *-----|-* +-----> +x / v X \ .-.<-------- o + |/ |/ / / o \ | / | Refraction / \ + *-------* v / \ +-' / \ + 5 6 +z v1 *------------------* v2 | o-----o + v + +``` + +### Complex + +```goat ++-------------------+ ^ .---. +| A Box |__.--.__ __.--> | .-. | | +| | '--' v | * |<--- | | ++-------------------+ '-' | | + Round *---(-. | + .-----------------. .-------. .----------. .-------. | | | + | Mixed Rounded | | | / Diagonals \ | | | | | | + | & Square Corners | '--. .--' / \ |---+---| '-)-' .--------. + '--+------------+-' .--. | '-------+--------' | | | | / Search / + | | | | '---. | '-------' | '-+------' + |<---------->| | | | v Interior | ^ + ' <---' '----' .-----------. ---. .--- v | + .------------------. Diag line | .-------. +---. \ / . | + | if (a > b) +---. .--->| | | | | Curved line \ / / \ | + | obj->fcn() | \ / | '-------' |<--' + / \ | + '------------------' '--' '--+--------' .--. .--. | .-. +Done?+-' + .---+-----. | ^ |\ | | /| .--+ | | \ / + | | | Join \|/ | | Curved | \| |/ | | \ | \ / + | | +----> o --o-- '-' Vertical '--' '--' '-- '--' + .---. + <--+---+-----' | /|\ | | 3 | + v not:line 'quotes' .-' '---' + .-. .---+--------. / A || B *bold* | ^ + | | | Not a dot | <---+---<-- A dash--is not a line v | + '-' '---------+--' / Nor/is this. --- + +``` + +### Process + +```goat + . + .---------. / \ + | START | / \ .-+-------+-. ___________ + '----+----' .-------. A / \ B | |COMPLEX| | / \ .-. + | | END |<-----+CHOICE +----->| | | +--->+ PREPARATION +--->| X | + v '-------' \ / | |PROCESS| | \___________/ '-' + .---------. \ / '-+---+---+-' + / INPUT / \ / + '-----+---' ' + | ^ + v | + .-----------. .-----+-----. .-. + | PROCESS +---------------->| PROCESS |<------+ X | + '-----------' '-----------' '-' +``` + +### File tree + +Created from + +```goat {width=300 color="orange"} +───Linux─┬─Android + ├─Debian─┬─Ubuntu─┬─Lubuntu + │ │ ├─Kubuntu + │ │ ├─Xubuntu + │ │ └─Xubuntu + │ └─Mint + ├─Centos + └─Fedora +``` + +### Sequence diagram + + + +```goat {class="w-40"} +┌─────┐ ┌───┐ +│Alice│ │Bob│ +└──┬──┘ └─┬─┘ + │ │ + │ Hello Bob! │ + │───────────>│ + │ │ + │Hello Alice!│ + │<───────────│ +┌──┴──┐ ┌─┴─┐ +│Alice│ │Bob│ +└─────┘ └───┘ + +``` + +### Flowchart + + + +```goat + _________________ + ╱ ╲ ┌─────┐ + ╱ DO YOU UNDERSTAND ╲____________________________________________________│GOOD!│ + ╲ FLOW CHARTS? ╱yes └──┬──┘ + ╲_________________╱ │ + │no │ + _________▽_________ ______________________ │ + ╱ ╲ ╱ ╲ ┌────┐ │ +╱ OKAY, YOU SEE THE ╲________________╱ ... AND YOU CAN SEE ╲___│GOOD│ │ +╲ LINE LABELED 'YES'? ╱yes ╲ THE ONES LABELED 'NO'? ╱yes└──┬─┘ │ + ╲___________________╱ ╲______________________╱ │ │ + │no │no │ │ + ________▽_________ _________▽__________ │ │ + ╱ ╲ ┌───────────┐ ╱ ╲ │ │ + ╱ BUT YOU SEE THE ╲___│WAIT, WHAT?│ ╱ BUT YOU JUST ╲___ │ │ + ╲ ONES LABELED 'NO'? ╱yes└───────────┘ ╲ FOLLOWED THEM TWICE? ╱yes│ │ │ + ╲__________________╱ ╲____________________╱ │ │ │ + │no │no │ │ │ + ┌───▽───┐ │ │ │ │ + │LISTEN.│ └───────┬───────┘ │ │ + └───┬───┘ ┌──────▽─────┐ │ │ + ┌─────▽────┐ │(THAT WASN'T│ │ │ + │I HATE YOU│ │A QUESTION) │ │ │ + └──────────┘ └──────┬─────┘ │ │ + ┌────▽───┐ │ │ + │SCREW IT│ │ │ + └────┬───┘ │ │ + └─────┬─────┘ │ + │ │ + └─────┬─────┘ + ┌───────▽──────┐ + │LET'S GO DRING│ + └───────┬──────┘ + ┌─────────▽─────────┐ + │HEY, I SHOULD TRY │ + │INSTALLING FREEBSD!│ + └───────────────────┘ + +``` + +### Table + + + +```goat {class="w-80 dark-blue"} +┌────────────────────────────────────────────────┐ +│ │ +├────────────────────────────────────────────────┤ +│SYNTAX = { PRODUCTION } . │ +├────────────────────────────────────────────────┤ +│PRODUCTION = IDENTIFIER "=" EXPRESSION "." . │ +├────────────────────────────────────────────────┤ +│EXPRESSION = TERM { "|" TERM } . │ +├────────────────────────────────────────────────┤ +│TERM = FACTOR { FACTOR } . │ +├────────────────────────────────────────────────┤ +│FACTOR = IDENTIFIER │ +├────────────────────────────────────────────────┤ +│ | LITERAL │ +├────────────────────────────────────────────────┤ +│ | "[" EXPRESSION "]" │ +├────────────────────────────────────────────────┤ +│ | "(" EXPRESSION ")" │ +├────────────────────────────────────────────────┤ +│ | "{" EXPRESSION "}" . │ +├────────────────────────────────────────────────┤ +│IDENTIFIER = letter { letter } . │ +├────────────────────────────────────────────────┤ +│LITERAL = """" character { character } """" .│ +└────────────────────────────────────────────────┘ +``` + +[code block render hook]: /render-hooks/code-blocks/ - [embedded code block render hook]: {{% eturl render-codeblock-goat %}} ++[embedded code block render hook]: <{{% eturl render-codeblock-goat %}}> +[GoAT]: https://github.com/bep/goat diff --cc docs/content/en/content-management/front-matter.md index 2da6a2613,000000000..f0484ef74 mode 100644,000000..100644 --- a/docs/content/en/content-management/front-matter.md +++ b/docs/content/en/content-management/front-matter.md @@@ -1,357 -1,0 +1,357 @@@ +--- +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 array`) An array of one or more aliases, where each alias is a relative URL that will redirect the browser to the current location. 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 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. ++: (`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 array`) 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 array`, 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 array`) The [output formats] to render. See [configure outputs] for more information. + +params +: {{< new-in 0.123.0 />}} +: (`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. + +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 + +{{< new-in 0.123.0 />}} + +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: + +{{< 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 >}} + +### 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/**}' +{{< /code-toggle >}} + +Use any combination of these keywords to target pages and/or environments: + +environment +: (`string`) A [glob](g) pattern matching the build [environment](g). For example: `{staging,production}`. + +kind +: (`string`) A [glob](g) pattern matching the [page kind](g). For example: `{taxonomy,term}`. + +path +: (`string`) A [glob](g) pattern 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=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/). +> +> 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: + +1. The time zone offset in the date/time string +1. The time zone specified in your site 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 %}} ++[`opengraph.html`]: <{{% eturl opengraph %}}> +[`Param`]: /methods/page/param/ +[`Params`]: /methods/page/params/ +[`publishdate`]: /methods/page/publishdate/ +[`readingtime`]: /methods/page/readingtime/ - [`schema.html`]: {{% eturl schema %}} ++[`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 %}} ++[`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 8d60c4f93,000000000..3cf8aa4fd 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,447 -1,0 +1,445 @@@ +--- +title: Image processing +description: Resize, crop, rotate, filter, and convert images. +categories: [] +keywords: [] +--- + +## Image resources + +To process an image you must access the file as a page resource, global resource, or remote resource. + +### Page resource + +{{% glossary-term "page resource" %}} + +```text +content/ +└── posts/ + └── post-1/ <-- page bundle + ├── index.md + └── sunset.jpg <-- page resource +``` + +To access an image as a page resource: + +```go-html-template +{{ $image := .Resources.Get "sunset.jpg" }} +``` + +### Global resource + +{{% glossary-term "global resource" %}} + +```text +assets/ +└── images/ + └── sunset.jpg <-- global resource +``` + +To access an image as a global resource: + +```go-html-template +{{ $image := resources.Get "images/sunset.jpg" }} +``` + +### Remote resource + +{{% glossary-term "remote resource" %}} + +To access an image as a remote resource: + +```go-html-template +{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }} +``` + +## Image rendering + +Once you have accessed an image as a resource, render it in your templates using the `Permalink`, `RelPermalink`, `Width`, and `Height` properties. + +Example 1: Throws an error if the resource is not found. + +```go-html-template +{{ $image := .Resources.GetMatch "sunset.jpg" }} + +``` + +Example 2: Skips 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: Skips 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 }} +``` + +## Image processing methods + +The `image` resource implements the [`Process`], [`Resize`], [`Fit`], [`Fill`], [`Crop`], [`Filter`], [`Colors`] and [`Exif`] methods. + +> [!note] +> Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the `Exif` method with the _original_ image to extract EXIF metadata from JPEG, PNG, TIFF, and WebP images. + +### Process + - {{< new-in 0.119.0 />}} - +> [!note] +> The `Process` method is also available as a filter, which is more effective if you need to apply multiple filters to an image. See [Process filter](/functions/images/process). + +Process processes the image with the given specification. The specification can contain an optional action, one of `resize`, `crop`, `fit` or `fill`. This means that you can use this method instead of [`Resize`], [`Fit`], [`Fill`], or [`Crop`]. + +See [Options](#image-processing-options) for available options. + +You can also use this method apply image processing that does not need any scaling, e.g. format conversions: + +```go-html-template +{{/* Convert the image from JPG to PNG. */}} +{{ $png := $jpg.Process "png" }} +``` + +Some more examples: + +```go-html-template +{{/* Rotate the image 90 degrees counter-clockwise. */}} +{{ $image := $image.Process "r90" }} + +{{/* Scaling actions. */}} +{{ $image := $image.Process "resize 600x" }} +{{ $image := $image.Process "crop 600x400" }} +{{ $image := $image.Process "fit 600x400" }} +{{ $image := $image.Process "fill 600x400" }} +``` + +### Resize + +Resize an image to the given width and/or height. + +If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio. + +```go-html-template +{{/* Resize to a width of 600px and preserve aspect ratio */}} +{{ $image := $image.Resize "600x" }} + +{{/* Resize to a height of 400px and preserve aspect ratio */}} +{{ $image := $image.Resize "x400" }} + +{{/* Resize to a width of 600px and a height of 400px */}} +{{ $image := $image.Resize "600x400" }} +``` + +### Fit + +Downscale an image to fit the given dimensions while maintaining aspect ratio. You must provide both width and height. + +```go-html-template +{{ $image := $image.Fit "600x400" }} +``` + +### Fill + +Crop and resize an image to match the given dimensions. You must provide both width and height. Use the [`anchor`] option to change the crop box anchor point. + +```go-html-template +{{ $image := $image.Fill "600x400" }} +``` + +### Crop + +Crop an image to match the given dimensions without resizing. You must provide both width and height. Use the [`anchor`] option to change the crop box anchor point. + +```go-html-template +{{ $image := $image.Crop "600x400" }} +``` + +### Filter + +Apply one or more [filters] to an image. + +```go-html-template +{{ $image := $image.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} +``` + +Write this in a more functional style using pipes. Hugo applies the filters in the order given. + +```go-html-template +{{ $image := $image | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} +``` + +Sometimes it can be useful to create the filter chain once and then reuse it. + +```go-html-template +{{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) }} +{{ $image1 := $image1.Filter $filters }} +{{ $image2 := $image2.Filter $filters }} +``` + +### Colors + +`.Colors` returns a slice of hex strings with the dominant colors in the image using a simple histogram method. + +```go-html-template +{{ $colors := $image.Colors }} +``` + +This method is fast, but if you also scale down your images, it would be good for performance to extract the colors from the scaled down image. + +### EXIF + +Provides an [EXIF] object containing image metadata. + +You may access EXIF data in JPEG, PNG, TIFF, and WebP images. To prevent errors when processing images without EXIF data, wrap the access in a [`with`] statement. + +```go-html-template +{{ with $image.Exif }} + Date: {{ .Date }} + Lat/Long: {{ .Lat }}/{{ .Long }} + Tags: + {{ range $k, $v := .Tags }} + TAG: {{ $k }}: {{ $v }} + {{ end }} +{{ end }} +``` + +You may also access EXIF fields individually, using the [`lang.FormatNumber`] function to format the fields as needed. + +```go-html-template +{{ with $image.Exif }} +
    + {{ with .Date }}
  • Date: {{ .Format "January 02, 2006" }}
  • {{ end }} + {{ with .Tags.ApertureValue }}
  • Aperture: {{ lang.FormatNumber 2 . }}
  • {{ end }} + {{ with .Tags.BrightnessValue }}
  • Brightness: {{ lang.FormatNumber 2 . }}
  • {{ end }} + {{ with .Tags.ExposureTime }}
  • Exposure Time: {{ . }}
  • {{ end }} + {{ with .Tags.FNumber }}
  • F Number: {{ . }}
  • {{ end }} + {{ with .Tags.FocalLength }}
  • Focal Length: {{ . }}
  • {{ end }} + {{ with .Tags.ISOSpeedRatings }}
  • ISO Speed Ratings: {{ . }}
  • {{ end }} + {{ with .Tags.LensModel }}
  • Lens Model: {{ . }}
  • {{ end }} +
+{{ end }} +``` + +#### EXIF methods + +Date +: (`time.Time`) Returns the image creation date/time. Format with the [`time.Format`]function. + +Lat +: (`float64`) Returns the GPS latitude in degrees. + +Long +: (`float64`) Returns the GPS longitude in degrees. + +Tags +: (`exif.Tags`) Returns a collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration]. + +## Image processing options + +The [`Resize`], [`Fit`], [`Fill`], and [`Crop`] methods accept a space-delimited, case-insensitive list of options. The order of the options within the list is irrelevant. + +### Dimensions + +With the [`Resize`] method you must specify width, height, or both. The [`Fit`], [`Fill`], and [`Crop`] methods require both width and height. All dimensions are in pixels. + +```go-html-template +{{ $image := $image.Resize "600x" }} +{{ $image := $image.Resize "x400" }} +{{ $image := $image.Resize "600x400" }} +{{ $image := $image.Fit "600x400" }} +{{ $image := $image.Fill "600x400" }} +{{ $image := $image.Crop "600x400" }} +``` + +### Rotation + +Rotates an image counter-clockwise by the given angle. Hugo performs rotation _before_ scaling. For example, if the original image is 600x400 and you wish to rotate the image 90 degrees counter-clockwise while scaling it by 50%: + +```go-html-template +{{ $image = $image.Resize "200x r90" }} +``` + +In the example above, the width represents the desired width _after_ rotation. + +To rotate an image without scaling, use the dimensions of the original image: + +```go-html-template +{{ with .Resources.GetMatch "sunset.jpg" }} + {{ with .Resize (printf "%dx%d r90" .Height .Width) }} + + {{ end }} +{{ end }} +``` + +In the example above, on the second line, we have reversed width and height to reflect the desired dimensions _after_ rotation. + +### Anchor + +When using the [`Crop`] or [`Fill`] method, the _anchor_ determines the placement of the crop box. You may specify `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. + +The default value is `Smart`, which uses [Smartcrop] image analysis to determine the optimal placement of the crop box. You may override the default value in the [site configuration]. + +For example, if you have a 400x200 image with a bird in the upper left quadrant, you can create a 200x100 thumbnail containing the bird: + +```go-html-template +{{ $image.Crop "200x100 TopLeft" }} +``` + +If you apply [rotation](#rotation) when using the [`Crop`] or [`Fill`] method, specify the anchor relative to the rotated image. + +### Target format + +By default, Hugo encodes the image in the source format. You may convert the image to another format by specifying `bmp`, `gif`, `jpeg`, `jpg`, `png`, `tif`, `tiff`, or `webp`. + +```go-html-template +{{ $image.Resize "600x webp" }} +``` + +To convert an image without scaling, use the dimensions of the original image: + +```go-html-template +{{ with .Resources.GetMatch "sunset.jpg" }} + {{ with .Resize (printf "%dx%d webp" .Width .Height) }} + + {{ end }} +{{ end }} +``` + +### Quality + +Applicable to JPEG and WebP images, the `q` value determines the quality of the converted image. Higher values produce better quality images, while lower values produce smaller files. Set this value to a whole number between 1 and 100, inclusive. + +The default value is 75. You may override the default value in the [site configuration]. + +```go-html-template +{{ $image.Resize "600x webp q50" }} +``` + +### Hint + +Applicable to WebP images, this option corresponds to a set of predefined encoding parameters, and is equivalent to the `-preset` flag for the [`cwebp`] encoder. + +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 + +The default value is `photo`. You may override the default value in the [site configuration]. + +```go-html-template +{{ $image.Resize "600x webp picture" }} +``` + +### Background color + +When converting an image from a format that supports transparency (e.g., PNG) to a format that does _not_ support transparency (e.g., JPEG), you may specify the background color of the resulting image. + +Use either a 3-digit or 6-digit hexadecimal color code (e.g., `#00f` or `#0000ff`). + +The default value is `#ffffff` (white). You may override the default value in the [site configuration]. + +```go-html-template +{{ $image.Resize "600x jpg #b31280" }} +``` + +### Resampling filter + +You may specify the resampling filter used when resizing an image. Commonly used resampling filters include: + +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 + +The default value is `Box`. You may override the default value in the [site configuration]. + +```go-html-template +{{ $image.Resize "600x400 Lanczos" }} +``` + +See [github.com/disintegration/imaging] for the complete list of resampling filters. If you wish to improve image quality at the expense of performance, you may wish to experiment with the alternative filters. + +## Image processing examples + +_The photo of the sunset used in the examples below is Copyright [Bjørn Erik Pedersen](https://bep.is) (Creative Commons Attribution-Share Alike 4.0 International license)_ + +{{< imgproc path="sunset.jpg" spec="resize 480x" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="fill 120x150 left" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="fill 120x150 right" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="fit 120x120" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="crop 240x240 center" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="resize 360x q10" alt="A sunset" />}} + +## Configuration + +See [configure imaging](/configuration/imaging). + +## Smart cropping of images + +By default, Hugo uses the [Smartcrop] library when cropping images with the `Crop` or `Fill` methods. You can set the anchor point manually, but in most cases the `Smart` option will make a good choice. + +Examples using the sunset image from above: + +{{< imgproc path="sunset.jpg" spec="fill 200x200 smart" alt="A sunset" />}} + +{{< imgproc path="sunset.jpg" spec="crop 200x200 smart" alt="A sunset" />}} + +## Image processing performance consideration + +Hugo caches processed images in the `resources` directory. If you include this directory in source control, Hugo will not have to regenerate the images in a [CI/CD](g) workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds. + +If you change image processing methods or options, or if you rename or remove images, the `resources` directory will contain unused images. To remove the unused images, perform garbage collection with: + +```sh +hugo --gc +``` + +[`anchor`]: /content-management/image-processing#anchor +[`Colors`]: #colors +[`Crop`]: #crop +[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp +[`Exif`]: #exif +[`Fill`]: #fill +[`Filter`]: #filter +[`Fit`]: #fit +[`lang.FormatNumber`]: /functions/lang/formatnumber/ +[`Process`]: #process +[`Resize`]: #resize +[`time.Format`]: /functions/time/format/ +[`with`]: /functions/go-template/with/ +[EXIF]: https://en.wikipedia.org/wiki/Exif +[filters]: /functions/images/filter/#image-filters +[github.com/disintegration/imaging]: https://github.com/disintegration/imaging#image-resizing +[site configuration]: /configuration/imaging/ +[Smartcrop]: https://github.com/muesli/smartcrop#smartcrop diff --cc docs/content/en/content-management/mathematics.md index aaa8c2394,000000000..5414a00f9 mode 100644,000000..100644 --- a/docs/content/en/content-management/mathematics.md +++ b/docs/content/en/content-management/mathematics.md @@@ -1,233 -1,0 +1,237 @@@ +--- +title: Mathematics in Markdown +linkTitle: Mathematics +description: Include mathematical equations and expressions in Markdown using LaTeX markup. +categories: [] +keywords: [] +--- + - {{< new-in 0.122.0 />}} - +## 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]. ++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, with this LaTeX markup: ++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} +\] +``` + - The MathJax display engine renders this: ++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 site. +> +> 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 site 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](#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 site 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](#inline-delimiters) section for details. ++ > 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]. ++ 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](#engines) section. ++: 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. + +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. + +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: + + {{< 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](https://github.com/KaTeX/KaTeX/issues/437). ++> 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. Both engines are fast, but at the time of this writing MathJax v3.2.2 is slightly faster than KaTeX v0.16.11. ++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](https://github.com/KaTeX/KaTeX/issues/437). ++> 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](#inline-delimiters) section for details. ++>See the [inline delimiters][] section for details. + - To use KaTeX instead of MathJax, replace the _partial_ template from [Step 2] with this: ++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. + +## 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](#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). ++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/organization/index.md index 4c6b94e3e,000000000..e1f6d8acd 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 `0.32` announced page-relative images and other resources packaged into `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]. + +### 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/summaries.md index da61c2c8e,000000000..93386eec2 mode 100644,000000..100644 --- a/docs/content/en/content-management/summaries.md +++ b/docs/content/en/content-management/summaries.md @@@ -1,123 -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. + +[`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/taxonomies.md index 12d96170e,000000000..8f990621d mode 100644,000000..100644 --- a/docs/content/en/content-management/taxonomies.md +++ b/docs/content/en/content-management/taxonomies.md @@@ -1,180 -1,0 +1,177 @@@ +--- +title: Taxonomies +description: Hugo includes support for user-defined taxonomies. +categories: [] +keywords: [] +aliases: [/taxonomies/overview/,/taxonomies/usage/,/indexes/overview/,/doc/indexes/,/extras/indexes] +--- + +## What is a taxonomy? + +Hugo includes support for user-defined groupings of content called **taxonomies**. Taxonomies are classifications of logical relationships between content. + +### Definitions + +Taxonomy +: A categorization that can be used to classify content + +Term +: A key within the taxonomy + +Value +: A piece of content assigned to a term + +## Example taxonomy: movie website + +Let's assume you are making a website about movies. You may want to include the following taxonomies: + +- Actors +- Directors +- Studios +- Genre +- Year +- Awards + +Then, in each of the movies, you would specify terms for each of these taxonomies (i.e., in the front matter of each of your movie content files). From these terms, Hugo would automatically create pages for each Actor, Director, Studio, Genre, Year, and Award, with each listing all of the Movies that matched that specific Actor, Director, Studio, Genre, Year, and Award. + +### Movie taxonomy organization + +To continue with the example of a movie site, the following demonstrates content relationships from the perspective of the taxonomy: + +```txt +Actor <- Taxonomy + Bruce Willis <- Term + The Sixth Sense <- Value + Unbreakable <- Value + Moonrise Kingdom <- Value + Samuel L. Jackson <- Term + Unbreakable <- Value + The Avengers <- Value + xXx <- Value +``` + +From the perspective of the content, the relationships would appear differently, although the data and labels used are the same: + +```txt +Unbreakable <- Value + Actors <- Taxonomy + Bruce Willis <- Term + Samuel L. Jackson <- Term + Director <- Taxonomy + M. Night Shyamalan <- Term + ... +Moonrise Kingdom <- Value + Actors <- Taxonomy + Bruce Willis <- Term + Bill Murray <- Term + Director <- Taxonomy + Wes Anderson <- Term + ... +``` + +### Default destinations + +When taxonomies are used Hugo will automatically create both a page listing all the taxonomy's terms and individual pages with lists of content associated with each term. For example, a `categories` taxonomy declared in your configuration and used in your content front matter will create the following pages: + +- A single page at `example.com/categories/` that lists all the terms within the taxonomy +- Individual taxonomy list pages (e.g., `/categories/development/`) for each of the terms that shows a listing of all pages marked as part of that taxonomy within any content file's front matter + +## Configuration + +See [configure taxonomies](/configuration/taxonomies/). + +## Assign terms to content + +To assign one or more terms to a page, create a front matter field using the plural name of the taxonomy, then add terms to the corresponding array. For example: + +{{< code-toggle file=content/example.md fm=true >}} +title = 'Example' +tags = ['Tag A','Tag B'] +categories = ['Category A','Category B'] +{{< /code-toggle >}} + - ## Order taxonomies ++## Taxonomic weight + - A content file can assign weight for each of its associate taxonomies. Taxonomic weight can be used for sorting or ordering content in taxonomy templates and is declared in a content file's front matter. The convention for declaring taxonomic weight is `taxonomyname_weight`. ++{{% glossary-term "taxonomic weight" %}} + - The following show a piece of content that has a weight of 22, which can be used for ordering purposes when rendering the pages assigned to the "a", "b" and "c" values of the `tags` taxonomy. It has also been assigned the weight of 44 when rendering the "d" category page. ++Assign a taxonomic weight using a front matter key named `[taxonomy_name]_weight`. + - ### Example: taxonomic `weight` - - {{< code-toggle file=hugo >}} - title = "foo" - tags = [ "a", "b", "c" ] - tags_weight = 22 - categories = ["d"] - categories_weight = 44 ++{{< code-toggle file="content/courses/organic-chemistry.md" fm=true >}} ++title = 'Organic Chemistry' ++weight = 10 ++tags_weight = 1000 ++tags = ['chemistry','science'] +{{}} + - By using taxonomic weight, the same piece of content can appear in different positions in different taxonomies. ++With the front matter above, the "Organic Chemistry" page will float towards the top of the list on section and home pages, and it will sink towards the bottom of the list on the "chemistry" and "science" term pages. + +## Metadata + +Display metadata about each term by creating a corresponding branch bundle in the `content` directory. + +For example, create an "authors" taxonomy: + +{{< code-toggle file=hugo >}} +[taxonomies] +author = 'authors' +{{< /code-toggle >}} + +Then create content with one [branch bundle](g) for each term: + +```text +content/ +└── authors/ + ├── jsmith/ + │ ├── _index.md + │ └── portrait.jpg + └── rjones/ + ├── _index.md + └── portrait.jpg +``` + +Then add front matter to each term page: + +{{< code-toggle file=content/authors/jsmith/_index.md fm=true >}} +title = "John Smith" +affiliation = "University of Chicago" +{{< /code-toggle >}} + +Then create a _taxonomy_ template specific to the "authors" taxonomy: + +```go-html-template {file="layouts/authors/taxonomy.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Data.Terms.Alphabetical }} +

{{ .Page.LinkTitle }}

+

Affiliation: {{ .Page.Params.Affiliation }}

+ {{ with .Page.Resources.Get "portrait.jpg" }} + {{ with .Fill "100x100" }} + portrait + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +In the example above we list each author including their affiliation and portrait. + +Or create a _term_ template specific to the "authors" taxonomy: + +```go-html-template {file="layouts/authors/term.html"} +{{ define "main" }} +

{{ .Title }}

+

Affiliation: {{ .Params.affiliation }}

+ {{ with .Resources.Get "portrait.jpg" }} + {{ with .Fill "100x100" }} + portrait + {{ end }} + {{ end }} + {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +In the example above we display the author including their affiliation and portrait, then a list of associated content. diff --cc docs/content/en/content-management/urls.md index 2513614ee,000000000..fda5f198c mode 100644,000000..100644 --- a/docs/content/en/content-management/urls.md +++ b/docs/content/en/content-management/urls.md @@@ -1,266 -1,0 +1,263 @@@ +--- +title: URL management +description: Control the structure and appearance of URLs through front matter entries and settings in your site 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. + +## 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 + +### 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 + +Create redirects from old URLs to new URLs with aliases: + +- An alias with a leading slash is relative to the `baseURL` +- An alias without a leading slash is relative to the current directory + +### Examples {#alias-examples} + +Change the file name of an existing page, and create an alias from the previous URL to the new URL: + +{{< code-toggle file=content/posts/new-file-name.md fm=true >}} +aliases = ['/posts/previous-file-name'] +{{< /code-toggle >}} + +Each of these directory-relative aliases is equivalent to the site-relative alias above: + +- `previous-file-name` +- `./previous-file-name` +- `../posts/previous-file-name` + +You can create more than one alias to the current page: + +{{< code-toggle file=content/posts/new-file-name.md fm=true >}} +aliases = ['previous-file-name','original-file-name'] +{{< /code-toggle >}} + +In a multilingual site, use a directory-relative alias, or include the language prefix with a site-relative alias: + +{{< code-toggle file=content/posts/new-file-name.de.md fm=true >}} +aliases = ['/de/posts/previous-file-name'] +{{< /code-toggle >}} + +### How aliases work + +Using the first example above, Hugo generates the following site structure: + +```text +public/ +├── posts/ +│ ├── new-file-name/ +│ │ └── index.html +│ ├── previous-file-name/ +│ │ └── index.html +│ └── index.html +└── index.html +``` + +The alias from the previous URL to the new URL is a client-side redirect: + +```html {file="posts/previous-file-name/index.html"} + + + + https://example.org/posts/new-file-name/ + - + + + + +``` + - Collectively, the elements in the `head` section: ++The `link rel="canonical"` tag informs search engines that the new URL is the preferred or "canonical" version of the page. This is crucial for SEO, as it prevents issues with duplicate content by consolidating all ranking signals to a single URL. + - - Tell search engines that the new URL is canonical - - Tell search engines not to index the previous URL - - Tell the browser to redirect to the new URL ++The `http-equiv="refresh"` meta tag instructs the web browser to automatically redirect the user to the new URL. This ensures that anyone who accesses the old alias URL is seamlessly taken to the correct, updated page. + +Hugo renders alias files before rendering pages. A new page with the previous file name will overwrite the alias, as expected. + +### Customize + +To override Hugo's embedded `alias` template, copy the [source code] to a file with the same name in the `layouts` directory. The template receives the following context: + +Permalink +: The link to the page being aliased. + +Page +: The Page data for the page being aliased. + +[`baseURL`]: /configuration/all/#baseurl +[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 - [source code]: {{% eturl alias %}} ++[source code]: <{{% eturl alias %}}> diff --cc docs/content/en/contribute/development.md index 5930fbf52,000000000..db1a2de69 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.23.0 or later ++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 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 ++ - 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.148.0 ++CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@v0.152.2 +``` + +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 2ce2db169,000000000..33f1e8a89 mode 100644,000000..100644 --- a/docs/content/en/contribute/documentation.md +++ b/docs/content/en/contribute/documentation.md @@@ -1,535 -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 [fenced code blocks], not [indented code blocks]. ++- 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.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 + +Use the [code-toggle shortcode](#code-toggle) to include site 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: + +config +: (`string`) The section of `site.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. + +file +: (`string`) The file name to display above the rendered code. Omit the file extension for site 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`. + +```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 */%}} ++[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/D.md index 000000000,000000000..655ced7e3 new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/collections/D.md @@@ -1,0 -1,0 +1,64 @@@ ++--- ++title: collections.D ++description: Returns a slice of sequentially ordered random integers. ++categories: [] ++keywords: [random] ++params: ++ functions_and_methods: ++ returnType: '[]int' ++ signatures: [collections.D SEED N HIGH] ++--- ++ ++{{< new-in 0.149.0 />}} ++ ++The `collections.D` function returns a slice of `N` sequentially ordered unique random integers in the half-open [interval](g) [0, `HIGH`) using the provided [`SEED`](g) value. This function implements J. S. Vitter's Method D[^1] for sequential random sampling, a fast and efficient algorithm for this task. ++ ++See [this article][] for a detailed explanation. ++ ++## Examples ++ ++```go-html-template ++{{ collections.D 6 7 42 }} → [4, 9, 10, 20, 22, 24, 41] ++``` ++ ++The example above generates the _same_ random numbers each time it is called. To generate a _different_ set of 7 random numbers in the same range, change the seed value. ++ ++```go-html-template ++{{ collections.D 2 7 42 }} → [3, 11, 19, 25, 32, 33, 38] ++``` ++ ++A common use case is the selection of random pages from a page collection. For example, to render a list of 5 random pages using the [day of the year][] as the seed value: ++ ++```go-html-template ++ ++``` ++ ++The construct above is significantly faster than using the [`collections.Shuffle`][] function. ++ ++## Seed value ++ ++Choosing an appropriate seed value depends on your objective. ++ ++Objective|Seed example ++:--|:-- ++Consistent result|`42` ++Different result on each call|`int time.Now.UnixNano` ++Same result per day|`time.Now.YearDay` ++Same result per page|`hash.FNV32a .Path` ++Different result per page per day|`hash.FNV32a (print .Path time.Now.YearDay)` ++ ++> [!note] ++> The slice created by this function is limited to 1 million elements. ++ ++[^1]: J. S. Vitter, "An efficient algorithm for sequential random sampling," _ACM Trans. Math. Soft._, vol. 13, pp. 58–67, Mar. 1987. ++ ++[`collections.Shuffle`]: /functions/collections/shuffle/ ++[day of the year]: /methods/time/yearday/ ++[this article]: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/ diff --cc docs/content/en/functions/collections/First.md index 9a672278d,000000000..d7bd565b9 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/First.md +++ b/docs/content/en/functions/collections/First.md @@@ -1,34 -1,0 +1,56 @@@ +--- +title: collections.First +description: Returns the given collection, limited to the first N elements. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [first] + returnType: any + signatures: [collections.First N COLLECTION] +aliases: [/functions/first] +--- + ++```go-html-template ++{{ slice "a" "b" "c" | first 1 }} → [a] ++{{ slice "a" "b" "c" | first 2 }} → [a b] ++``` ++ ++Given that a string is in effect a read-only slice of bytes, this function can be used to return the specified number of bytes from the beginning of the string: ++ ++```go-html-template ++{{ "abc" | first 1 }} → a ++{{ "abc" | first 2 }} → ab ++``` ++ ++Note that a _character_ may consist of multiple _bytes_: ++ ++```go-html-template ++{{ "Schön" | first 3 }} → Sch ++{{ "Schön" | first 4 }} → Sch\xc3 ++{{ "Schön" | first 5 }} → Schö ++``` ++ ++To use the `collections.First` function with a page collection: ++ +```go-html-template +{{ range first 5 .Pages }} + {{ .Render "summary" }} +{{ end }} +``` + - Set `N` to zero to return an empty collection. ++Set `N` to zero to return an empty collection: + +```go-html-template +{{ $emptyPageCollection := first 0 .Pages }} +``` + - Use `first` and [`where`] together. ++Use `first` and [`where`][] together: + +```go-html-template +{{ range where .Pages "Section" "articles" | first 5 }} + {{ .Render "summary" }} +{{ end }} +``` + +[`where`]: /functions/collections/where/ diff --cc docs/content/en/functions/collections/IsSet.md index 5457df5d4,000000000..d254abf1d 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 the key exists within the collection. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [isset] + returnType: bool + signatures: [collections.IsSet COLLECTION KEY] +aliases: [/functions/isset] +--- + +For example, consider this site configuration: + +{{< code-toggle file=hugo >}} +[params] +showHeroImage = false +{{< /code-toggle >}} + - It the value of `showHeroImage` is `true`, we can detect that it exists using either `if` or `with`: ++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/Last.md index f0cfff219,000000000..9ac60de15 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Last.md +++ b/docs/content/en/functions/collections/Last.md @@@ -1,34 -1,0 +1,56 @@@ +--- +title: collections.Last +description: Returns the given collection, limited to the last N elements. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [last] + returnType: any + signatures: [collections.Last N COLLECTION] +aliases: [/functions/last] +--- + +```go-html-template - {{ range last 10 .Pages }} ++{{ slice "a" "b" "c" | last 1 }} → [c] ++{{ slice "a" "b" "c" | last 2 }} → [b c] ++``` ++ ++Given that a string is in effect a read-only slice of bytes, this function can be used to return the specified number of bytes from the end of the string: ++ ++```go-html-template ++{{ "abc" | last 1 }} → c ++{{ "abc" | last 2 }} → bc ++``` ++ ++Note that a _character_ may consist of multiple _bytes_: ++ ++```go-html-template ++{{ "Schön" | last 1 }} → n ++{{ "Schön" | last 2 }} → \xb6n ++{{ "Schön" | last 3 }} → ön ++``` ++ ++To use the `collections.Last` function with a page collection: ++ ++```go-html-template ++{{ range last 5 .Pages }} + {{ .Render "summary" }} +{{ end }} +``` + - Set `N` to zero to return an empty collection. ++Set `N` to zero to return an empty collection: + +```go-html-template +{{ $emptyPageCollection := last 0 .Pages }} +``` + - Use `last` and [`where`] together. ++Use `last` and [`where`][] together: + +[`where`]: /functions/collections/where/ + +```go-html-template +{{ range where .Pages "Section" "articles" | last 5 }} + {{ .Render "summary" }} +{{ end }} +``` diff --cc docs/content/en/functions/collections/Seq.md index e396f07e3,000000000..d3fb34bfa mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Seq.md +++ b/docs/content/en/functions/collections/Seq.md @@@ -1,35 -1,0 +1,35 @@@ +--- +title: collections.Seq +description: Returns a slice of integers. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [seq] + returnType: '[]int' + signatures: + - collections.Seq LAST + - collections.Seq FIRST LAST + - collections.Seq FIRST INCREMENT LAST +aliases: [/functions/seq] +--- + +```go-html-template +{{ seq 2 }} → [1 2] +{{ seq 0 2 }} → [0 1 2] +{{ seq -2 2 }} → [-2 -1 0 1 2] +{{ seq -2 2 2 }} → [-2 0 2] +``` + +A contrived example of iterating over a sequence of integers: + +```go-html-template +{{ $product := 1 }} +{{ range seq 4 }} + {{ $product = mul $product . }} +{{ end }} +{{ $product }} → 24 +``` + +> [!note] - > The slice created by the `seq` function is limited to 2000 elements. ++> The slice created by this function is limited to 1 million elements. diff --cc docs/content/en/functions/collections/Shuffle.md index 60af0a1ba,000000000..d346a644d mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Shuffle.md +++ b/docs/content/en/functions/collections/Shuffle.md @@@ -1,29 -1,0 +1,35 @@@ +--- +title: collections.Shuffle +description: Returns a random permutation of a given array or slice. +categories: [] - keywords: [] ++keywords: [random] +params: + functions_and_methods: + aliases: [shuffle] + returnType: any + signatures: [collections.Shuffle COLLECTION] +aliases: [/functions/shuffle] +--- + +```go-html-template +{{ collections.Shuffle (slice "a" "b" "c") }} → [b a c] +``` + +The result will vary from one build to the next. + +To render an unordered list of 5 random pages from a page collection: + +```go-html-template +

    + {{ $p := site.RegularPages }} + {{ range $p | collections.Shuffle | first 5 }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` ++ ++{{< new-in 0.149.0 />}} ++ ++Using the [`collections.D`][] function for the same task is significantly faster. ++ ++[`collections.D`]: /functions/collections/D/ diff --cc docs/content/en/functions/compare/Default.md index f8bd06f06,000000000..5925f7750 mode 100644,000000..100644 --- a/docs/content/en/functions/compare/Default.md +++ b/docs/content/en/functions/compare/Default.md @@@ -1,47 -1,0 +1,47 @@@ +--- +title: compare.Default +description: Returns the second argument if set, else the first argument. +keywords: [] +params: + functions_and_methods: + aliases: [default] + returnType: any + signatures: [compare.Default DEFAULT INPUT] +aliases: [/functions/default] +--- + +The `default` function returns the second argument if set, else the first argument. + +> [!note] +> When the second argument is the boolean `false` value, the `default` function returns `false`. All _other_ falsy values are considered unset. +> +> The falsy values are `false`, `0`, any `nil` pointer or interface value, any array, slice, map, or string of length zero, and zero `time.Time` values. +> +> Everything else is truthy. +> +> To set a default value based on truthiness, use the [`or`] operator instead. + +The `default` function returns the second argument if set: + +```go-html-template +{{ default 42 1 }} → 1 +{{ default 42 "foo" }} → foo +{{ default 42 (dict "k" "v") }} → map[k:v] +{{ default 42 (slice "a" "b") }} → [a b] +{{ default 42 true }} → true + + +{{ default 42 false }} → false +``` + +The `default` function returns the first argument if the second argument is not set: + +```go-html-template +{{ default 42 0 }} → 42 +{{ default 42 "" }} → 42 +{{ default 42 dict }} → 42 +{{ default 42 slice }} → 42 - {{ default 42 }} → 42 ++{{ default 42 nil }} → 42 +``` + +[`or`]: /functions/go-template/or/ diff --cc docs/content/en/functions/css/Quoted.md index 000000000,000000000..ef3ff65a6 new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/css/Quoted.md @@@ -1,0 -1,0 +1,73 @@@ ++--- ++title: css.Quoted ++description: Returns the given string, setting its data type to indicate that it must be quoted when used in CSS. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ aliases: [] ++ returnType: css.QuotedString ++ signatures: [css.Quoted STRING] ++--- ++ ++ ++ ++> [!note] ++> This function is only applicable to the [`vars`] option passed to the [`css.Sass`] function. ++ ++When 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` function to explicitly indicate that the value must be treated as a quoted string. ++ ++For example: ++ ++```scss {file="assets/sass/main.scss"} ++@use "hugo:vars" as h; ++ ++ol li::after { ++ content: h.$ol-li-after; ++} ++ ++ul li::after { ++ content: h.$ul-li-after; ++} ++``` ++ ++```go-html-template {file="layouts/_partials/css.html"} ++{{ $vars := dict ++ "ol_li_after" ("6" | css.Quoted ) ++ "ul_li_after" ("7" | css.Quoted ) ++}} ++ ++{{ with resources.Get "sass/main.scss" }} ++ {{ $opts := dict ++ "enableSourceMap" hugo.IsDevelopment ++ "outputStyle" (cond hugo.IsDevelopment "expanded" "compressed") ++ "targetPath" "css/main.css" ++ "transpiler" "dartsass" ++ "vars" $vars ++ }} ++ {{ with . | toCSS $opts }} ++ {{ if hugo.IsDevelopment }} ++ ++ {{ else }} ++ {{ with . | fingerprint }} ++ ++ {{ end }} ++ {{ end }} ++ {{ end }} ++{{ end }} ++``` ++ ++The Sass code is transpiled to: ++ ++```css {file="public/css/main.css"} ++ol li::after { ++ content: "6"; ++} ++ ++ul li::after { ++ content: "7"; ++} ++``` ++ ++[`css.Sass`]: /functions/css/sass/ ++[`vars`]: /functions/css/sass/#vars diff --cc docs/content/en/functions/css/Sass.md index 4bce2fd06,000000000..c02b4ee42 mode 100644,000000..100644 --- a/docs/content/en/functions/css/Sass.md +++ b/docs/content/en/functions/css/Sass.md @@@ -1,152 -1,0 +1,159 @@@ +--- +title: css.Sass +description: Transpiles Sass to CSS. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [toCSS] + returnType: resource.Resource + signatures: ['css.Sass [OPTIONS] RESOURCE'] +--- + +{{< new-in 0.128.0 />}} + +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. + - Sass has two forms of syntax: [SCSS] and [indented]. Hugo supports both. - - [scss]: https://sass-lang.com/documentation/syntax#scss - [indented]: https://sass-lang.com/documentation/syntax#the-indented-syntax ++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. ++: (`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`. + +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 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]. ++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. ++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 platform like GitHub Pages, GitLab Pages, or Netlify, 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 sites configuration. + +By committing the `resources` directory, you're providing the pre-built CSS files directly to your CI/CD service, so it doesn't need to run the Sass compilation itself. + - For examples of how to install Dart Sass in a production environment, see the following workflow files: ++For examples of how to install Dart Sass in a production environment, see these hosting guides: + ++- [Cloudflare] +- [GitHub Pages] +- [GitLab Pages] +- [Netlify] ++- [Render] ++- [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 - [dart sass]: https://sass-lang.com/dart-sass - [GitHub Pages]: /host-and-deploy/host-on-github-pages/#step-7 - [GitLab Pages]: /host-and-deploy/host-on-gitlab-pages/#configure-gitlab-cicd - [libsass]: https://sass-lang.com/libsass - [Netlify]: /host-and-deploy/host-on-netlify/#configuration-file ++[Cloudflare]: /host-and-deploy/host-on-cloudflare/ ++[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 - [snap package]: /installation/linux/#snap ++[SCSS]: https://sass-lang.com/documentation/syntax#scss +[snapcraft.io]: https://snapcraft.io/dart-sass ++[Vercel]: /host-and-deploy/host-on-vercel/ diff --cc docs/content/en/functions/css/Unquoted.md index 000000000,000000000..c47059b7b new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/css/Unquoted.md @@@ -1,0 -1,0 +1,73 @@@ ++--- ++title: css.Unquoted ++description: Returns the given string, setting its data type to indicate that it must not be quoted when used in CSS. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ aliases: [] ++ returnType: css.UnquotedString ++ signatures: [css.Unquoted STRING] ++--- ++ ++ ++ ++> [!note] ++> This function is only applicable to the [`vars`] option passed to the [`css.Sass`] function. ++ ++When 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.Unquoted` function to explicitly indicate that the value must not be treated as a quoted string. ++ ++For example: ++ ++```scss {file="assets/sass/main.scss"} ++@use "hugo:vars" as h; ++ ++h1 { ++ font-size: h.$font-size-h1; ++} ++ ++h2 { ++ font-size: h.$font-size-h2; ++} ++``` ++ ++```go-html-template {file="layouts/_partials/css.html"} ++{{ $vars := dict ++ "font_size_h1" ("72px * 0.500" | css.Unquoted) ++ "font_size_h2" ("72px * 0.375" | css.Unquoted) ++}} ++ ++{{ with resources.Get "sass/main.scss" }} ++ {{ $opts := dict ++ "enableSourceMap" hugo.IsDevelopment ++ "outputStyle" (cond hugo.IsDevelopment "expanded" "compressed") ++ "targetPath" "css/main.css" ++ "transpiler" "dartsass" ++ "vars" $vars ++ }} ++ {{ with . | toCSS $opts }} ++ {{ if hugo.IsDevelopment }} ++ ++ {{ else }} ++ {{ with . | fingerprint }} ++ ++ {{ end }} ++ {{ end }} ++ {{ end }} ++{{ end }} ++``` ++ ++The Sass rules are transpiled to: ++ ++```css {file="public/css/main.css"} ++h1 { ++ font-size: 36px; ++} ++ ++h2 { ++ font-size: 27px; ++} ++``` ++ ++[`css.Sass`]: /functions/css/sass/ ++[`vars`]: /functions/css/sass/#vars diff --cc docs/content/en/functions/debug/Timer.md index 74395b130,000000000..4d4b02650 mode 100644,000000..100644 --- a/docs/content/en/functions/debug/Timer.md +++ b/docs/content/en/functions/debug/Timer.md @@@ -1,37 -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] +--- + - {{< new-in 0.120.0 />}} - +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 +``` + +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/debug/VisualizeSpaces.md index 000000000,000000000..39b9158d1 new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/debug/VisualizeSpaces.md @@@ -1,0 -1,0 +1,17 @@@ ++--- ++title: debug.VisualizeSpaces ++description: Returns the given string with spaces replaced by a visible string. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ aliases: [] ++ returnType: string ++ signatures: [debug.VisualizeSpaces STRING] ++--- ++ ++ ++ ++```go-html-template ++{{ debug.VisualizeSpaces "foo bar" }} → foo[SPACE][SPACE]bar ++``` diff --cc docs/content/en/functions/diagrams/Goat.md index 5f6fcf1da,000000000..3802b46fd mode 100644,000000..100644 --- a/docs/content/en/functions/diagrams/Goat.md +++ b/docs/content/en/functions/diagrams/Goat.md @@@ -1,115 -1,0 +1,115 @@@ +--- +title: diagrams.Goat +description: Returns an SVGDiagram object created from the given GoAT markup and options. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: diagrams.SVGDiagram + signatures: [diagrams.Goat MARKUP] +--- + +Useful in a [code block render hook], the `diagrams.Goat` function returns an SVGDiagram object created from the given [GoAT] markup. + +## Methods + +The SVGDiagram object has the following methods: + +Inner +: (`template.HTML`) Returns the SVG child elements without a wrapping `svg` element, allowing you to create your own wrapper. + +Wrapped +: (`template.HTML`) Returns the SVG child elements wrapped in an `svg` element. + +Width +: (`int`) Returns the width of the rendered diagram, in pixels. + +Height +: (`int`) Returns the height of the rendered diagram, in pixels. + +## GoAT Diagrams + +Hugo natively supports GoAT diagrams with an [embedded code block render hook]. + +This Markdown: + +````text +```goat +.---. .-. .-. .-. .---. +| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B | +'---' '-' '+' '+' '---' +``` +```` + +Is rendered to: + +```html +
+ + ... + +
+``` + +Which appears in your browser as: + +```goat {class="mw6-ns"} +.---. .-. .-. .-. .---. +| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B | +'---' '-' '+' '+' '---' +``` + +To customize rendering, override Hugo's [embedded code block render hook] for GoAT diagrams. + +## Code block render hook + +By way of example, let's create a code block render hook to render GoAT diagrams as `figure` elements with an optional caption. + +```go-html-template {file="layouts/_markup/render-codeblock-goat.html"} +{{ $caption := or .Attributes.caption "" }} +{{ $class := or .Attributes.class "diagram" }} +{{ $id := or .Attributes.id (printf "diagram-%d" (add 1 .Ordinal)) }} + +
+ {{ with diagrams.Goat (trim .Inner "\n\r") }} + + {{ .Inner }} + + {{ end }} +
{{ $caption }}
+
+``` + +This Markdown: + +````text {file="content/example.md" } +```goat {class="foo" caption="Diagram 1: Example"} +.---. .-. .-. .-. .---. +| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B | +'---' '-' '+' '+' '---' +``` +```` + +Is rendered to: + +```html +
+ + ... + +
Diagram 1: Example
+
+``` + +Use CSS to style the SVG as needed: + +```css +svg.foo { + font-family: "Segoe UI","Noto Sans",Helvetica,Arial,sans-serif +} +``` + +[code block render hook]: /render-hooks/code-blocks/ - [embedded code block render hook]: {{% eturl render-codeblock-goat %}} ++[embedded code block render hook]: <{{% eturl render-codeblock-goat %}}> +[GoAT]: https://github.com/bep/goat diff --cc docs/content/en/functions/fmt/Println.md index b7fe608ff,000000000..6bcda3b1c mode 100644,000000..100644 --- a/docs/content/en/functions/fmt/Println.md +++ b/docs/content/en/functions/fmt/Println.md @@@ -1,16 -1,0 +1,17 @@@ +--- +title: fmt.Println +description: Prints the default representation of the given argument using the standard `fmt.Print` function and enforces a line break. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [println] + returnType: string + signatures: [fmt.Println INPUT] +aliases: [/functions/println] +--- + +```go-html-template +{{ println "foo" }} → foo\n ++{{ println "foo" "bar" }} → foo bar\n +``` diff --cc docs/content/en/functions/hugo/Generator.md index 176d8e6bf,000000000..1070d27ac 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/IsDevelopment.md index cea923acd,000000000..2392c54ea mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/IsDevelopment.md +++ b/docs/content/en/functions/hugo/IsDevelopment.md @@@ -1,17 -1,0 +1,15 @@@ +--- +title: hugo.IsDevelopment +description: Reports whether the current running environment is "development". +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: bool + signatures: [hugo.IsDevelopment] +--- + - {{< new-in 0.120.0 />}} - +```go-html-template +{{ hugo.IsDevelopment }} → true/false +``` diff --cc docs/content/en/functions/hugo/IsServer.md index 840ff060d,000000000..771d4eb71 mode 100644,000000..100644 --- a/docs/content/en/functions/hugo/IsServer.md +++ b/docs/content/en/functions/hugo/IsServer.md @@@ -1,17 -1,0 +1,15 @@@ +--- +title: hugo.IsServer +description: Reports whether the built-in development server is running. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: bool + signatures: [hugo.IsServer] +--- + - {{< new-in 0.120.0 />}} - +```go-html-template +{{ hugo.IsServer }} → true/false +``` diff --cc docs/content/en/functions/hugo/Version.md index 33827737a,000000000..babd4238a 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.148.0 ++{{ hugo.Version }} → 0.152.2 +``` diff --cc docs/content/en/functions/images/AutoOrient.md index fd8d2ed14,000000000..4563e69f2 mode 100644,000000..100644 --- a/docs/content/en/functions/images/AutoOrient.md +++ b/docs/content/en/functions/images/AutoOrient.md @@@ -1,48 -1,0 +1,46 @@@ +--- +title: images.AutoOrient +description: Returns an image filter that rotates and flips an image as needed per its EXIF orientation tag. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: images.filter + signatures: [images.AutoOrient] +--- + - {{< new-in 0.121.2 />}} - +## Usage + +Create the filter: + +```go-html-template +{{ $filter := images.AutoOrient }} +``` + +{{% include "/_common/functions/images/apply-image-filter.md" %}} + +> [!note] +> When using with other filters, specify `images.AutoOrient` first. + +```go-html-template +{{ $filters := slice + images.AutoOrient + (images.Process "resize 200x") +}} +{{ with resources.Get "images/original.jpg" }} + {{ with images.Filter $filters . }} + + {{ end }} +{{ end }} +``` + +## Example + +{{< img + src="images/examples/landscape-exif-orientation-5.jpg" + alt="Zion National Park" + filter="AutoOrient" + filterArgs="" + example=true +>}} diff --cc docs/content/en/functions/images/Opacity.md index b9dcf3fd2,000000000..2105aea78 mode 100644,000000..100644 --- a/docs/content/en/functions/images/Opacity.md +++ b/docs/content/en/functions/images/Opacity.md @@@ -1,49 -1,0 +1,47 @@@ +--- +title: images.Opacity +description: Returns an image filter that changes the opacity of an image. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: images.filter + signatures: [images.Opacity OPACITY] +--- + - {{< new-in 0.119.0 />}} - +The opacity value must be in the range [0, 1]. A value of `0` produces a transparent image, and a value of `1` produces an opaque image (no transparency). + +## Usage + +Create the filter: + +```go-html-template +{{ $filter := images.Opacity 0.65 }} +``` + +{{% include "/_common/functions/images/apply-image-filter.md" %}} + +The `images.Opacity` filter is most useful for target formats such as PNG and WebP that support transparency. If the source image does not support transparency, combine this filter with the `images.Process` filter: + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ $filters := slice + (images.Opacity 0.65) + (images.Process "png") + }} + {{ with . | images.Filter $filters }} + + {{ end }} +{{ end }} +``` + +## Example + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Opacity" + filterArgs="0.65" + example=true +>}} diff --cc docs/content/en/functions/images/Padding.md index da15a44ca,000000000..8e6d05c01 mode 100644,000000..100644 --- a/docs/content/en/functions/images/Padding.md +++ b/docs/content/en/functions/images/Padding.md @@@ -1,72 -1,0 +1,70 @@@ +--- +title: images.Padding +description: Returns an image filter that resizes the image canvas without resizing the image. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: images.filter + signatures: ['images.Padding V1 [V2] [V3] [V4] [COLOR]'] +--- + - {{< new-in 0.120.0 />}} - +The last argument is the canvas color, expressed as an RGB or RGBA [hexadecimal color]. The default value is `ffffffff` (opaque white). The preceding arguments are the padding values, in pixels, using the CSS [shorthand property] syntax. Negative padding values will crop the image. + +[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color +[shorthand property]: https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties#edges_of_a_box + +## Usage + +Create the filter: + +```go-html-template +{{ $filter := images.Padding 20 40 "#976941" }} +``` + +{{% include "/_common/functions/images/apply-image-filter.md" %}} + +Combine with the [`Colors`] method to create a border with one of the image's most dominant colors: + +[`Colors`]: /methods/resource/colors/ + +```go-html-template +{{ with resources.Get "images/original.jpg" }} + {{ $filter := images.Padding 20 40 (index .Colors 2) }} + {{ with . | images.Filter $filter }} + + {{ end }} +{{ end }} +``` + +## Example + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Padding" + filterArgs="20,40,20,40,#976941" + example=true +>}} + +## Other recipes + +This example resizes an image to 300px wide, converts it to the WebP format, adds 20px vertical padding and 50px horizontal padding, then sets the canvas color to dark green with 33% opacity. + +Conversion to WebP is required to support transparency. PNG and WebP images have an alpha channel; JPEG and GIF do not. + +```go-html-template +{{ $img := resources.Get "images/a.jpg" }} +{{ $filters := slice + (images.Process "resize 300x webp") + (images.Padding 20 50 "#0705") +}} +{{ $img = $img.Filter $filters }} +``` + +To add a 2px gray border to an image: + +```go-html-template +{{ $img = $img.Filter (images.Padding 2 "#777") }} +``` diff --cc docs/content/en/functions/images/Process.md index 134c40c5a,000000000..a5aefc74c mode 100644,000000..100644 --- a/docs/content/en/functions/images/Process.md +++ b/docs/content/en/functions/images/Process.md @@@ -1,110 -1,0 +1,108 @@@ +--- +title: images.Process +description: Returns an image filter that processes the given image using the given specification. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: images.filter + signatures: [images.Process SPEC] +--- + - {{< new-in 0.119.0 />}} - +This filter has the same options as the [`Process`] method on a `Resource` object, but using it as a filter may be more effective if you need to apply multiple filters to an image. + +[`Process`]: /methods/resource/process/ + +The process specification is a space-delimited, case-insensitive list of one or more of the following in any sequence: + +action +: Specify zero or one of `crop`, `fill`, `fit`, or `resize`. If you specify an action you must also provide dimensions. See [details](content-management/image-processing/#image-processing-methods). + +```go-html-template +{{ $filter := images.Process "resize 300x" }} +``` + +dimensions +: Required if you specify an action. Provide width _or_ height when using `resize`, else provide both width _and_ height. See [details](/content-management/image-processing/#dimensions). + +```go-html-template +{{ $filter := images.Process "crop 200x200" }} +``` + +anchor +: Use with the `crop` or `fill` action. Specify zero or one of `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`. Default is `Smart`. See [details](/content-management/image-processing/#anchor). + +```go-html-template +{{ $filter := images.Process "crop 200x200 center" }} +``` + +rotation +: Typically specify zero or one of `r90`, `r180`, or `r270`. Also supports arbitrary rotation angles. See [details](/content-management/image-processing/#rotation). + +```go-html-template +{{ $filter := images.Process "r90" }} +{{ $filter := images.Process "crop 200x200 center r90" }} +``` + +target format +: Specify zero or one of `gif`, `jpeg`, `png`, `tiff`, or `webp`. See [details](/content-management/image-processing/#target-format). + +```go-html-template +{{ $filter := images.Process "webp" }} +{{ $filter := images.Process "crop 200x200 center r90 webp" }} +``` + +quality +: Applicable to JPEG and WebP images. Optionally specify `qN` where `N` is an integer in the range [0, 100]. Default is `75`. See [details](/content-management/image-processing/#quality). + +```go-html-template +{{ $filter := images.Process "q50" }} +{{ $filter := images.Process "crop 200x200 center r90 webp q50" }} +``` + +hint +: Applicable to WebP images and equivalent to the `-preset` flag for the [`cwebp`] encoder. Specify zero or one of `drawing`, `icon`, `photo`, `picture`, or `text`. Default is `photo`. See [details](/content-management/image-processing/#hint). + +[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp + +```go-html-template +{{ $filter := images.Process "webp" "icon" }} +{{ $filter := images.Process "crop 200x200 center r90 webp q50 icon" }} +``` + +background color +: When converting a PNG or WebP with transparency to a format that does not support transparency, optionally specify a background color using a 3-digit or a 6-digit hexadecimal color code. Default is `#ffffff` (white). See [details](/content-management/image-processing/#background-color). + +```go-html-template +{{ $filter := images.Process "jpeg #000" }} +{{ $filter := images.Process "crop 200x200 center r90 q50 jpeg #000" }} +``` + +resampling filter +: Typically specify zero or one of `Box`, `Lanczos`, `CatmullRom`, `MitchellNetravali`, `Linear`, or `NearestNeighbor`. Other resampling filters are available. See [details](/content-management/image-processing/#resampling-filter). + +```go-html-template +{{ $filter := images.Process "resize 300x lanczos" }} +{{ $filter := images.Process "resize 300x r90 q50 jpeg #000 lanczos" }} +``` + +## Usage + +Create a filter: + +```go-html-template +{{ $filter := images.Process "resize 256x q40 webp" }} +``` + +{{% include "/_common/functions/images/apply-image-filter.md" %}} + +## Example + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Process" + filterArgs="resize 256x q40 webp" + example=true +>}} diff --cc docs/content/en/functions/js/Batch.md index 360f98656,000000000..9e6a33c88 mode 100644,000000..100644 --- a/docs/content/en/functions/js/Batch.md +++ b/docs/content/en/functions/js/Batch.md @@@ -1,306 -1,0 +1,308 @@@ +--- +title: js.Batch +description: Build JavaScript bundle groups with global code splitting and flexible hooks/runners setup. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: js.Batcher + signatures: ['js.Batch [ID]'] +--- + +> [!note] +> For a runnable example of this feature, see [this test and demo repo](https://github.com/bep/hugojsbatchdemo/). + +The Batch `ID` is used to create the base directory for this batch. Forward slashes are allowed. `js.Batch` returns an object with an API with this structure: + +- [Group] + - [Script] + - [SetOptions] + - [Instance] + - [SetOptions] + - [Runner] + - [SetOptions] + - [Config] + - [SetOptions] + +## Group + +The `Group` method take an `ID` (`string`) as argument. No slashes. It returns an object with these methods: + +### Script + +The `Script` method takes an `ID` (`string`) as argument. No slashes. It returns an [OptionsSetter] that can be used to set [script options] for this script. + +```go-html-template +{{ with js.Batch "js/mybatch" }} + {{ with .Group "mygroup" }} + {{ with .Script "myscript" }} + {{ .SetOptions (dict "resource" (resources.Get "myscript.js")) }} + {{ end }} + {{ end }} +{{ end }} +``` + +`SetOptions` takes a [script options] map. Note that if you want the script to be handled by a [runner], you need to set the `export` option to match what you want to pass on to the runner (default is `*`). + +### Instance + +The `Instance` method takes two `string` arguments `SCRIPT_ID` and `INSTANCE_ID`. No slashes. It returns an [OptionsSetter] that can be used to set [params options] for this instance. + +```go-html-template +{{ with js.Batch "js/mybatch" }} + {{ with .Group "mygroup" }} + {{ with .Instance "myscript" "myinstance" }} + {{ .SetOptions (dict "params" (dict "param1" "value1")) }} + {{ end }} + {{ end }} +{{ end }} +``` + +`SetOptions` takes a [params options] map. The instance options will be passed to any [runner] script in the same group, as JSON. + +### Runner + +The `Runner` method takes an `ID` (`string`) as argument. No slashes. It returns an [OptionsSetter] that can be used to set [script options] for this runner. + +```go-html-template +{{ with js.Batch "js/mybatch" }} + {{ with .Group "mygroup" }} + {{ with .Runner "myrunner" }} + {{ .SetOptions (dict "resource" (resources.Get "myrunner.js")) }} + {{ end }} + {{ end }} +{{ end }} +``` + +`SetOptions` takes a [script options] map. + +The runner will receive a data structure with all instances for that group with a live binding of the [JavaScript import] of the defined `export`. + +The runner script's export must be a function that takes one argument, the group data structure. An example of a group data structure as JSON is: + +```json +{ + "id": "leaflet", + "scripts": [ + { + "id": "mapjsx", + "binding": JAVASCRIPT_BINDING, + "instances": [ + { + "id": "0", + "params": { + "c": "h-64", + "lat": 48.8533173846729, + "lon": 2.3497416090232535, + "r": "map.jsx", + "title": "Cathédrale Notre-Dame de Paris", + "zoom": 23 + } + }, + { + "id": "1", + "params": { + "c": "h-64", + "lat": 59.96300872062237, + "lon": 10.663529183196863, + "r": "map.jsx", + "title": "Holmenkollen", + "zoom": 3 + } + } + ] + } + ] +} +``` + +Below is an example of a runner script that uses React to render elements. Note that the export (`default`) must match the `export` option in the [script options] (`default` is the default value for runner scripts) (runnable versions of examples on this page can be found at [js.Batch Demo Repo]): + +```js +import * as ReactDOM from 'react-dom/client'; +import * as React from 'react'; + +export default function Run(group) { + console.log('Running react-create-elements.js', group); + const scripts = group.scripts; + for (const script of scripts) { + for (const instance of script.instances) { + /* This is a convention in this project. */ + let elId = `${script.id}-${instance.id}`; + let el = document.getElementById(elId); + if (!el) { + console.warn(`Element with id ${elId} not found`); + continue; + } + const root = ReactDOM.createRoot(el); + const reactEl = React.createElement(script.binding, instance.params); + root.render(reactEl); + } + } +} +``` + +### Config + +Returns an [OptionsSetter] that can be used to set [build options] for the batch. + +These are mostly the same as for `js.Build`, but note that: + +- `targetPath` is set automatically (there may be multiple outputs). - - ``format` must be `esm`, currently the only format supporting [code splitting]. - - ``params` will be available in the `@params/config` namespace in the scripts. This way you can import both the [script] or [runner] params and the [config] params with: ++- `format` must be `esm`, currently the only format supporting [code splitting]. ++- `params` will be available in the `@params/config` namespace in the scripts. This way you can import both the [script] or [runner] params and the [config] params with: + +```js +import * as params from "@params"; +import * as config from "@params/config"; +``` + +Setting the `Config` for a batch can be done from any template (including _shortcode_ templates), but will only be set once (the first will win): + +```go-html-template +{{ with js.Batch "js/mybatch" }} + {{ with .Config }} + {{ .SetOptions (dict + "target" "es2023" + "format" "esm" + "jsx" "automatic" + "loaders" (dict ".png" "dataurl") + "minify" true + "params" (dict "param1" "value1") + ) + }} + {{ end }} +{{ end }} +``` + +## Options + +### Build options + +format +: (`string`) Currently only `esm` is supported in ESBuild's [code splitting]. + +{{% include "/_common/functions/js/options.md" %}} + +### Script options + +resource +: The resource to build. This can be a file resource or a virtual resource. + +export +: The export to bind the runner to. Set it to `*` to export the [entire namespace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import). Default is `default` for [runner] scripts and `*` for other [scripts](#script). + +importContext +: An additional context for resolving imports. Hugo will always check this one first before falling back to `assets` and `node_modules`. A common use of this is to resolve imports inside a page bundle. See [import context](#import-context). + +params +: A map of parameters that will be passed to the script as JSON. These gets bound to the `@params` namespace: + + ```js + import * as params from '@params'; + ``` + +### Params options + +params +: A map of parameters that will be passed to the script as JSON. + +### Import context + +Hugo will, by default, first try to resolve any import in [assets](/hugo-pipes/introduction/#asset-directory) and, if not found, let [ESBuild] resolve it (e.g. from `node_modules`). The `importContext` option can be used to set the first context for resolving imports. A common use of this is to resolve imports inside a [page bundle](/content-management/page-bundles/). + +```go-html-template +{{ $common := resources.Match "/js/headlessui/*.*" }} +{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }} +``` + +You can pass any object that implements [Resource.Get](/methods/page/resources/#get). Pass a slice to set multiple contexts. + +The example above uses [`Resources.Mount`] to resolve a directory inside `assets` relative to the page bundle. + +### OptionsSetter + +An `OptionsSetter` is a special object that is returned once only. This means that you should wrap it with [with]: + +```go-html-template +{{ with .Script "myscript" }} + {{ .SetOptions (dict "resource" (resources.Get "myscript.js"))}} +{{ end }} +``` + +## Build + +The `Build` method returns an object with the following structure: + +- Groups (map) + - [`Resources`] + +Each [`Resource`] will be of media type `application/javascript` or `text/css`. + +In a template you would typically handle one group with a given `ID` (e.g. scripts for the current section). Because of the concurrent build, this needs to be done in a [`templates.Defer`] block: + +> [!note] +> The [`templates.Defer`] acts as a synchronisation point to handle scripts added concurrently by different templates. If you have a setup with where the batch is created in one go (in one template), you don't need it. +> +> See [this discussion](https://discourse.gohugo.io/t/js-batch-with-simple-global-script/53002/5?u=bep) for more. + +```go-html-template +{{ $group := .group }} +{{ with (templates.Defer (dict "key" $group "data" $group )) }} + {{ with (js.Batch "js/mybatch") }} + {{ with .Build }} + {{ with index .Groups $ }} + {{ range . }} + {{ $s := . }} + {{ if eq $s.MediaType.SubType "css" }} + + {{ else }} + + {{ end }} + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +## Known Issues + +In the official documentation for ESBuild's [code splitting], there's a warning note in the header. The two issues are: + +- `esm` is currently the only implemented output format. This means that it will not work for very old browsers. See [caniuse](https://caniuse.com/?search=ESM). +- There's a known import ordering issue. + +We have not seen the ordering issue as a problem during our [extensive testing](https://github.com/bep/hugojsbatchdemo) of this new feature with different libraries. There are two main cases: + +1. Undefined execution order of imports, see [this comment](https://github.com/evanw/esbuild/issues/399#issuecomment-1458680887) +1. Only one execution order of imports, see [this comment](https://github.com/evanw/esbuild/issues/399#issuecomment-735355932) + +Many would say that both of the above are [code smells](https://en.wikipedia.org/wiki/Code_smell). The first one has a simple workaround in Hugo. Define the import order in its own script and make sure it gets passed early to ESBuild, e.g. by putting it in a script group with a name that comes early in the alphabet. + +```js +import './lib2.js'; +import './lib1.js'; + +console.log('entrypoints-workaround.js'); +``` + +[`Resource`]: /methods/resource/ +[`Resources.Mount`]: /methods/page/resources/#mount +[`Resources`]: /methods/page/resources/ +[`templates.Defer`]: /functions/templates/defer/ +[build options]: #build-options +[code splitting]: https://esbuild.github.io/api/#splitting +[config]: #config +[ESBuild]: https://github.com/evanw/esbuild ++[group]: #group ++[instance]: #instance +[JavaScript import]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import +[js.Batch Demo Repo]: https://github.com/bep/hugojsbatchdemo/ +[OptionsSetter]: #optionssetter +[params options]: #params-options +[runner]: #runner +[script]: #script +[script options]: #script-options +[SetOptions]: #optionssetter +[with]: /functions/go-template/with/ diff --cc docs/content/en/functions/lang/Translate.md index 00bb0e3f3,000000000..92a10f016 mode 100644,000000..100644 --- a/docs/content/en/functions/lang/Translate.md +++ b/docs/content/en/functions/lang/Translate.md @@@ -1,246 -1,0 +1,245 @@@ +--- +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 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, use the `--printI18nWarnings` flag when building your site. +> - > 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 site 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: ++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/en-US.toml +``` + - The base name must match the [language key] as defined in your site configuration. ++The base name must match the [language key][] as defined in your site configuration. + - 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: ++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] describes the pluralization categories for each language. ++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: ++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". ++: (`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". ++: (`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". ++: (`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". ++: (`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". ++: (`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". ++: (`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 - [CLDR]: https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html - [CLDR Plural Rules chart]: https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html ++[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]: https://datatracker.ietf.org/doc/html/rfc5646 +[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7 diff --cc docs/content/en/functions/math/Rand.md index d659e651f,000000000..72338ac89 mode 100644,000000..100644 --- a/docs/content/en/functions/math/Rand.md +++ b/docs/content/en/functions/math/Rand.md @@@ -1,43 -1,0 +1,41 @@@ +--- +title: math.Rand +description: Returns a pseudo-random number in the half-open interval [0.0, 1.0). +categories: [] - keywords: [] ++keywords: [random] +params: + functions_and_methods: + aliases: [] + returnType: float64 + signatures: [math.Rand] +--- + - {{< new-in 0.121.2 />}} - +The `math.Rand` function returns a pseudo-random number in the half-open [interval](g) [0.0, 1.0). + +```go-html-template +{{ math.Rand }} → 0.6312770459590062 +``` + +To generate a random integer in the closed interval [0, 5]: + +```go-html-template +{{ math.Rand | mul 6 | math.Floor }} +``` + +To generate a random integer in the closed interval [1, 6]: + +```go-html-template +{{ math.Rand | mul 6 | math.Ceil }} +``` + +To generate a random float, with one digit after the decimal point, in the closed interval [0, 4.9]: + +```go-html-template +{{ div (math.Rand | mul 50 | math.Floor) 10 }} +``` + +To generate a random float, with one digit after the decimal point, in the closed interval [0.1, 5.0]: + +```go-html-template +{{ div (math.Rand | mul 50 | math.Ceil) 10 }} +``` diff --cc docs/content/en/functions/partials/IncludeCached.md index b80aaf8a1,000000000..a8a715783 mode 100644,000000..100644 --- a/docs/content/en/functions/partials/IncludeCached.md +++ b/docs/content/en/functions/partials/IncludeCached.md @@@ -1,57 -1,0 +1,57 @@@ +--- +title: partials.IncludeCached - description: Executes the given template and caches the result, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output. ++description: Executes the given template and caches the result, optionally passing one or more variant keys. If the partial template contains a return statement, returns the given value, else returns the rendered output. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [partialCached] + returnType: any + signatures: ['partials.IncludeCached LAYOUT CONTEXT [VARIANT...]'] +aliases: [/functions/partialcached] +--- + +Without a [`return`] statement, the `partialCached` function returns a string of type `template.HTML`. With a `return` statement, the `partialCached` function can return any data type. + +The `partialCached` function can offer significant performance gains for complex templates that don't need to be re-rendered on every invocation. + +> [!note] +> Each site (or language) has its own `partialCached` cache, so each site will execute a partial once. +> +> Hugo renders pages in parallel, and will render the partial more than once with concurrent calls to the `partialCached` function. After Hugo caches the rendered partial, new pages entering the build pipeline will use the cached result. + +Here is the simplest usage: + +```go-html-template +{{ partialCached "footer.html" . }} +``` + +Pass additional arguments to `partialCached` to create variants of the cached partial. For example, if you have a complex partial that should be identical when rendered for pages within the same section, use a variant based on section so that the partial is only rendered once per section: + +```go-html-template {file="layouts/baseof.html"} +{{ partialCached "footer.html" . .Section }} +``` + +Pass additional arguments, of any data type, as needed to create unique variants: + +```go-html-template +{{ partialCached "footer.html" . .Params.country .Params.province }} +``` + +The variant arguments are not available to the underlying _partial_ template; they are only used to create unique cache keys. + +To return a value from a _partial_ template, it must contain only one `return` statement, placed at the end of the template: + +```go-html-template +{{ $result := "" }} +{{ if math.ModBool . 2 }} + {{ $result = "even" }} +{{ else }} + {{ $result = "odd" }} +{{ end }} +{{ return $result }} +``` + +See [details][`return`]. + +[`return`]: /functions/go-template/return/ diff --cc docs/content/en/functions/resources/FromString.md index c86f90cbb,000000000..518511898 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": "2025-07-08T13:12:19-07:00", - "hugo_version": "0.148.0", ++ "hugo_version": "0.152.2", + "last_modified": "2025-07-07T22:09:13-07: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/strings/CountRunes.md index 8ad6b00da,000000000..3ac7baad7 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/CountRunes.md +++ b/docs/content/en/functions/strings/CountRunes.md @@@ -1,20 -1,0 +1,20 @@@ +--- +title: strings.CountRunes +description: Returns the number of runes in the given string excluding whitespace. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [countrunes] + returnType: int - signatures: [strings.CountRunes INPUT] ++ signatures: [strings.CountRunes STRING] +aliases: [/functions/countrunes] +--- + +In contrast with the [`strings.RuneCount`] function, which counts every rune in a string, `strings.CountRunes` excludes whitespace. + +```go-html-template +{{ "Hello, 世界" | strings.CountRunes }} → 8 +``` + +[`strings.RuneCount`]: /functions/strings/runecount/ diff --cc docs/content/en/functions/strings/CountWords.md index e50febf69,000000000..14939a7ea mode 100644,000000..100644 --- a/docs/content/en/functions/strings/CountWords.md +++ b/docs/content/en/functions/strings/CountWords.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: strings.CountWords +description: Returns the number of words in the given string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [countwords] + returnType: int - signatures: [strings.CountWords INPUT] ++ signatures: [strings.CountWords STRING] +aliases: [/functions/countwords] +--- + +```go-html-template +{{ "Hugo is a static site generator." | countwords }} → 6 +``` diff --cc docs/content/en/functions/strings/Repeat.md index b6027368e,000000000..d45216ab7 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/Repeat.md +++ b/docs/content/en/functions/strings/Repeat.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: strings.Repeat +description: Returns a new string consisting of zero or more copies of another string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: string - signatures: [strings.Repeat COUNT INPUT] ++ signatures: [strings.Repeat COUNT STRING] +aliases: [/functions/strings.repeat] +--- + +```go-html-template +{{ strings.Repeat 3 "yo" }} → yoyoyo +``` diff --cc docs/content/en/functions/strings/RuneCount.md index 8c0e24342,000000000..bdc1bfd2d mode 100644,000000..100644 --- a/docs/content/en/functions/strings/RuneCount.md +++ b/docs/content/en/functions/strings/RuneCount.md @@@ -1,20 -1,0 +1,20 @@@ +--- +title: strings.RuneCount +description: Returns the number of runes in the given string. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: int - signatures: [strings.RuneCount INPUT] ++ signatures: [strings.RuneCount STRING] +aliases: [/functions/strings.runecount] +--- + +In contrast with the [`strings.CountRunes`] function, which excludes whitespace, `strings.RuneCount` counts every rune in a string. + +```go-html-template +{{ "Hello, 世界" | strings.RuneCount }} → 9 +``` + +[`strings.CountRunes`]: /functions/strings/countrunes/ diff --cc docs/content/en/functions/strings/ToLower.md index c329b5e55,000000000..18ed6d456 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/ToLower.md +++ b/docs/content/en/functions/strings/ToLower.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: strings.ToLower +description: Returns the given string, converting all characters to lowercase. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [lower] + returnType: string - signatures: [strings.ToLower INPUT] ++ signatures: [strings.ToLower STRING] +aliases: [/functions/lower] +--- + +```go-html-template +{{ lower "BatMan" }} → batman +``` diff --cc docs/content/en/functions/strings/ToUpper.md index acccb4124,000000000..a3e8ff991 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/ToUpper.md +++ b/docs/content/en/functions/strings/ToUpper.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: strings.ToUpper +description: Returns the given string, converting all characters to uppercase. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [upper] + returnType: string - signatures: [strings.ToUpper INPUT] ++ signatures: [strings.ToUpper STRING] +aliases: [/functions/upper] +--- + +```go-html-template +{{ upper "BatMan" }} → BATMAN +``` diff --cc docs/content/en/functions/strings/Trim.md index 1afa0627f,000000000..edbdcc215 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/Trim.md +++ b/docs/content/en/functions/strings/Trim.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: strings.Trim +description: Returns the given string, removing leading and trailing characters specified in the cutset. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [trim] + returnType: string - signatures: [strings.Trim INPUT CUTSET] ++ signatures: [strings.Trim STRING CUTSET] +aliases: [/functions/trim] +--- + +```go-html-template +{{ trim "++foo--" "+-" }} → foo +``` diff --cc docs/content/en/functions/strings/TrimSpace.md index cb38b5ab1,000000000..77da321d3 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/TrimSpace.md +++ b/docs/content/en/functions/strings/TrimSpace.md @@@ -1,20 -1,0 +1,20 @@@ +--- +title: strings.TrimSpace +description: Returns the given string, removing leading and trailing whitespace as defined by Unicode. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: string - signatures: [strings.TrimSpace INPUT] ++ signatures: [strings.TrimSpace STRING] +--- + +{{< new-in 0.136.3 />}} + +Whitespace characters include `\t`, `\n`, `\v`, `\f`, `\r`, and characters in the [Unicode Space Separator] category. + +[Unicode Space Separator]: https://www.compart.com/en/unicode/category/Zs + +```go-html-template +{{ strings.TrimSpace "\n\r\t foo \n\r\t" }} → foo +``` diff --cc docs/content/en/functions/transform/CanHighlight.md index c00445605,000000000..5e3b04a81 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/CanHighlight.md +++ b/docs/content/en/functions/transform/CanHighlight.md @@@ -1,16 -1,0 +1,16 @@@ +--- +title: transform.CanHighlight +description: Reports whether the given code language is supported by the Chroma highlighter. +categories: [] - keywords: [] ++keywords: [highlight] +params: + functions_and_methods: + aliases: [] + returnType: bool + signatures: [transform.CanHighlight LANGUAGE] +--- + +```go-html-template +{{ transform.CanHighlight "go" }} → true +{{ transform.CanHighlight "klingon" }} → false +``` diff --cc docs/content/en/functions/transform/HTMLtoMarkdown.md index 000000000,000000000..1c05c7da2 new file mode 100644 --- /dev/null +++ b/docs/content/en/functions/transform/HTMLtoMarkdown.md @@@ -1,0 -1,0 +1,37 @@@ ++--- ++title: transform.HTMLToMarkdown ++description: Converts HTML to Markdown. ++categories: [] ++keywords: [] ++params: ++ functions_and_methods: ++ returnType: string ++ signatures: [transform.HTMLToMarkdown INPUT] ++--- ++ ++{{< new-in "0.151.0" />}} ++ ++> [!note] ++> This function is experimental and its API may change in the future. ++ ++The `transform.HTMLToMarkdown` function converts HTML to Markdown by utilizing the [`html-to-markdown`][] Go package. ++ ++## Usage ++ ++```go-html-template ++{{ .Content | transform.HTMLToMarkdown | safeHTML }} ++``` ++ ++## Plugins ++ ++The conversion process is enabled by the following `html-to-markdown` plugins: ++ ++Plugin|Description ++:--|:-- ++Base|Implements basic shared functionality ++CommonMark|Implements Markdown according to the [Commonmark Spec][] ++Table|Implements tables according to the [GitHub Flavored Markdown Spec][] ++ ++[`html-to-markdown`]: https://github.com/JohannesKaufmann/html-to-markdown?tab=readme-ov-file#readme ++[Commonmark Spec]: https://spec.commonmark.org/current/ ++[GitHub Flavored Markdown Spec]: https://github.github.com/gfm/ diff --cc docs/content/en/functions/transform/HighlightCodeBlock.md index bbebf9459,000000000..2fc0b6f37 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/HighlightCodeBlock.md +++ b/docs/content/en/functions/transform/HighlightCodeBlock.md @@@ -1,36 -1,0 +1,36 @@@ +--- +title: transform.HighlightCodeBlock +description: Highlights code received in context within a code block render hook. +categories: [] - keywords: [] ++keywords: [highlight] +params: + functions_and_methods: + aliases: [] + returnType: highlight.HighlightResult + signatures: ['transform.HighlightCodeBlock CONTEXT [OPTIONS]'] +--- + +This function is only useful within a code block render hook. + +Given the context passed into a code block render hook, `transform.HighlightCodeBlock` returns a `HighlightResult` object with two methods. + +.Wrapped +: (`template.HTML`) Returns highlighted code wrapped in `
`, `
`, and `` elements. This is identical to the value returned by the transform.Highlight function.
 +
 +.Inner
 +: (`template.HTML`) Returns highlighted code without any wrapping elements, allowing you to create your own wrapper.
 +
 +```go-html-template
 +{{ $result := transform.HighlightCodeBlock . }}
 +{{ $result.Wrapped }}
 +```
 +
 +To override the default [highlighting options]:
 +
 +```go-html-template
 +{{ $opts := merge .Options (dict "linenos" true) }}
 +{{ $result := transform.HighlightCodeBlock . $opts }}
 +{{ $result.Wrapped }}
 +```
 +
 +[highlighting options]: /functions/transform/highlight/#options
diff --cc docs/content/en/functions/transform/ToMath.md
index be62e8bce,000000000..22ae04dd5
mode 100644,000000..100644
--- a/docs/content/en/functions/transform/ToMath.md
+++ b/docs/content/en/functions/transform/ToMath.md
@@@ -1,171 -1,0 +1,182 @@@
 +---
 +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.
 +
 +[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.
 +
 +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}$$
 +
 +[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/transform/Unmarshal.md
index 8b2173b9b,000000000..7e9726749
mode 100644,000000..100644
--- a/docs/content/en/functions/transform/Unmarshal.md
+++ b/docs/content/en/functions/transform/Unmarshal.md
@@@ -1,372 -1,0 +1,371 @@@
 +---
 +title: transform.Unmarshal
 +description: Parses serialized data and returns a map or an array. Supports CSV, JSON, TOML, YAML, and XML.
 +categories: []
 +keywords: []
 +params:
 +  functions_and_methods:
 +    aliases: [unmarshal]
 +    returnType: any
 +    signatures: ['transform.Unmarshal [OPTIONS] INPUT']
 +aliases: [/functions/transform.unmarshal]
 +---
 +
 +The input can be a string or a [resource](g).
 +
++## Options
++
++delimiter
++: (`string`) Applicable to CSV files. The delimiter used. Default is `,`.
++
++comment
++: (`string`) Applicable to CSV files. The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.
++
++format
++: {{< new-in 0.149.0 />}}
++: (`string`) The serialization format of the input, one of `csv`, `json`, `org`, `toml`, `xml`, or `yaml`. If empty or unspecified, Hugo infers the format from the input. For resources, this option is only needed if the file lacks an extension or to override the inferred format. For strings, it's only required when the format is ambiguous.
++
++lazyQuotes
++: (`bool`) Applicable to CSV files. Whether to allow a quote in an unquoted field, or to allow a non-doubled quote in a quoted field. Default is `false`.
++
++targetType
++: {{< new-in 0.146.7 />}}
++: (`string`) Applicable to CSV files. The target data type, either `slice` or `map`. Default is `slice`.
++
 +## Unmarshal a string
 +
 +```go-html-template
 +{{ $string := `
 +title: Les Misérables
 +author: Victor Hugo
 +`}}
 +
 +{{ $book := unmarshal $string }}
 +{{ $book.title }} → Les Misérables
 +{{ $book.author }} → Victor Hugo
 +```
 +
 +## Unmarshal a resource
 +
 +Use the `transform.Unmarshal` function with global, page, and remote resources.
 +
 +### Global resource
 +
 +A global resource is a file within the `assets` directory, or within any directory mounted to the `assets` directory.
 +
 +```text
 +assets/
 +└── data/
 +    └── books.json
 +```
 +
 +```go-html-template
 +{{ $data := dict }}
 +{{ $path := "data/books.json" }}
 +{{ with resources.Get $path }}
 +  {{ with . | transform.Unmarshal }}
 +    {{ $data = . }}
 +  {{ end }}
 +{{ else }}
 +  {{ errorf "Unable to get global resource %q" $path }}
 +{{ end }}
 +
 +{{ range where $data "author" "Victor Hugo" }}
 +  {{ .title }} → Les Misérables
 +{{ end }}
 +```
 +
 +### Page resource
 +
 +A page resource is a file within a [page bundle].
 +
 +```text
 +content/
 +├── post/
 +│   └── book-reviews/
 +│       ├── books.json
 +│       └── index.md
 +└── _index.md
 +```
 +
 +```go-html-template
 +{{ $data := dict }}
 +{{ $path := "books.json" }}
 +{{ with .Resources.Get $path }}
 +  {{ with . | transform.Unmarshal }}
 +    {{ $data = . }}
 +  {{ end }}
 +{{ else }}
 +  {{ errorf "Unable to get page resource %q" $path }}
 +{{ end }}
 +
 +{{ range where $data "author" "Victor Hugo" }}
 +  {{ .title }} → Les Misérables
 +{{ end }}
 +```
 +
 +### Remote resource
 +
 +A remote resource is a file on a remote server, accessible via HTTP or HTTPS.
 +
 +```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 }}
 +
 +{{ range where $data "author" "Victor Hugo" }}
 +  {{ .title }} → Les Misérables
 +{{ 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 }}`
 +
 +## Working with CSV
 +
- ### Options
- 
- When unmarshaling a CSV file, provide an optional map of options.
- 
- delimiter
- : (`string`) The delimiter used. Default is `,`.
- 
- comment
- : (`string`) The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.
- 
- lazyQuotes
- : {{< new-in 0.122.0 />}}
- : (`bool`) Whether to allow a quote in an unquoted field, or to allow a non-doubled quote in a quoted field. Default is `false`.
- 
- targetType
- : {{< new-in 0.146.7 />}}
- : (`string`) The target data type, either `slice` or `map`. Default is `slice`.
- 
- ### Examples
- 
 +The examples below use this CSV file:
 +
 +```csv
 +"name","type","breed","age"
 +"Spot","dog","Collie",3
 +"Rover","dog","Boxer",5
 +"Felix","cat","Calico",7
 +```
 +
 +To render an HTML table from a CSV file:
 +
 +```go-html-template
 +{{ $data := slice }}
 +{{ $file := "pets.csv" }}
 +{{ with or (.Resources.Get $file) (resources.Get $file) }}
 +  {{ $opts := dict "targetType" "slice" }}
 +  {{ $data = transform.Unmarshal $opts . }}
 +{{ end }}
 +
 +{{ with $data }}
 +  
 +    
 +      
 +        {{ range index . 0 }}
 +          
 +        {{ end }}
 +      
 +    
 +    
 +      {{ range . | after 1 }}
 +        
 +          {{ range . }}
 +            
 +          {{ end }}
 +        
 +      {{ end }}
 +    
 +  
{{ . }}
{{ . }}
+{{ end }} +``` + +To extract a subset of the data, or to sort the data, unmarshal to a map instead of a slice: + +```go-html-template +{{ $data := dict }} +{{ $file := "pets.csv" }} +{{ with or (.Resources.Get $file) (resources.Get $file) }} + {{ $opts := dict "targetType" "map" }} + {{ $data = transform.Unmarshal $opts . }} +{{ end }} + +{{ with sort (where $data "type" "dog") "name" "asc" }} + + + + + + + + + + + {{ range . }} + + + + + + + {{ end }} + +
nametypebreedage
{{ .name }}{{ .type }}{{ .breed }}{{ .age }}
+{{ end }} +``` + +## Working with XML + +When unmarshaling an XML file, do not include the root node when accessing data. For example, after unmarshaling the RSS feed below, access the feed title with `$data.channel.title`. + +```xml + + + + Books on Example Site + https://example.org/books/ + Recent content in Books on Example Site + en-US + + + The Hunchback of Notre Dame + Written by Victor Hugo + https://example.org/books/the-hunchback-of-notre-dame/ + Mon, 09 Oct 2023 09:27:12 -0700 + https://example.org/books/the-hunchback-of-notre-dame/ + + + Les Misérables + Written by Victor Hugo + https://example.org/books/les-miserables/ + Mon, 09 Oct 2023 09:27:11 -0700 + https://example.org/books/les-miserables/ + + + +``` + +Get the remote data: + +```go-html-template +{{ $data := dict }} +{{ $url := "https://example.org/books/index.xml" }} +{{ 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 }} +``` + +Inspect the data structure: + +```go-html-template +
{{ debug.Dump $data }}
+``` + +List the book titles: + +```go-html-template +{{ with $data.channel.item }} +
    + {{ range . }} +
  • {{ .title }}
  • + {{ end }} +
+{{ end }} +``` + +Hugo renders this to: + +```html +
    +
  • The Hunchback of Notre Dame
  • +
  • Les Misérables
  • +
+``` + +### XML attributes and namespaces + +Let's add a `lang` attribute to the `title` nodes of our RSS feed, and a namespaced node for the ISBN number: + +```xml + + + + Books on Example Site + https://example.org/books/ + Recent content in Books on Example Site + en-US + + + The Hunchback of Notre Dame + Written by Victor Hugo + 9780140443530 + https://example.org/books/the-hunchback-of-notre-dame/ + Mon, 09 Oct 2023 09:27:12 -0700 + https://example.org/books/the-hunchback-of-notre-dame/ + + + Les Misérables + Written by Victor Hugo + 9780451419439 + https://example.org/books/les-miserables/ + Mon, 09 Oct 2023 09:27:11 -0700 + https://example.org/books/les-miserables/ + + + +``` + +After retrieving the remote data, inspect the data structure: + +```go-html-template +
{{ debug.Dump $data }}
+``` + +Each item node looks like this: + +```json +{ + "description": "Written by Victor Hugo", + "guid": "https://example.org/books/the-hunchback-of-notre-dame/", + "link": "https://example.org/books/the-hunchback-of-notre-dame/", + "number": "9780140443530", + "pubDate": "Mon, 09 Oct 2023 09:27:12 -0700", + "title": { + "#text": "The Hunchback of Notre Dame", + "-lang": "en" + } +} +``` + +The title keys do not begin with an underscore or a letter---they are not valid [identifiers](g). Use the [`index`] function to access the values: + +```go-html-template +{{ with $data.channel.item }} +
    + {{ range . }} + {{ $title := index .title "#text" }} + {{ $lang := index .title "-lang" }} + {{ $ISBN := .number }} +
  • {{ $title }} ({{ $lang }}) {{ $ISBN }}
  • + {{ end }} +
+{{ end }} +``` + +Hugo renders this to: + +```html +
    +
  • The Hunchback of Notre Dame (en) 9780140443530
  • +
  • Les Misérables (fr) 9780451419439
  • +
+``` + +[`index`]: /functions/collections/indexfunction/ +[Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type +[page bundle]: /content-management/page-bundles/ diff --cc docs/content/en/functions/transform/XMLEscape.md index 372ad9b6a,000000000..dbe0b9334 mode 100644,000000..100644 --- a/docs/content/en/functions/transform/XMLEscape.md +++ b/docs/content/en/functions/transform/XMLEscape.md @@@ -1,40 -1,0 +1,38 @@@ +--- +title: transform.XMLEscape +description: Returns the given string, removing disallowed characters then escaping the result to its XML equivalent. +categories: [] +keywords: [] +params: + functions_and_methods: + aliases: [] + returnType: string + signatures: [transform.XMLEscape INPUT] +--- + - {{< new-in 0.121.0 />}} - +The `transform.XMLEscape` function removes [disallowed characters] as defined in the XML specification, then escapes the result by replacing the following characters with [HTML entities]: + +- `"` → `"` +- `'` → `'` +- `&` → `&` +- `<` → `<` +- `>` → `>` +- `\t` → ` ` +- `\n` → ` ` +- `\r` → ` ` + +For example: + +```go-html-template +{{ transform.XMLEscape "

abc

" }} → <p>abc</p> +``` + +When using `transform.XMLEscape` in a template rendered by Go's [html/template] package, declare the string to be safe HTML to avoid double escaping. For example, in an RSS template: + +```xml {file="layouts/rss.xml"} +{{ .Summary | transform.XMLEscape | safeHTML }} +``` + +[disallowed characters]: https://www.w3.org/TR/xml/#charsets +[html entities]: https://developer.mozilla.org/en-us/docs/glossary/entity +[html/template]: https://pkg.go.dev/html/template diff --cc docs/content/en/getting-started/quick-start.md index dfb78f42e,000000000..e7494a924 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,218 @@@ +--- +title: Quick start +description: Create a Hugo site in minutes. +categories: [] +keywords: [] +params: + minVersion: v0.128.0 +weight: 10 +aliases: [/quickstart/,/overview/quickstart/] +--- + +In this tutorial you will: + +1. Create a site +1. Add content +1. Configure the site +1. Publish the site + +## 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 + +### 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 +> +> 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. + +```text +hugo new site 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. + +### Explanation of commands + - Create the [directory structure] for your project in the `quickstart` directory. ++Create the [site skeleton] for your project in the `quickstart` directory. + +```text +hugo new site 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]. + +```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. + +```text +echo "theme = 'ananke'" >> hugo.toml +``` + +Start Hugo's development server to view the site. + +```text +hugo server +``` + +Press `Ctrl + C` to stop Hugo's development server. + +## Add content + +Add a new page to your site. + +```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]. + +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. + +```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. + +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. + +## Configure the site + +With your editor, open the [site configuration] file (`hugo.toml`) in the root of your project. + +```text +baseURL = 'https://example.org/' +languageCode = 'en-us' +title = 'My New Hugo Site' +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. + +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]. + +## Publish the site + +In this step you will _publish_ your site, 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. + +```text +hugo +``` + +To learn how to _deploy_ your site, 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. + +## 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. + +[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/ - [directory structure]: /getting-started/directory-structure/ ++[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 +[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 +[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 d6bc42550,000000000..8cbcc9b02 mode 100644,000000..100644 --- a/docs/content/en/getting-started/usage.md +++ b/docs/content/en/getting-started/usage.md @@@ -1,166 -1,0 +1,166 @@@ +--- +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.123.0-3c8a4713908e48e6523f058ca126710397aa4ed5+extended linux/amd64 BuildDate=2024-02-19T16:32:38Z VendorInfo=gohugoio ++hugo v0.152.2-6abdacad3f3fe944ea42177844469139e81feda6+extended linux/amd64 BuildDate=2025-10-24T15:31:49Z 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 + +To build your site, `cd` into your project directory and run: + +```sh +hugo +``` + +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. + +> [!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. +> +> 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 + +{{< new-in 0.123.0 />}} + +> [!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: + +```sh +hugo --buildDrafts # or -D +hugo --buildExpired # or -E +hugo --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. + +> [!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. +> +> 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. + +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 using a [CI/CD](g) workflow, where a push[^1] to their GitHub or GitLab repository triggers a build and deployment. Popular providers include [AWS Amplify], [CloudCannon], [Cloudflare Pages], [GitHub Pages], [GitLab Pages], and [Netlify]. + +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/ +[`publishDir`]: /configuration/all/#publishdir +[AWS Amplify]: https://aws.amazon.com/amplify/ +[build options]: /content-management/build-options/ +[CloudCannon]: https://cloudcannon.com/ +[Cloudflare Pages]: https://pages.cloudflare.com/ +[front matter]: /content-management/front-matter/ +[GitHub Pages]: https://pages.github.com/ +[GitLab Pages]: https://docs.gitlab.com/ee/user/project/pages/ +[host and deploy]: /host-and-deploy/ +[installing]: /installation/ +[LiveReload]: https://github.com/livereload/livereload-js +[Netlify]: https://www.netlify.com/ diff --cc docs/content/en/host-and-deploy/deploy-with-rsync.md index d073107fe,000000000..0ad64d6fb 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 < [!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: + + {{< 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.90.0 - GO_VERSION: 1.24.5 - HUGO_VERSION: 0.148.2 - NODE_VERSION: 22.18.0 ++ DART_SASS_VERSION: 1.96.0 ++ GO_VERSION: 1.25.5 ++ HUGO_VERSION: 0.152.2 ++ NODE_VERSION: 24.12.0 + TZ: Europe/Oslo + steps: + - name: Checkout + uses: actions/checkout@v5 + with: + submodules: recursive + fetch-depth: 0 + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version: ${{ env.GO_VERSION }} + cache: false + - name: Setup Node.js + uses: actions/setup-node@v4 + 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@v4 + with: + path: ${{ runner.temp }}/hugo_cache + key: hugo-${{ github.run_id }} + restore-keys: + hugo- + - name: Build the site + run: | + hugo \ + --gc \ + --minify \ + --baseURL "${{ steps.pages.outputs.base_url }}/" \ + --cacheDir "${{ runner.temp }}/hugo_cache" + - name: Cache save + id: cache-save + uses: actions/cache/save@v4 + 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 c43303804,000000000..e10c3aca1 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. + +## 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.90.0 - HUGO_VERSION: 0.148.2 - NODE_VERSION: 22.18.0 ++ DART_SASS_VERSION: 1.96.0 ++ HUGO_VERSION: 0.152.2 ++ NODE_VERSION: 24.12.0 + # Git + GIT_DEPTH: 0 + GIT_STRATEGY: clone + GIT_SUBMODULE_STRATEGY: recursive + # Time zone + TZ: Europe/Oslo + +image: - name: golang:1.24.5-bookworm ++ name: golang:1.25.5-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}" + + # 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 cc0bf6b2b,000000000..d2eeb2665 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,130 -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 - : Log in to your Netlify account, navigate to the Sites page, press the **Add new site** button, and choose "Import an existing project" from the dropdown menu. ++: Create a `netlify.toml` file in the root of your project. ++ ++ ```text {file="netlify.toml" copy=true} ++ [build.environment] ++ DART_SASS_VERSION = "1.96.0" ++ GO_VERSION = "1.25.5" ++ HUGO_VERSION = "0.152.2" ++ NODE_VERSION = "24.12.0" ++ TZ = "Europe/Oslo" ++ ++ [build] ++ publish = "public" ++ command = """\ ++ git config core.quotepath false && \ ++ hugo --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.96.0" ++ GO_VERSION = "1.25.5" ++ HUGO_VERSION = "0.152.2" ++ NODE_VERSION = "24.12.0" ++ 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}" ++ """ ++ ``` + +Step 2 - : Select your deployment method. - - ![screen capture](netlify-step-02.png) ++: Commit the changes to your local Git repository and push to your GitHub repository. + +Step 3 - : Authorize Netlify to connect with your GitHub account by pressing the **Authorize Netlify** button. ++: In the upper right corner of the Netlify dashboard, press the **Add new project** button and select “Import an existing project". + - ![screen capture](netlify-step-03.png) ++ ![screen capture](netlify-01.png) + +Step 4 - : Press the **Configure Netlify on GitHub** button. ++: Connect to GitHub. + - ![screen capture](netlify-step-04.png) ++ ![screen capture](netlify-02.png) + +Step 5 - : Install the Netlify app by selecting your GitHub account. ++: Press the "Authorize Netlify" button to allow the Netlify application to access your GitHub account. + - ![screen capture](netlify-step-05.png) ++ ![screen capture](netlify-03.png) + +Step 6 - : Press the **Install** button. - - ![screen capture](netlify-step-06.png) ++: Press the **Configure Netlify on GitHub** button. ++ ++ ![screen capture](netlify-04.png) + +Step 7 - : Click on the site's repository from the list. ++: Select the GitHub account where you want to install the Netlify application. + - ![screen capture](netlify-step-07.png) ++ ![screen capture](netlify-05.png) + +Step 8 - : Set the site name and branch from which to deploy. ++: Authorize the Netlify application to access all repositories or only select repositories, then press the Install button. + - ![screen capture](netlify-step-08.png) ++ ![screen capture](netlify-06.png) ++ ++Your browser will be redirected to the Netlify dashboard. + +Step 9 - : Define the build settings, press the **Add environment variables** button, then press the **New variable** button. ++: Click on the name of the repository you wish to import. + - ![screen capture](netlify-step-09.png) ++ ![screen capture](netlify-07.png) + +Step 10 - : Create a new environment variable named `HUGO_VERSION` and set the value to the [latest version](https://github.com/gohugoio/hugo/releases/latest). ++: 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-step-10.png) ++ ![screen capture](netlify-09.png) + +Step 11 - : Press the "Deploy my new site" button at the bottom of the page. - - ![screen capture](netlify-step-11.png) - - Step 12 - : At the bottom of the screen, wait for the deploy to complete, then click on the deploy log entry. - - ![screen capture](netlify-step-12.png) - - Step 13 - : Press the **Open production deploy** button to view the live site. - - ![screen capture](netlify-step-13.png) - - ## Configuration file - - In the procedure above we configured our site using the Netlify user interface. Most site owners find it easier to use a configuration file checked into source control. - - Create a new file named `netlify.toml` in the root of your project directory. In its simplest form, the configuration file might look like this: - - ```toml {file="netlify.toml"} - [build.environment] - GO_VERSION = "1.24.5" - HUGO_VERSION = "0.148.2" - NODE_VERSION = "22.18.0" - TZ = "Europe/Oslo" - - [build] - publish = "public" - command = """\ - git config core.quotepath false && \ - hugo --gc --minify --baseURL "${URL}" - """ - ``` - - If your site requires Dart Sass to transpile Sass to CSS, the configuration file should look something like this: - - ```toml {file="netlify.toml"} - [build.environment] - DART_SASS_VERSION = "1.90.0" - GO_VERSION = "1.24.5" - HUGO_VERSION = "0.148.2" - NODE_VERSION = "22.18.0" - 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}" - """ - ``` ++: 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-netlify/netlify-01.png index 000000000,000000000..5d09da9d4 new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-02.png index 000000000,000000000..0c76e1d3d new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-03.png index 000000000,000000000..5bfceabbe new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-04.png index 000000000,000000000..e059dcae4 new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-05.png index 000000000,000000000..ffb8b983f new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-06.png index 000000000,000000000..0bf5a29cb new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-07.png index 000000000,000000000..9842fac37 new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-08.png index 000000000,000000000..8d6874769 new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-09.png index 000000000,000000000..5807f6b2d new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-netlify/netlify-10.png index 000000000,000000000..0577a46fc new file mode 100644 Binary files differ diff --cc docs/content/en/host-and-deploy/host-on-render/index.md index f52e09280,000000000..b8d597b15 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.90.0 ++ value: 1.96.0 + - key: GO_VERSION - value: 1.24.5 ++ value: 1.25.5 + - key: HUGO_VERSION - value: 0.148.2 ++ value: 0.152.2 + - key: NODE_VERSION - value: 22.18.0 ++ value: 24.12.0 + - 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}" + + } + + 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 6b092fbf2,000000000..1d278f0fe 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,94 -1,0 +1,94 @@@ +--- +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. + +[`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: ++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/ ++[SourceHut personal access token]: https://meta.sr.ht/oauth2/personal-token +[hut]: https://sr.ht/~xenrox/hut/ + +```sh +hugo +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 + 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 8d402cb87,000000000..d93ab6040 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.90.0 - GO_VERSION=1.24.5 - HUGO_VERSION=0.148.2 - NODE_VERSION=22.18.0 ++ DART_SASS_VERSION=1.96.0 ++ GO_VERSION=1.25.5 ++ HUGO_VERSION=0.152.2 ++ NODE_VERSION=24.12.0 + + 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}" + + } + + 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/introduction.md index b45607dc0,000000000..ba1dd6a46 mode 100644,000000..100644 --- a/docs/content/en/hugo-modules/introduction.md +++ b/docs/content/en/hugo-modules/introduction.md @@@ -1,19 -1,0 +1,19 @@@ +--- +title: Introduction +description: A brief introduction to Hugo Modules. +categories: [] +keywords: [] +weight: 10 +--- + +Hugo uses modules as its fundamental organizational units. A module can be a full Hugo project or a smaller, reusable piece providing one or more of Hugo's seven component types: static files, content, layouts, data, assets, internationalization (i18n) resources, and archetypes. + +Modules are combinable in any arrangement, and external directories (including those from non-Hugo projects) can be mounted, effectively creating a single, unified file system. + +Some example projects: + - [https://github.com/bep/docuapi](https://github.com/bep/docuapi) - : A theme that has been ported to Hugo Modules while testing this feature. It is a good example of a non-Hugo-project mounted into Hugo's directory structure. It even shows a JS Bundler implementation in regular Go templates. ++ ++: A theme that has been ported to Hugo Modules while testing this feature. It is a good example of a non-Hugo-project mounted into Hugo's directory structure. + - [https://github.com/bep/my-modular-site](https://github.com/bep/my-modular-site) ++ +: A simple site used for testing. diff --cc docs/content/en/installation/linux.md index babb759ea,000000000..0ce751d43 mode 100644,000000..100644 --- a/docs/content/en/installation/linux.md +++ b/docs/content/en/installation/linux.md @@@ -1,218 -1,0 +1,219 @@@ +--- +title: Linux +description: Install Hugo on Linux. +categories: [] +keywords: [] +weight: 20 +--- + +## Editions + +{{% include "/_common/installation/01-editions.md" %}} + +Unless your specific deployment needs require the extended/deploy edition, we recommend the extended edition. + +{{% include "/_common/installation/02-prerequisites.md" %}} + +{{% include "/_common/installation/03-prebuilt-binaries.md" %}} + +## Package managers + +### Snap + +[Snap] is a free and open-source package manager for Linux. Available for [most distributions], snap packages are simple to install and are automatically updated. + +The Hugo snap package is [strictly confined]. Strictly confined snaps run in complete isolation, up to a minimal access level that's deemed always safe. The sites you create and build must be located within your home directory, or on removable media. + +To install the extended edition of Hugo: + +```sh +sudo snap install hugo +``` + +To control automatic updates: + +```sh +# disable automatic updates +sudo snap refresh --hold hugo + +# enable automatic updates +sudo snap refresh --unhold hugo +``` + +To control access to removable media: + +```sh +# allow access +sudo snap connect hugo:removable-media + +# revoke access +sudo snap disconnect hugo:removable-media +``` + +To control access to SSH keys: + +```sh +# allow access +sudo snap connect hugo:ssh-keys + +# revoke access +sudo snap disconnect hugo:ssh-keys +``` + +{{% 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. ++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/ +[most distributions]: https://snapcraft.io/docs/installing-snapd +[MX Linux]: https://mxlinux.org/ +[openSUSE]: https://www.opensuse.org/ +[Pop!_OS]: https://pop.system76.com/ +[Red Hat Enterprise Linux]: https://www.redhat.com/ +[Snap]: https://snapcraft.io/ +[Solus]: https://getsol.us/ +[strictly confined]: https://snapcraft.io/docs/snap-confinement +[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/menu-entry/PageRef.md index 5fc2dfcae,000000000..31db24de0 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] +--- + - The use case for this method is rare. - - In almost also scenarios you should use the [`URL`] method instead. ++> [!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 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. + +[`HasMenuCurrent`]: /methods/page/hasmenucurrent/ +[`IsMenuCurrent`]: /methods/page/ismenucurrent/ +[`Page`]: /methods/menu-entry/page/ +[`URL`]: /methods/menu-entry/url/ +[defining a menu entry]: /content-management/menus/#define-in-site-configuration diff --cc docs/content/en/methods/page/IsNode.md index 194a2cac8,000000000..24e7c033e mode 100644,000000..100644 --- a/docs/content/en/methods/page/IsNode.md +++ b/docs/content/en/methods/page/IsNode.md @@@ -1,32 -1,0 +1,30 @@@ +--- +title: IsNode +description: Reports whether the given page is a node. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: bool + signatures: [PAGE.IsNode] +--- + - The `IsNode` method on a `Page` object returns `true` if the [page kind](g) is `home`, `section`, `taxonomy`, or `term`. - - It returns `false` is the page kind is `page`. ++The `IsNode` method on a `Page` object checks if the [page kind](g) is one of the following: `home`, `section`, `taxonomy`, or `term`. If it is, the method returns `true`, indicating the page is a [node](g). Otherwise, if the page kind is page, it returns `false`. + +```text +content/ +├── books/ +│ ├── book-1/ - │ │ └── index.md <-- kind = page, node = false - │ ├── book-2.md <-- kind = page, node = false - │ └── _index.md <-- kind = section, node = true - ├── tags/ - │ ├── fiction/ - │ │ └── _index.md <-- kind = term, node = true - │ └── _index.md <-- kind = taxonomy, node = true - └── _index.md <-- kind = home, node = true ++│ │ └── index.md <-- kind = page IsNode = false ++│ ├── book-2.md <-- kind = page IsNode = false ++│ └── _index.md <-- kind = section IsNode = true ++├── tags ++│ ├── fiction ++│ │ └── _index.md <-- kind = term IsNode = true ++│ └── _index.md <-- kind = taxonomy IsNode = true ++└── _index.md <-- kind = home IsNode = true +``` + +```go-html-template +{{ .IsNode }} +``` diff --cc docs/content/en/methods/page/Summary.md index 9158e571d,000000000..c72a2440d mode 100644,000000..100644 --- a/docs/content/en/methods/page/Summary.md +++ b/docs/content/en/methods/page/Summary.md @@@ -1,44 -1,0 +1,48 @@@ +--- +title: Summary +description: Returns the summary of the given page. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: template.HTML + signatures: [PAGE.Summary] +--- + + + + + + +You can define a [summary] manually, in front matter, or automatically. A manual summary takes precedence over a front matter summary, and a front matter summary takes precedence over an automatic summary. + +To list the pages in a section with a summary beneath each link: + +```go-html-template +{{ range .Pages }} +

{{ .LinkTitle }}

+ {{ .Summary }} +{{ end }} +``` + ++> [!warning] ++> Automatic `.Summary` may cut block tags (e.g., `blockquote`) in the middle, causing the browser to recover the end tag. See [automatic summary] for details and for ways to avoid this. ++ +Depending on content length and how you define the summary, the summary may be equivalent to the content itself. To determine whether the content length exceeds the summary length, use the [`Truncated`] method on a `Page` object. This is useful for conditionally rendering a “read more” link: + +```go-html-template +{{ range .Pages }} +

{{ .LinkTitle }}

+ {{ .Summary }} + {{ if .Truncated }} + Read more... + {{ end }} +{{ end }} +``` + +> [!note] +> The `Truncated` method returns `false` if you define the summary in front matter. + +[`Truncated`]: /methods/page/truncated +[summary]: /content-management/summaries/ ++[automatic summary]: /content-management/summaries/#automatic-summary diff --cc docs/content/en/methods/site/Home.md index 19ab61747,000000000..11ce617ef mode 100644,000000..100644 --- a/docs/content/en/methods/site/Home.md +++ b/docs/content/en/methods/site/Home.md @@@ -1,25 -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] +--- + - This method is useful for obtaining a link to the home page. ++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: + +{{< 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/taxonomy/ByCount.md index fbf9bb4a1,000000000..196b31769 mode 100644,000000..100644 --- a/docs/content/en/methods/taxonomy/ByCount.md +++ b/docs/content/en/methods/taxonomy/ByCount.md @@@ -1,69 -1,0 +1,69 @@@ +--- +title: ByCount +description: Returns an ordered taxonomy, sorted by the number of pages associated with each term. +categories: [] +keywords: [] +params: + functions_and_methods: + returnType: page.OrderedTaxonomy + signatures: [TAXONOMY.ByCount] +--- + - The `ByCount` method on a `Taxonomy` object returns an [ordered taxonomy](g), sorted by the number of pages associated with each [term](g). ++The `ByCount` method on a `Taxonomy` object returns an [ordered taxonomy](g), sorted by the number of pages associated with each [term](g), then sorted alphabetically by term in the event of a tie. + +While a `Taxonomy` object is a [map](g), an ordered taxonomy is a [slice](g), where each element is an object that contains the term and a slice of its [weighted pages](g). + +{{% include "/_common/methods/taxonomy/get-a-taxonomy-object.md" %}} + +## Get the ordered taxonomy + +Now that we have captured the “genres” Taxonomy object, let's get the ordered taxonomy sorted by the number of pages associated with each term: + +```go-html-template +{{ $taxonomyObject.ByCount }} +``` + +To reverse the sort order: + +```go-html-template +{{ $taxonomyObject.ByCount.Reverse }} +``` + +To inspect the data structure: + +```go-html-template +
{{ debug.Dump $taxonomyObject.ByCount }}
+``` + +{{% include "/_common/methods/taxonomy/ordered-taxonomy-element-methods.md" %}} + +## Example + +With this template: + +```go-html-template +{{ range $taxonomyObject.ByCount }} +

{{ .Page.LinkTitle }} ({{ .Count }})

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

suspense (3)

+ +

romance (2)

+ +``` diff --cc docs/content/en/quick-reference/glossary/archetype.md index 231089c56,000000000..d22fae954 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/archetype.md +++ b/docs/content/en/quick-reference/glossary/archetype.md @@@ -1,6 -1,0 +1,7 @@@ +--- +title: archetype - details: /content-management/archetypes ++params: ++ reference: /content-management/archetypes/ +--- + +An _archetype_ is a template for new content. diff --cc docs/content/en/quick-reference/glossary/component.md index 000000000,000000000..3c3c0236b new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/component.md @@@ -1,0 -1,0 +1,17 @@@ ++--- ++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: ++ ++ Component|Directory within the unified file system ++ :--|:-- ++ archetypes|`archetypes` ++ assets|`assets` ++ content|`content` ++ data|`data` ++ templates|`layouts` ++ translation tables|`i18n` ++ static files|`static` diff --cc docs/content/en/quick-reference/glossary/module.md index 90c8ff80b,000000000..30ec49ea4 mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/module.md +++ b/docs/content/en/quick-reference/glossary/module.md @@@ -1,6 -1,0 +1,5 @@@ +--- +title: module - reference: /hugo-modules/ +--- + - A _module_ is a packaged combination of [_archetypes_](g), assets, content, data, [_templates_](g), translation tables, static files, or configuration settings. A module may serve as the basis for a new site, or to augment an existing site. ++A _module_ is a packaged combination of [_components_](g) which may include [_archetypes_](g), assets, content, data, templates, [_translation tables_](g), and static files. A module may be a [_theme_](g), a complete project, or a smaller collection of one or more components. diff --cc docs/content/en/quick-reference/glossary/mount.md index 000000000,000000000..12a4a6414 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/mount.md @@@ -1,0 -1,0 +1,7 @@@ ++--- ++title: mount ++params: ++ reference: /configuration/module ++--- ++ ++A _mount_ is a configuration object that maps a file system path (source) to a [_component_](g) path (target) within Hugo's [_unified file system_](g). diff --cc docs/content/en/quick-reference/glossary/seed.md index 000000000,000000000..bbb6e4809 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/seed.md @@@ -1,0 -1,0 +1,6 @@@ ++--- ++title: seed ++reference: https://en.wikipedia.org/wiki/Random_seed ++--- ++ ++A _seed_ is the starting point for a computer algorithm that generates pseudo-random numbers. Using the same seed will always produce the identical sequence of numbers, which is essential for reproducibility in areas like simulations, cryptography, and video games. diff --cc docs/content/en/quick-reference/glossary/theme.md index 84b9c684a,000000000..fca98572d mode 100644,000000..100644 --- a/docs/content/en/quick-reference/glossary/theme.md +++ b/docs/content/en/quick-reference/glossary/theme.md @@@ -1,5 -1,0 +1,5 @@@ +--- +title: theme +--- + - A _theme_ is a packaged combination of [_archetypes_](g), assets, content, data, [_templates_](g), translation tables, static files, or configuration settings. A theme may serve as the basis for a new site, or to augment an existing site. ++A _theme_ is a [_module_](g) that delivers a complete set of [components](g) defining a site's layout, presentation, and behavior. While every theme is a module, not every module is a theme. diff --cc docs/content/en/quick-reference/glossary/translation-table.md index 000000000,000000000..a48febb67 new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/translation-table.md @@@ -1,0 -1,0 +1,5 @@@ ++--- ++title: translation table ++--- ++ ++A _translation table_ is a data file within the `i18n` directory, holding translations for a single language. diff --cc docs/content/en/quick-reference/glossary/unified-file-system.md index 000000000,000000000..4d3d779de new file mode 100644 --- /dev/null +++ b/docs/content/en/quick-reference/glossary/unified-file-system.md @@@ -1,0 -1,0 +1,5 @@@ ++--- ++title: unified file system ++--- ++ ++Hugo's _unified file system_ provides a layered view for each of its seven [_component_](g) types: [_archetypes_](g), assets, content, data, templates, [_translation tables_](g), and static files. Project component directories are layered over [_module_](g) component directories. Hugo searches these layers in order to locate files. diff --cc docs/content/en/render-hooks/code-blocks.md index 526a1232f,000000000..f6af66d59 mode 100755,000000..100755 --- a/docs/content/en/render-hooks/code-blocks.md +++ b/docs/content/en/render-hooks/code-blocks.md @@@ -1,126 -1,0 +1,126 @@@ +--- +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} +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 +: {{< new-in 0.125.0 />}} +: (`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 %}} ++[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 bee068a0d,000000000..9f2625fee mode 100755,000000..100755 --- a/docs/content/en/render-hooks/images.md +++ b/docs/content/en/render-hooks/images.md @@@ -1,137 -1,0 +1,137 @@@ +--- +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 +: {{< new-in 0.125.0 />}} +: (`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: + +{{< code-toggle file=hugo >}} +[markup.goldmark.parser] +wrapStandAloneImageWithinParagraph = false +{{< /code-toggle >}} + +## Embedded + +{{< new-in 0.123.0 />}} + +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: + +{{< 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: + +{{< 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 %}} ++[embedded image render hook]: <{{% eturl render-image %}}> +[Markdown attributes]: /content-management/markdown-attributes/ diff --cc docs/content/en/render-hooks/links.md index 0e6519e2e,000000000..623678ee1 mode 100755,000000..100755 --- a/docs/content/en/render-hooks/links.md +++ b/docs/content/en/render-hooks/links.md @@@ -1,107 -1,0 +1,107 @@@ +--- +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 +: {{< new-in 0.125.0 />}} +: (`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 + +{{< new-in 0.123.0 />}} + +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: + +{{< 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: + +{{< 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 %}} ++[embedded link render hook]: <{{% eturl render-link %}}> diff --cc docs/content/en/render-hooks/passthrough.md index 253039316,000000000..76643718f mode 100755,000000..100755 --- a/docs/content/en/render-hooks/passthrough.md +++ b/docs/content/en/render-hooks/passthrough.md @@@ -1,123 -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: + +{{< 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/details.md index 421fb4e66,000000000..5df6c118f mode 100755,000000..100755 --- a/docs/content/en/shortcodes/details.md +++ b/docs/content/en/shortcodes/details.md @@@ -1,74 -1,0 +1,74 @@@ +--- +title: Details shortcode +linkTitle: Details +description: Insert an HTML details element into your content using the details shortcode. +categories: [] +keywords: [] +--- + +{{< new-in 0.140.0 />}} + +> [!note] +> To override Hugo's embedded `details` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +## Example + +With this markup: + +```text +{{}} +This is a **bold** word. +{{}} +``` + +Hugo renders this HTML: + +```html +
+ See the details +

This is a bold word.

+
+``` + +Which looks like this in your browser: + +{{< details summary="See the details" >}} +This is a **bold** word. +{{< /details >}} + +## Arguments + +summary +: (`string`) The content of the child `summary` element rendered from Markdown to HTML. Default is `Details`. + +open +: (`bool`) Whether to initially display the content of the `details` element. Default is `false`. + +class +: (`string`) The `class` attribute of the `details` element. + +name +: (`string`) The `name` attribute of the `details` element. + +title +: (`string`) The `title` attribute of the `details` element. + +## Styling + +Use CSS to style the `details` element, the `summary` element, and the content itself. + +```css +/* target the details element */ +details { } + +/* target the summary element */ +details > summary { } + +/* target the children of the summary element */ +details > summary > * { } + +/* target the content */ +details > :not(summary) { } +``` + - [source code]: {{% eturl details %}} ++[source code]: <{{% eturl details %}}> diff --cc docs/content/en/shortcodes/figure.md index 2234bb3c5,000000000..24d85064b 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: + +{{< code-toggle file=hugo >}} +[[module.mounts]] +source = 'assets' +target = 'assets' + +[[module.mounts]] +source = 'static' +target = 'assets' +{{< /code-toggle >}} + - [source code]: {{% eturl figure %}} ++[source code]: <{{% eturl figure %}}> diff --cc docs/content/en/shortcodes/highlight.md index de90f64f3,000000000..c349e97be 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. + +## 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]. + +{{% 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 - [source code]: {{% eturl highlight %}} ++[source code]: <{{% eturl highlight %}}> +[supported languages]: /content-management/syntax-highlighting/#languages diff --cc docs/content/en/shortcodes/instagram.md index 4ee558c00,000000000..9f8b4fd26 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. + +{{< 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 %}} ++[source code]: <{{% eturl instagram %}}> diff --cc docs/content/en/shortcodes/param.md index 1a782056f,000000000..967d12846 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. +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 %}} ++[source code]: <{{% eturl param %}}> diff --cc docs/content/en/shortcodes/qr.md index 3cbc5d3fd,000000000..d83be2a6f mode 100755,000000..100755 --- a/docs/content/en/shortcodes/qr.md +++ b/docs/content/en/shortcodes/qr.md @@@ -1,107 -1,0 +1,107 @@@ +--- +title: QR shortcode +linkTitle: QR +description: Insert a QR code into your content using the qr shortcode. +categories: [] +keywords: [] +--- + +{{< new-in 0.141.0 />}} + +> [!note] +> To override Hugo's embedded `qr` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +The `qr` shortcode encodes the given text into a [QR code] using the specified options and renders the resulting image. + +Internally this shortcode calls the `images.QR` function. Please read the [related documentation] for implementation details and guidance. + +## Examples + +Use the self-closing syntax to pass the text as an argument: + +```text +{{}} +``` + +Or insert the text between the opening and closing tags: + +```text +{{}} +https://gohugo.io +{{}} +``` + +Both of the above produce this image: + +{{< qr text="https://gohugo.io" class="qrcode" targetDir="images/qr" />}} + +To create a QR code for a phone number: + +```text +{{}} +``` + +{{< qr text="tel:+12065550101" class="qrcode" targetDir="images/qr" />}} + +To create a QR code containing contact information in the [vCard] format: + +```text +{{}} +BEGIN:VCARD +VERSION:2.1 +N;CHARSET=UTF-8:Smith;John;R.;Dr.;PhD +FN;CHARSET=UTF-8:Dr. John R. Smith, PhD. +ORG;CHARSET=UTF-8:ABC Widgets +TITLE;CHARSET=UTF-8:Vice President Engineering +TEL;TYPE=WORK:+12065550101 +EMAIL;TYPE=WORK:jsmith@example.org +END:VCARD +{{}} +``` + +{{< qr level="low" scale=2 alt="QR code of vCard for John Smith" class="qrcode" targetDir="images/qr" >}} +BEGIN:VCARD +VERSION:2.1 +N;CHARSET=UTF-8:Smith;John;R.;Dr.;PhD +FN;CHARSET=UTF-8:Dr. John R. Smith, PhD. +ORG;CHARSET=UTF-8:ABC Widgets +TITLE;CHARSET=UTF-8:Vice President Engineering +TEL;TYPE=WORK:+12065550101 +EMAIL;TYPE=WORK:jsmith@example.org +END:VCARD +{{< /qr >}} + +## Arguments + +text +: (`string`) The text to encode, falling back to the text between the opening and closing shortcode tags. + +level +: (`string`) The error correction level to use when encoding the text, one of `low`, `medium`, `quartile`, or `high`. Default is `medium`. + +scale +: (`int`) The number of image pixels per QR code module. Must be greater than or equal to 2. Default is `4`. + +targetDir +: (`string`) The subdirectory within the [`publishDir`] where Hugo will place the generated image. + +alt +: (`string`) The `alt` attribute of the `img` element. + +class +: (`string`) The `class` attribute of the `img` element. + +id +: (`string`) The `id` attribute of the `img` element. + +loading +: (`string`) The `loading` attribute of the `img` element, either `eager` or `lazy`. + +title +: (`string`) The `title` attribute of the `img` element. + +[`publishDir`]: /configuration/all/#publishdir +[QR code]: https://en.wikipedia.org/wiki/QR_code +[related documentation]: /functions/images/qr/ - [source code]: {{% eturl qr %}} ++[source code]: <{{% eturl qr %}}> +[vCard]: diff --cc docs/content/en/shortcodes/ref.md index 0cd5b52dc,000000000..19c0ae711 mode 100755,000000..100755 --- a/docs/content/en/shortcodes/ref.md +++ b/docs/content/en/shortcodes/ref.md @@@ -1,65 -1,0 +1,65 @@@ +--- +title: Ref shortcode +linkTitle: Ref +description: Insert a permalink to the given page reference using the ref shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `ref` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +> [!note] +> When working with Markdown this shortcode is obsolete. Instead, to properly resolve Markdown link destinations, use the [embedded link render hook] or create your own. +> +> In its default configuration, 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). + +## Usage + +The `ref` shortcode accepts either a single positional argument (the path) or one or more named arguments, as listed below. + +## Arguments + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The `ref` shortcode typically provides the destination for a Markdown link. + +> [!note] +> Always use [Markdown notation] notation when calling this shortcode. + +The following examples show the rendered output for a page on the English version of the site: + +```md +[Link A]({{%/* ref "/books/book-1" */%}}) + +[Link B]({{%/* ref path="/books/book-1" */%}}) + +[Link C]({{%/* ref path="/books/book-1" lang="de" */%}}) + +[Link D]({{%/* ref path="/books/book-1" lang="de" outputFormat="json" */%}}) +``` + +Rendered: + +```html +Link A + +Link B + +Link C + +Link D +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} + +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[embedded link render hook]: /render-hooks/links/#embedded +[Markdown notation]: /content-management/shortcodes/#notation - [source code]: {{% eturl relref %}} ++[source code]: <{{% eturl relref %}}> diff --cc docs/content/en/shortcodes/relref.md index 22cdb9f2f,000000000..3f85b8419 mode 100755,000000..100755 --- a/docs/content/en/shortcodes/relref.md +++ b/docs/content/en/shortcodes/relref.md @@@ -1,65 -1,0 +1,65 @@@ +--- +title: Relref shortcode +linkTitle: Relref +description: Insert a relative permalink to the given page reference using the relref shortcode. +categories: [] +keywords: [] +--- + +> [!note] +> To override Hugo's embedded `relref` shortcode, copy the [source code] to a file with the same name in the `layouts/_shortcodes` directory. + +> [!note] +> When working with Markdown this shortcode is obsolete. Instead, to properly resolve Markdown link destinations, use the [embedded link render hook] or create your own. +> +> In its default configuration, 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). + +## Usage + +The `relref` shortcode accepts either a single positional argument (the path) or one or more named arguments, as listed below. + +## Arguments + +{{% include "_common/ref-and-relref-options.md" %}} + +## Examples + +The `relref` shortcode typically provides the destination for a Markdown link. + +> [!note] +> Always use [Markdown notation] notation when calling this shortcode. + +The following examples show the rendered output for a page on the English version of the site: + +```md +[Link A]({{%/* relref "/books/book-1" */%}}) + +[Link B]({{%/* relref path="/books/book-1" */%}}) + +[Link C]({{%/* relref path="/books/book-1" lang="de" */%}}) + +[Link D]({{%/* relref path="/books/book-1" lang="de" outputFormat="json" */%}}) +``` + +Rendered: + +```html +Link A + +Link B + +Link C + +Link D +``` + +## Error handling + +{{% include "_common/ref-and-relref-error-handling.md" %}} + +[duplication of shared page resources]: /configuration/markup/#duplicateresourcefiles +[embedded link render hook]: /render-hooks/links/#embedded +[Markdown notation]: /content-management/shortcodes/#notation - [source code]: {{% eturl relref %}} ++[source code]: <{{% eturl relref %}}> diff --cc docs/content/en/shortcodes/vimeo.md index 40daaeec2,000000000..b09420018 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. + +{{< 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 [here]. ++The source code for the simple version of the shortcode is available [in this file]. + - [here]: {{% eturl vimeo_simple %}} - [source code]: {{% eturl vimeo %}} ++[in this file]: <{{% eturl vimeo_simple %}}> ++[source code]: <{{% eturl vimeo %}}> diff --cc docs/content/en/shortcodes/x.md index dbce7e613,000000000..967a526a8 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. + +{{< 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 [here]. ++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`. + +{{< code-toggle config=services.x />}} + - [here]: {{% eturl x_simple %}} - [source code]: {{% eturl x %}} ++[in this file]: <{{% eturl x_simple %}}> ++[source code]: <{{% eturl x %}}> diff --cc docs/content/en/templates/embedded.md index af9a08f26,000000000..daba32c3e mode 100644,000000..100644 --- a/docs/content/en/templates/embedded.md +++ b/docs/content/en/templates/embedded.md @@@ -1,224 -1,0 +1,224 @@@ +--- +title: Embedded partial templates +description: Hugo provides embedded partial templates for common use cases. +categories: [] +keywords: [] +weight: 170 +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: ++> 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. + +{{< 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: ++> 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. + +{{< 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 `false`. + +## 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: ++> 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. + +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: ++> 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: ++> 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. + +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`. + +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: + +{{< 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 9d94032c9,000000000..207cfc4a7 mode 100644,000000..100644 --- a/docs/content/en/templates/introduction.md +++ b/docs/content/en/templates/introduction.md @@@ -1,531 -1,0 +1,555 @@@ +--- +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. ++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)), variables, functions, and methods. ++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 ++```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. + +### 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. + +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: + +{{< 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]: /content-management/front-matter/ +[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/pagination.md index 6d4203949,000000000..a1174980d 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 + +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: + +{{< 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: + +{{< 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 %}} ++[source code]: <{{% eturl pagination %}}> diff --cc docs/content/en/templates/robots.md index 807a6027a,000000000..8183d316f 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: 180 +aliases: [/extras/robots-txt/] +--- + +To generate a robots.txt file from a template, change the [site 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. 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. + - [embedded template]: {{% eturl robots %}} ++[embedded template]: <{{% eturl robots %}}> +[site configuration]: /configuration/ diff --cc docs/content/en/templates/rss.md index 6e92d4ba4,000000000..cbc393a03 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: + +{{< 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: + +{{< 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: + +{{< 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 %}} ++[embedded RSS template]: <{{% eturl rss %}}> diff --cc docs/content/en/templates/shortcode.md index f07206f6a,000000000..34cf46f5a mode 100644,000000..100644 --- a/docs/content/en/templates/shortcode.md +++ b/docs/content/en/templates/shortcode.md @@@ -1,340 -1,0 +1,340 @@@ +--- +title: Shortcode templates +description: Create custom shortcodes to simplify and standardize content creation. +categories: [] +keywords: [] +weight: 120 +aliases: [/templates/shortcode-templates/] +--- + +{{< newtemplatesystem >}} + +> [!note] +> Before creating custom shortcodes, please review the [shortcodes] page in the [content management] section. Understanding the usage details will help you design and create better templates. + +## Introduction + +Hugo provides [embedded shortcodes] for many common tasks, but you'll likely need to create your own for more specific needs. Some examples of custom shortcodes you might develop include: + +- Audio players +- Video players +- Image galleries +- Diagrams +- Maps +- Tables +- And many other custom elements + +## Directory structure + +Create _shortcode_ templates within the `layouts/_shortcodes` directory, either at its root or organized into subdirectories. + +```text +layouts/ +└── _shortcodes/ + ├── diagrams/ + │ ├── kroki.html + │ └── plotly.html + ├── media/ + │ ├── audio.html + │ ├── gallery.html + │ └── video.html + ├── capture.html + ├── column.html + ├── include.html + └── row.html +``` + +When calling a shortcode in a subdirectory, specify its path relative to the `_shortcode` directory, excluding the file extension. + +```text +{{}} +``` + +## Lookup order + +Hugo selects _shortcode_ templates based on the shortcode name, the current output format, and the current language. The examples below are sorted by specificity in descending order. The least specific path is at the bottom of the list. + +Shortcode name|Output format|Language|Template path +:--|:--|:--|:-- +foo|html|en|`layouts/_shortcodes/foo.en.html` +foo|html|en|`layouts/_shortcodes/foo.html.html` +foo|html|en|`layouts/_shortcodes/foo.html` +foo|html|en|`layouts/_shortcodes/foo.html.en.html` + +Shortcode name|Output format|Language|Template path +:--|:--|:--|:-- - foo|json|en|`layouts/_shortcodes/foo.en.json` - foo|json|en|`layouts/_shortcodes/foo.json` - foo|json|en|`layouts/_shortcodes/foo.json.json` - foo|json|en|`layouts/_shortcodes/foo.json.en.json` ++foo|rss|en|`layouts/_shortcodes/foo.en.rss.xml` ++foo|rss|en|`layouts/_shortcodes/foo.rss.xml` ++foo|rss|en|`layouts/_shortcodes/foo.en.xml` ++foo|rss|en|`layouts/_shortcodes/foo.xml` + +## Methods + +Use these methods in your _shortcode_ templates. Refer to each methods's documentation for details and examples. + +{{% list-pages-in-section path=/methods/shortcode %}} + +## Examples + +These examples range in complexity from simple to moderately advanced, with some simplified for clarity. + +### Insert year + +Create a shortcode to insert the current year: + +```go-html-template {file="layouts/_shortcodes/year.html"} +{{- now.Format "2006" -}} +``` + +Then call the shortcode from within your markup: + +```text {file="content/example.md"} +This is {{}}, and look at how far we've come. +``` + +This shortcode can be used inline or as a block on its own line. If a shortcode might be used inline, remove the surrounding [whitespace] by using [template action](g) delimiters with hyphens. + +### Insert image + +This example assumes the following content structure, where `content/example/index.md` is a [page bundle](g) containing one or more [page resources](g). + +```text +content/ +├── example/ +│ ├── a.jpg +│ └── index.md +└── _index.md +``` + +Create a shortcode to capture an image as a page resource, resize it to the given width, convert it to the WebP format, and add an `alt` attribute: + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{- with .Page.Resources.Get (.Get "path") }} + {{- with .Process (printf "resize %dx wepb" ($.Get "width")) -}} + {{ $.Get + {{- end }} +{{- end -}} +``` + +Then call the shortcode from within your markup: + +```text {file="content/example/index.md"} +{{}} +``` + +The example above uses: + +- The [`with`] statement to rebind the [context](g) after each successful operation +- The [`Get`] method to retrieve arguments by name +- The `$` to access the template context + +> [!note] +> Make sure that you thoroughly understand the concept of context. The most common templating errors made by new users relate to context. +> +> Read more about context in the [introduction to templating]. + +### Insert image with error handling + +The previous example, while functional, silently fails if the image is missing, and does not gracefully exit if a required argument is missing. We'll add error handling to address these issues: + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{- with .Get "path" }} + {{- with $r := $.Page.Resources.Get ($.Get "path") }} + {{- with $.Get "width" }} + {{- with $r.Process (printf "resize %dx wepb" ($.Get "width" )) }} + {{- $alt := or ($.Get "alt") "" -}} + {{ $alt }} + {{- end }} + {{- else }} + {{- errorf "The %q shortcode requires a 'width' argument: see %s" $.Name $.Position }} + {{- end }} + {{- else }} + {{- warnf "The %q shortcode was unable to find %s: see %s" $.Name ($.Get "path") $.Position }} + {{- end }} +{{- else }} + {{- errorf "The %q shortcode requires a 'path' argument: see %s" .Name .Position }} +{{- end -}} +``` + +This template throws an error and gracefully fails the build if the author neglected to provide a `path` or `width` argument, and it emits a warning if it cannot find the image at the specified path. If the author does not provide an `alt` argument, the `alt` attribute is set to an empty string. + +The [`Name`] and [`Position`] methods provide helpful context for errors and warnings. For example, a missing `width` argument causes the shortcode to throw this error: + +```text +ERROR The "image" shortcode requires a 'width' argument: see "/home/user/project/content/example/index.md:7:1" +``` + +### Positional arguments + +Shortcode arguments can be [named or positional]. We used named arguments previously; let's explore positional arguments. Here's the named argument version of our example: + +```text {file="content/example/index.md"} +{{}} +``` + +Here's how to call it with positional arguments: + +```text {file="content/example/index.md"} +{{}} +``` + +Using the `Get` method with zero-indexed keys, we'll initialize variables with descriptive names in our template: + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{ $path := .Get 0 }} +{{ $width := .Get 1 }} +{{ $alt := .Get 2 }} +``` + +> [!note] +> Positional arguments work well for frequently used shortcodes with one or two arguments. Since you'll use them often, the argument order will be easy to remember. For less frequently used shortcodes, or those with more than two arguments, named arguments improve readability and reduce the chance of errors. + +### Named and positional arguments + +You can create a shortcode that will accept both named and positional arguments, but not at the same time. Use the [`IsNamedParams`] method to determine whether the shortcode call used named or positional arguments: + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{ $path := cond (.IsNamedParams) (.Get "path") (.Get 0) }} +{{ $width := cond (.IsNamedParams) (.Get "width") (.Get 1) }} +{{ $alt := cond (.IsNamedParams) (.Get "alt") (.Get 2) }} +``` + +This example uses the `cond` alias for the [`compare.Conditional`] function to get the argument by name if `IsNamedParams` returns `true`, otherwise get the argument by position. + +### Argument collection + +Use the [`Params`] method to access the arguments as a collection. + +When using named arguments, the `Params` method returns a map: + +```text {file="content/example/index.md"} +{{}} +``` + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{ .Params.path }} → a.jpg +{{ .Params.width }} → 300 +{{ .Params.alt }} → A white kitten +``` + + When using positional arguments, the `Params` method returns a slice: + +```text {file="content/example/index.md"} +{{}} +``` + +```go-html-template {file="layouts/_shortcodes/image.html"} +{{ index .Params 0 }} → a.jpg +{{ index .Params 1 }} → 300 +{{ index .Params 1 }} → A white kitten +``` + +Combine the `Params` method with the [`collections.IsSet`] function to determine if a parameter is set, even if its value is falsy. + +### Inner content + +Extract the content enclosed within shortcode tags using the [`Inner`] method. This example demonstrates how to pass both content and a title to a shortcode. The shortcode then generates a `div` element containing an `h2` element (displaying the title) and the provided content. + +```text {file="content/example.md"} +{{}} +This is a **bold** word, and this is an _emphasized_ word. +{{}} +``` + +```go-html-template {file="layouts/_shortcodes/contrived.html"} +
+

{{ .Get "title" }}

+ {{ .Inner | .Page.RenderString }} +
+``` + +The preceding example called the shortcode using [standard notation], requiring us to process the inner content with the [`RenderString`] method to convert the Markdown to HTML. This conversion is unnecessary when calling a shortcode using [Markdown notation]. + +### Nesting + +The [`Parent`] method provides access to the parent shortcode context when the shortcode in question is called within the context of a parent shortcode. This provides an inheritance model. + +The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` argument: + +```go-html-template {file="layouts/_shortcodes/gallery.html"} +
+ {{ .Inner }} +
+``` + +You also have an `img` shortcode with a single named `src` argument that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`: + +```go-html-template {file="layouts/_shortcodes/img.html"} +{{ $src := .Get "src" }} +{{ with .Parent }} + +{{ else }} + +{{ end }} +``` + +You can then call your shortcode in your content as follows: + +```text {file="content/example.md"} +{{}} + {{}} + {{}} +{{}} +{{}} +``` + +This will output the following HTML. Note how the first two `img` shortcodes inherit the `class` value of `content-gallery` set with the call to the parent `gallery`, whereas the third `img` only uses `src`: + +```html + + +``` + +### Other examples + +For guidance, consider examining Hugo's embedded shortcodes. The source code, available on [GitHub], can provide a useful model. + +## Detection + +The [`HasShortcode`] method allows you to check if a specific shortcode has been called on a page. For example, consider a custom audio shortcode: + +```text {file="content/example.md"} +{{}} +``` + +You can use the `HasShortcode` method in your base template to conditionally load CSS if the audio shortcode was used on the page: + +```go-html-template {file="layouts/baseof.html"} + + ... + {{ if .HasShortcode "audio" }} + + {{ end }} + ... + +``` + +[`collections.IsSet`]: /functions/collections/isset/ +[`compare.Conditional`]: /functions/compare/conditional/ +[`Get`]: /methods/shortcode/get/ +[`HasShortcode`]: /methods/page/hasshortcode/ +[`Inner`]: /methods/shortcode/inner/ +[`IsNamedParams`]: /methods/shortcode/isnamedparams/ +[`Name`]: /methods/shortcode/name/ +[`Params`]: /methods/shortcode/params/ +[`Parent`]: /methods/shortcode/parent/ +[`Position`]: /methods/shortcode/position/ +[`RenderString`]: /methods/page/renderstring/ +[`with`]: /functions/go-template/with/ +[content management]: /content-management/shortcodes/ +[embedded shortcodes]: /shortcodes/ +[GitHub]: https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates/_shortcodes +[introduction to templating]: /templates/introduction/ +[Markdown notation]: /content-management/shortcodes/#markdown-notation +[named or positional]: /content-management/shortcodes/#arguments +[shortcodes]: /content-management/shortcodes/ +[standard notation]: /content-management/shortcodes/#standard-notation +[whitespace]: /templates/introduction/#whitespace diff --cc docs/content/en/templates/sitemap.md index 8eb358d87,000000000..a79ec7bba 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: + +{{< code-toggle file=hugo >}} +disableKinds = ['sitemap'] +{{}} + +[`publishDir`]: /configuration/all/#publishdir - [embedded sitemap template]: {{% eturl sitemap %}} - [embedded sitemapindex template]: {{% eturl sitemapindex %}} ++[embedded sitemap template]: <{{% eturl sitemap %}}> ++[embedded sitemapindex template]: <{{% eturl sitemapindex %}}> +[sitemap protocol]: https://www.sitemaps.org/protocol.html diff --cc docs/content/en/templates/types.md index 19e0e32dd,000000000..a030d7fdf mode 100644,000000..100644 --- a/docs/content/en/templates/types.md +++ b/docs/content/en/templates/types.md @@@ -1,403 -1,0 +1,404 @@@ +--- +title: Template types +description: Create templates of different types to render your content, resources, and data. +categories: [] +keywords: [] +weight: 30 +aliases: [ + '/templates/base/', + '/templates/content-view/', + '/templates/home/', + '/templates/lists/', + '/templates/partial/', + '/templates/section/', + '/templates/single/', + '/templates/taxonomy/', + '/templates/term/', +] +--- + +## Structure + +Create templates in the `layouts` directory in the root of your project. + +Although your site may not require each of these templates, the example below is typical for a site of medium complexity. + +```text +layouts/ +├── _markup/ +│ ├── render-image.html <-- render hook +│ └── render-link.html <-- render hook +├── _partials/ +│ ├── footer.html +│ └── header.html +├── _shortcodes/ +│ ├── audio.html +│ └── video.html +├── books/ +│ ├── page.html +│ └── section.html +├── films/ +│ ├── view_card.html <-- content view +│ ├── view_li.html <-- content view +│ ├── page.html +│ └── section.html +├── baseof.html +├── home.html +├── page.html +├── section.html +├── taxonomy.html +└── term.html +``` + +Hugo's [template lookup order] determines the template path, allowing you to create unique templates for any page. + +> [!note] +> You must have thorough understanding of the template lookup order when creating templates. Template selection is based on template type, page kind, content type, section, language, and output format. + +The purpose of each template type is described below. + +## Base + +A _base_ template serves as a foundational layout that other templates can build upon. It typically defines the common structural components of your HTML, such as the `html`, `head`, and `body` elements. It also often includes recurring features like headers, footers, navigation, and script inclusions that appear across multiple pages of your site. By defining these common aspects once in a _base_ template, you avoid redundancy, ensure consistency, and simplify the maintenance of your website. + +Hugo can apply a _base_ template to the following template types: [home](#home), [page](#page), [section](#section), [taxonomy](#taxonomy), [term](#term), [single](#single), [list](#list), and [all](#all). When Hugo parses any of these template types, it will apply a _base_ template only if the template being parsed meets these specific conditions: + +- It must include at least one [`define`] [action](g). +- It can only contain `define` actions, whitespace, and [template comments]. No other content is allowed. + +> [!note] +> If a template doesn't meet all these criteria, Hugo executes it exactly as provided, without applying a _base_ template. + +When Hugo applies a _base_ template, it replaces its [`block`] actions with content from the corresponding `define` actions found in the template to which the base template is applied. + +For example, the _base_ template below calls the [`partial`] function to include `head`, `header`, and `footer` elements. The `block` action acts as a placeholder, and its content will be replaced by a matching `define` action from the template to which it is applied. + +```go-html-template {file="layouts/baseof.html"} + + + + {{ partial "head.html" . }} + + +
+ {{ partial "header.html" . }} +
+
+ {{ block "main" . }} + This will be replaced with content from the + corresponding "define" action found in the template + to which this base template is applied. + {{ end }} +
+
+ {{ partial "footer.html" . }} +
+ + +``` + +```go-html-template {file="layouts/home.html"} +{{ define "main" }} + This will replace the content of the "block" action + found in the base template. +{{ end }} +``` + +## Home + +A _home_ template renders your site's home page. + +For example, Hugo applies a _base_ template to the _home_ template below, then renders the page content and a list of the site's regular pages. + +```go-html-template {file="layouts/home.html"} +{{ define "main" }} + {{ .Content }} + {{ range .Site.RegularPages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +{{% include "/_common/filter-sort-group.md" %}} + +## Page + +A _page_ template renders a regular page. + +For example, Hugo applies a _base_ template to the _page_ template below, then renders the page title and page content. + +```go-html-template {file="layouts/page.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} +{{ end }} +``` + +## Section + +A _section_ template renders a list of pages within a [section](g). + +For example, Hugo applies a _base_ template to the _section_ template below, then renders the page title, page content, and a list of pages in the current section. + +```go-html-template {file="layouts/section.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +{{% include "/_common/filter-sort-group.md" %}} + +## Taxonomy + +A _taxonomy_ template renders a list of terms in a [taxonomy](g). + +For example, Hugo applies a _base_ template to the _taxonomy_ template below, then renders the page title, page content, and a list of [terms](g) in the current taxonomy. + +```go-html-template {file="layouts/taxonomy.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +{{% include "/_common/filter-sort-group.md" %}} + +Within a _taxonomy_ template, the [`Data`] object provides these taxonomy-specific methods: + +- [`Singular`][taxonomy-singular] +- [`Plural`][taxonomy-plural] +- [`Terms`] + +The `Terms` method returns a [taxonomy object](g), allowing you to call any of its methods including [`Alphabetical`] and [`ByCount`]. For example, use the `ByCount` method to render a list of terms sorted by the number of pages associated with each term: + +```go-html-template {file="layouts/taxonomy.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Data.Terms.ByCount }} +

{{ .Page.LinkTitle }} ({{ .Count }})

+ {{ end }} +{{ end }} +``` + +## Term + +A _term_ template renders a list of pages associated with a [term](g). + +For example, Hugo applies a _base_ template to the _term_ template below, then renders the page title, page content, and a list of pages associated with the current term. + +```go-html-template {file="layouts/term.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +{{% include "/_common/filter-sort-group.md" %}} + +Within a _term_ template, the [`Data`] object provides these term-specific methods: + +- [`Singular`][term-singular] +- [`Plural`][term-plural] +- [`Term`] + +## Single + +A _single_ template is a fallback for a _page_ template. If a _page_ template does not exist, Hugo will look for a _single_ template instead. + +For example, Hugo applies a _base_ template to the _single_ template below, then renders the page title and page content. + +```go-html-template {file="layouts/single.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} +{{ end }} +``` + +## List + +A _list_ template is a fallback for [home](#home), [section](#section), [taxonomy](#taxonomy), and [term](#term) templates. If one of these template types does not exist, Hugo will look for a _list_ template instead. + +For example, Hugo applies a _base_ template to the _list_ template below, then renders the page title, page content, and a list of pages. + +```go-html-template {file="layouts/list.html"} +{{ define "main" }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} +{{ end }} +``` + +## All + +An _all_ template is a fallback for [home](#home), [page](#page), [section](#section), [taxonomy](#taxonomy), [term](#term), [single](#single), and [list](#list) templates. If one of these template types does not exist, Hugo will look for an _all_ template instead. + +For example, Hugo applies a _base_ template to the _all_ template below, then conditionally renders a page based on its page kind. + +```go-html-template {file="layouts/all.html"} +{{ define "main" }} + {{ if eq .Kind "home" }} + {{ .Content }} + {{ range .Site.RegularPages }} +

{{ .LinkTitle }}

+ {{ end }} + {{ else if eq .Kind "page" }} +

{{ .Title }}

+ {{ .Content }} + {{ else if in (slice "section" "taxonomy" "term") .Kind }} +

{{ .Title }}

+ {{ .Content }} + {{ range .Pages }} +

{{ .LinkTitle }}

+ {{ end }} + {{ else }} + {{ errorf "Unsupported page kind: %s" .Kind }} + {{ end }} +{{ end }} +``` + +## Partial + +A _partial_ template is typically used to render a component of your site, though you may also create _partial_ templates that return values. + +For example, the _partial_ template below renders copyright information: + +```go-html-template {file="layouts/_partials/footer.html"} +

Copyright {{ now.Year }}. All rights reserved.

+``` + +Execute the _partial_ template by calling the [`partial`] or [`partialCached`] function, optionally passing context as the second argument: + +```go-html-template {file="layouts/baseof.html"} +{{ partial "footer.html" . }} +``` + + - Unlike other template types, Hugo does not consider the current page kind, content type, logical path, language, or output format when searching for a matching _partial_ template. However, it _does_ apply the same name matching logic it uses for other template types. This means it tries to find the most specific match first, then progressively looks for more general versions if the specific one isn't found. ++Unlike other template types, Hugo does not consider the current page kind, content type, logical path, language, or output format when searching for a matching _partial_ template. However, it _does_ apply the same _name_ matching logic it uses for other template types. This means it tries to find the most specific match first, then progressively looks for more general versions if the specific one isn't found. + +For example, with this call: + +```go-html-template {file="layouts/baseof.html"} +{{ partial "footer.section.de.html" . }} +``` + +Hugo uses this lookup order to find a matching template: + +1. `layouts/_partials/footer.section.de.html` +1. `layouts/_partials/footer.section.html` +1. `layouts/_partials/footer.de.html` +1. `layouts/_partials/footer.html` + +A _partial_ template can also be defined inline within another template. However, it's important to note that the template namespace is global; ensuring unique names for these _partial_ templates is necessary to prevent conflicts. + +```go-html-template +Value: {{ partial "my-inline-partial.html" . }} + +{{ define "_partials/my-inline-partial.html" }} + {{ $value := 32 }} + {{ return $value }} +{{ end }} +``` + +## Content view + +A _content view_ template is similar to a _partial_ template, invoked by calling the [`Render`] method on a `Page` object. Unlike _partial_ templates, _content view_ templates: + +- Inherit the context of the current page +- Can target any page kind, content type, logical path, language, or output format ++- Can reside at any level within the `layouts` directory + +For example, Hugo applies a _base_ template to the _home_ template below, then renders the page content and a card component for each page within the "films" section of your site. + +```go-html-template {file="layouts/home.html"} +{{ define "main" }} + {{ .Content }} +
    + {{ range where site.RegularPages "Section" "films" }} + {{ .Render "view_card" }} + {{ end }} +
+{{ end }} +``` + +```go-html-template {file="layouts/films/view_card.html"} +
+

{{ .LinkTitle }}

+ {{ .Summary }} +
+``` + +In the example above, the content view template's name starts with `view_`. While not strictly required, this naming convention helps distinguish content view templates from other templates within the same directory, improving organization and clarity. + +## Render hook + +A _render hook_ template overrides the conversion of Markdown to HTML. + +For example, the _render hook_ template below adds an anchor link to the right of each heading. + +```go-html-template {file="layouts/_markup/render-heading.html"} + + {{ .Text }} + # + +``` + +Learn more about [render hook templates](/render-hooks/). + +## Shortcode + +A _shortcode_ template is used to render a component of your site. Unlike _partial_ or _content view_ templates, _shortcode_ templates are called from content pages. + +For example, the _shortcode_ template below renders an audio element from 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 [shortcode templates](/templates/shortcode/). + +## Other + +Use other specialized templates to create: + +- [Sitemaps](/templates/sitemap) +- [RSS feeds](/templates/rss/) +- [404 error pages](/templates/404/) +- [robots.txt files](/templates/robots/) + +[`Alphabetical`]: /methods/taxonomy/alphabetical/ +[`block`]: /functions/go-template/block/ +[`ByCount`]: /methods/taxonomy/bycount/ +[`Data`]: /methods/page/data/ +[`define`]: /functions/go-template/define/ +[`partial`]: /functions/partials/include/ +[`partialCached`]: /functions/partials/includeCached/ +[`Render`]: /methods/page/render/ +[`Term`]: /methods/page/data/#term +[`Terms`]: /methods/page/data/#terms +[taxonomy-plural]: /methods/page/data/#plural +[taxonomy-singular]: /methods/page/data/#singular +[template comments]: /templates/introduction/#comments +[template lookup order]: /templates/lookup-order/ +[term-plural]: /methods/page/data/#plural-1 +[term-singular]: /methods/page/data/#singular-1 diff --cc docs/content/en/tools/editors.md index 612e06987,000000000..4679ec09e mode 100644,000000..100644 --- a/docs/content/en/tools/editors.md +++ b/docs/content/en/tools/editors.md @@@ -1,58 -1,0 +1,63 @@@ +--- +title: Editor plugins +description: The Hugo community uses a wide range of tools and has developed plugins for some of the most popular text editors to help automate parts of your workflow. +categories: [] +keywords: [] +weight: 10 +--- + +## Visual Studio Code + +[Front Matter](https://marketplace.visualstudio.com/items?itemName=eliostruyf.vscode-front-matter) +: Once you go for a static site, you need to think about how you are going to manage your articles. Front matter is a tool that helps you maintain the metadata/front matter of your articles like: creation date, modified date, slug, tile, SEO check, and more. + +[Hugo Helper](https://marketplace.visualstudio.com/items?itemName=rusnasonov.vscode-hugo) +: Hugo Helper is a plugin for Visual Studio Code that has some useful commands for Hugo. The source code can be found on its [GitHub repository](https://github.com/rusnasonov/vscode-hugo). + +[Hugo Language and Syntax Support](https://marketplace.visualstudio.com/items?itemName=budparr.language-hugo-vscode) +: Hugo Language and Syntax Support is a Visual Studio Code plugin for Hugo syntax highlighting and snippets. The source code can be found on its [GitHub repository](https://github.com/budparr/language-hugo-vscode). + +[Hugo Themer](https://marketplace.visualstudio.com/items?itemName=eliostruyf.vscode-hugo-themer) +: Hugo Themer is an extension to help you while developing themes. It allows you to easily navigate through your theme files. + +[Hugofy](https://marketplace.visualstudio.com/items?itemName=akmittal.hugofy) +: Hugofy is a plugin for Visual Studio Code to "make life easier" when developing with Hugo. The source code can be found on its [GitHub repository](https://github.com/akmittal/hugofy-vscode). + +[Prettier Plugin for Go Templates](https://github.com/NiklasPor/prettier-plugin-go-template) +: Format Hugo templates using this [Prettier](https://prettier.io/) plugin. See [installation instructions](https://discourse.gohugo.io/t/38403). + +[Syntax Highlighting for Hugo Shortcodes](https://marketplace.visualstudio.com/items?itemName=kaellarkin.hugo-shortcode-syntax) +: This extension adds some syntax highlighting for Shortcodes, making visual identification of individual pieces easier. + ++## JetBrains IDEs ++ ++[Smart Hugo](https://smarthugo.dev) ++: Plugin for IntelliJ IDEA, WebStorm, PhpStorm, and other JetBrains IDEs that adds Hugo template support including syntax highlighting, actions completion, code formatting, and optional advanced features. ++ +## Emacs + +[emacs-easy-hugo](https://github.com/masasam/emacs-easy-hugo) +: Emacs major mode for managing hugo blogs. Note that Hugo also supports [Org-mode][formats]. + +[ox-hugo.el](https://ox-hugo.scripter.co) +: Native Org-mode exporter that exports to Blackfriday Markdown with Hugo front-matter. `ox-hugo` supports two common Org blogging flows --- exporting multiple Org subtrees in a single file to multiple Hugo posts, and exporting a single Org file to a single Hugo post. It also leverages the Org tag and property inheritance features. See [Why ox-hugo?](https://ox-hugo.scripter.co/doc/why-ox-hugo/) for more. + +## Sublime Text + +[Hugofy](https://github.com/akmittal/Hugofy) +: Hugofy is a plugin for Sublime Text 3 to make life easier to use Hugo static site generator. + +[Hugo Snippets](https://packagecontrol.io/packages/Hugo%20Snippets) +: Hugo Snippets is a useful plugin for adding automatic snippets to Sublime Text 3. + +## Vim + +[Vim Hugo Helper]: https://github.com/robertbasic/vim-hugo-helper + +[Vim Hugo Helper] +: A small Vim plugin that facilitates authoring pages and blog posts with Hugo. + +[vim-hugo](https://github.com/phelipetls/vim-hugo) +: A Vim plugin with syntax highlighting for templates and a few other features. + +[formats]: /content-management/formats/ diff --cc docs/data/docs.yaml index 75daaf6ac,000000000..b53f092a5 mode 100644,000000..100644 --- a/docs/data/docs.yaml +++ b/docs/data/docs.yaml @@@ -1,4680 -1,0 +1,4518 @@@ +chroma: + lexers: + - Aliases: + - abap + Name: ABAP + - Aliases: + - abnf + Name: ABNF + - Aliases: + - as + - actionscript + Name: ActionScript + - Aliases: + - as3 + - actionscript3 + Name: ActionScript 3 + - Aliases: + - ada + - ada95 + - ada2005 + Name: Ada + - Aliases: + - agda + Name: Agda + - Aliases: + - al + Name: AL + - Aliases: + - alloy + Name: Alloy + - Aliases: + - ng2 + Name: Angular2 + - Aliases: + - antlr + Name: ANTLR + - Aliases: + - apacheconf + - aconf + - apache + Name: ApacheConf + - Aliases: + - apl + Name: APL + - Aliases: + - applescript + Name: AppleScript + - Aliases: + - aql + Name: ArangoDB AQL + - Aliases: + - arduino + Name: Arduino + - Aliases: + - armasm + Name: ArmAsm + - Aliases: + - atl + Name: ATL + - Aliases: + - autohotkey + - ahk + Name: AutoHotkey + - Aliases: + - autoit + Name: AutoIt + - Aliases: + - awk + - gawk + - mawk + - nawk + Name: Awk + - Aliases: + - ballerina + Name: Ballerina + - Aliases: + - bash + - sh + - ksh + - zsh + - shell + Name: Bash + - Aliases: + - bash-session + - console + - shell-session + Name: Bash Session + - Aliases: + - bat + - batch + - dosbatch + - winbatch + Name: Batchfile + - Aliases: + - beef + Name: Beef + - Aliases: + - bib + - bibtex + Name: BibTeX + - Aliases: + - bicep + Name: Bicep + - Aliases: + - blitzbasic + - b3d + - bplus + Name: BlitzBasic + - Aliases: + - bnf + Name: BNF + - Aliases: + - bqn + Name: BQN + - Aliases: + - brainfuck + - bf + Name: Brainfuck + - Aliases: + - c + Name: C + - Aliases: + - csharp - - 'c#' - Name: 'C#' ++ - c# ++ Name: C# + - Aliases: + - cpp + - c++ + Name: C++ + - Aliases: + - caddyfile + - caddy + Name: Caddyfile + - Aliases: + - caddyfile-directives + - caddyfile-d + - caddy-d + Name: Caddyfile Directives + - Aliases: + - capnp + Name: Cap'n Proto + - Aliases: + - cassandra + - cql + Name: Cassandra CQL + - Aliases: + - ceylon + Name: Ceylon + - Aliases: + - cfengine3 + - cf3 + Name: CFEngine3 + - Aliases: + - cfs + Name: cfstatement + - Aliases: + - chai + - chaiscript + Name: ChaiScript + - Aliases: + - chapel + - chpl + Name: Chapel + - Aliases: + - cheetah + - spitfire + Name: Cheetah + - Aliases: + - clojure + - clj + - edn + Name: Clojure + - Aliases: + - cmake + Name: CMake + - Aliases: + - cobol + Name: COBOL + - Aliases: + - coffee-script + - coffeescript + - coffee + Name: CoffeeScript + - Aliases: + - common-lisp + - cl + - lisp + Name: Common Lisp + - Aliases: + - coq + Name: Coq + - Aliases: + - core + Name: Core + - Aliases: + - cr + - crystal + Name: Crystal + - Aliases: + - css + Name: CSS + - Aliases: + - csv + Name: CSV + - Aliases: + - cue + Name: CUE + - Aliases: + - cython + - pyx + - pyrex + Name: Cython + - Aliases: + - d + Name: D + - Aliases: + - dart + Name: Dart + - Aliases: + - dax + Name: Dax + - Aliases: + - desktop + - desktop_entry + Name: Desktop file + - Aliases: + - diff + - udiff + Name: Diff + - Aliases: + - django + - jinja + Name: Django/Jinja + - Aliases: + - zone + - bind + Name: dns + - Aliases: + - docker + - dockerfile + - containerfile + Name: Docker + - Aliases: + - dtd + Name: DTD + - Aliases: + - dylan + Name: Dylan + - Aliases: + - ebnf + Name: EBNF + - Aliases: + - elixir + - ex + - exs + Name: Elixir + - Aliases: + - elm + Name: Elm + - Aliases: + - emacs + - elisp + - emacs-lisp + Name: EmacsLisp + - Aliases: + - erlang + Name: Erlang + - Aliases: + - factor + Name: Factor + - Aliases: + - fennel + - fnl + Name: Fennel + - Aliases: + - fish + - fishshell + Name: Fish + - Aliases: + - forth + Name: Forth + - Aliases: + - fortran + - f90 + Name: Fortran + - Aliases: + - fortranfixed + Name: FortranFixed + - Aliases: + - fsharp + Name: FSharp + - Aliases: + - gas + - asm + Name: GAS + - Aliases: + - gdscript + - gd + Name: GDScript + - Aliases: + - gdscript3 + - gd3 + Name: GDScript3 + - Aliases: + - gemtext + - gmi + - gmni + - gemini + Name: Gemtext + - Aliases: + - genshi + - kid + - xml+genshi + - xml+kid + Name: Genshi + - Aliases: + - html+genshi + - html+kid + Name: Genshi HTML + - Aliases: + - genshitext + Name: Genshi Text + - Aliases: + - cucumber + - Cucumber + - gherkin + - Gherkin + Name: Gherkin + - Aliases: + - gleam + Name: Gleam + - Aliases: + - glsl + Name: GLSL + - Aliases: + - gnuplot + Name: Gnuplot + - Aliases: + - go + - golang + Name: Go + - Aliases: + - go-html-template + Name: Go HTML Template + - Aliases: + - go-template + Name: Go Template + - Aliases: + - go-text-template + Name: Go Text Template + - Aliases: + - graphql + - graphqls + - gql + Name: GraphQL + - Aliases: + - groff + - nroff + - man + Name: Groff + - Aliases: + - groovy + Name: Groovy + - Aliases: + - handlebars + - hbs + Name: Handlebars + - Aliases: + - hare + Name: Hare + - Aliases: + - haskell + - hs + Name: Haskell + - Aliases: + - hx + - haxe + - hxsl + Name: Haxe + - Aliases: + - hcl + Name: HCL + - Aliases: + - hexdump + Name: Hexdump + - Aliases: + - hlb + Name: HLB + - Aliases: + - hlsl + Name: HLSL + - Aliases: + - holyc + Name: HolyC + - Aliases: + - html + Name: HTML + - Aliases: + - http + Name: HTTP + - Aliases: + - hylang + Name: Hy + - Aliases: + - idris + - idr + Name: Idris + - Aliases: + - igor + - igorpro + Name: Igor + - Aliases: + - ini + - cfg + - dosini + Name: INI + - Aliases: + - io + Name: Io + - Aliases: + - iscdhcpd + Name: ISCdhcpd + - Aliases: + - j + Name: J + - Aliases: + - janet + Name: Janet + - Aliases: + - java + Name: Java + - Aliases: + - js + - javascript + Name: JavaScript + - Aliases: + - json + Name: JSON + - Aliases: + - jsonata + Name: JSONata + - Aliases: + - jsonnet + Name: Jsonnet + - Aliases: + - julia + - jl + Name: Julia + - Aliases: + - jungle + Name: Jungle + - Aliases: + - kotlin + Name: Kotlin + - Aliases: + - lean4 + - lean + Name: Lean4 + - Aliases: + - lighty + - lighttpd + Name: Lighttpd configuration file + - Aliases: + - llvm + Name: LLVM + - Aliases: null + Name: lox + - Aliases: + - lua + - luau + Name: Lua + - Aliases: + - make + - makefile + - mf + - bsdmake + Name: Makefile + - Aliases: + - mako + Name: Mako + - Aliases: + - md + - mkd + Name: markdown + - Aliases: + - mason + Name: Mason + - Aliases: + - materialize + - mzsql + Name: Materialize SQL dialect + - Aliases: + - mathematica + - mma + - nb + Name: Mathematica + - Aliases: + - matlab + Name: Matlab + - Aliases: + - mcfunction + - mcf + Name: MCFunction + - Aliases: + - meson + - meson.build + Name: Meson + - Aliases: + - metal + Name: Metal + - Aliases: + - minizinc + - MZN + - mzn + Name: MiniZinc + - Aliases: + - mlir + Name: MLIR + - Aliases: + - modula2 + - m2 + Name: Modula-2 + - Aliases: + - mojo - - 🔥 ++ - "\U0001F525" + Name: Mojo + - Aliases: + - monkeyc + Name: MonkeyC + - Aliases: + - moonscript + - moon + Name: MoonScript + - Aliases: + - morrowind + - mwscript + Name: MorrowindScript + - Aliases: + - myghty + Name: Myghty + - Aliases: + - mysql + - mariadb + Name: MySQL + - Aliases: + - nasm + Name: NASM + - Aliases: + - natural + Name: Natural + - Aliases: + - ndisasm + Name: NDISASM + - Aliases: + - newspeak + Name: Newspeak + - Aliases: + - nginx + Name: Nginx configuration file + - Aliases: + - nim + - nimrod + Name: Nim + - Aliases: + - nixos + - nix + Name: Nix + - Aliases: + - nsis + - nsi + - nsh + Name: NSIS + - Aliases: + - nu + Name: Nu + - Aliases: + - objective-c + - objectivec + - obj-c + - objc + Name: Objective-C + - Aliases: + - objectpascal + Name: ObjectPascal + - Aliases: + - ocaml + Name: OCaml + - Aliases: + - octave + Name: Octave + - Aliases: + - odin + Name: Odin + - Aliases: + - ones + - onesenterprise + - 1S + - 1S:Enterprise + Name: OnesEnterprise + - Aliases: + - openedge + - abl + - progress + - openedgeabl + Name: OpenEdge ABL + - Aliases: + - openscad + Name: OpenSCAD + - Aliases: + - org + - orgmode + Name: Org Mode + - Aliases: + - pacmanconf + Name: PacmanConf + - Aliases: + - perl + - pl + Name: Perl + - Aliases: + - php + - php3 + - php4 + - php5 + Name: PHP + - Aliases: + - phtml + Name: PHTML + - Aliases: + - pig + Name: Pig + - Aliases: + - pkgconfig + Name: PkgConfig + - Aliases: + - plpgsql + Name: PL/pgSQL + - Aliases: + - text + - plain + - no-highlight + Name: plaintext + - Aliases: + - plutus-core + - plc + Name: Plutus Core + - Aliases: + - pony + Name: Pony + - Aliases: + - postgresql + - postgres + Name: PostgreSQL SQL dialect + - Aliases: + - postscript + - postscr + Name: PostScript + - Aliases: + - pov + Name: POVRay + - Aliases: + - powerquery + - pq + Name: PowerQuery + - Aliases: + - powershell + - posh + - ps1 + - psm1 + - psd1 + - pwsh + Name: PowerShell + - Aliases: + - prolog + Name: Prolog + - Aliases: + - promela + Name: Promela + - Aliases: + - promql + Name: PromQL + - Aliases: + - java-properties + Name: properties + - Aliases: + - protobuf + - proto + Name: Protocol Buffer + - Aliases: + - prql + Name: PRQL + - Aliases: + - psl + Name: PSL + - Aliases: + - puppet + Name: Puppet + - Aliases: + - python + - py + - sage + - python3 + - py3 + Name: Python + - Aliases: + - python2 + - py2 + Name: Python 2 + - Aliases: + - qbasic + - basic + Name: QBasic + - Aliases: + - qml + - qbs + Name: QML + - Aliases: + - splus + - s + - r + Name: R + - Aliases: + - racket + - rkt + Name: Racket + - Aliases: + - ragel + Name: Ragel + - Aliases: + - perl6 + - pl6 + - raku + Name: Raku + - Aliases: + - jsx + - react + Name: react + - Aliases: + - reason + - reasonml + Name: ReasonML + - Aliases: + - registry + Name: reg + - Aliases: + - rego + Name: Rego + - Aliases: + - rst + - rest + - restructuredtext + Name: reStructuredText + - Aliases: + - rexx + - arexx + Name: Rexx + - Aliases: + - SQLRPGLE + - RPG IV + Name: RPGLE + - Aliases: + - spec + Name: RPMSpec + - Aliases: + - rb + - ruby + - duby + Name: Ruby + - Aliases: + - rust + - rs + Name: Rust + - Aliases: + - sas + Name: SAS + - Aliases: + - sass + Name: Sass + - Aliases: + - scala + Name: Scala + - Aliases: + - scheme + - scm + Name: Scheme + - Aliases: + - scilab + Name: Scilab + - Aliases: + - scss + Name: SCSS + - Aliases: + - sed + - gsed + - ssed + Name: Sed + - Aliases: + - sieve + Name: Sieve + - Aliases: + - smali + Name: Smali + - Aliases: + - smalltalk + - squeak + - st + Name: Smalltalk + - Aliases: + - smarty + Name: Smarty + - Aliases: + - snbt + Name: SNBT + - Aliases: + - snobol + Name: Snobol + - Aliases: + - sol + - solidity + Name: Solidity + - Aliases: + - sp + Name: SourcePawn + - Aliases: + - sparql + Name: SPARQL + - Aliases: + - sql + Name: SQL + - Aliases: + - squidconf + - squid.conf + - squid + Name: SquidConf + - Aliases: + - sml + Name: Standard ML + - Aliases: null + Name: stas + - Aliases: + - stylus + Name: Stylus + - Aliases: + - svelte + Name: Svelte + - Aliases: + - swift + Name: Swift + - Aliases: + - systemd + Name: SYSTEMD + - Aliases: + - systemverilog + - sv + Name: systemverilog + - Aliases: + - tablegen + Name: TableGen + - Aliases: + - tal + - uxntal + Name: Tal + - Aliases: + - tasm + Name: TASM + - Aliases: + - tcl + Name: Tcl + - Aliases: + - tcsh + - csh + Name: Tcsh + - Aliases: + - termcap + Name: Termcap + - Aliases: + - terminfo + Name: Terminfo + - Aliases: + - terraform + - tf + - hcl + Name: Terraform + - Aliases: + - tex + - latex + Name: TeX + - Aliases: + - thrift + Name: Thrift + - Aliases: + - toml + Name: TOML + - Aliases: + - tradingview + - tv + Name: TradingView + - Aliases: + - tsql + - t-sql + Name: Transact-SQL + - Aliases: + - turing + Name: Turing + - Aliases: + - turtle + Name: Turtle + - Aliases: + - twig + Name: Twig + - Aliases: + - ts + - tsx + - typescript + Name: TypeScript + - Aliases: + - typoscript + Name: TypoScript + - Aliases: + - typoscriptcssdata + Name: TypoScriptCssData + - Aliases: + - typoscripthtmldata + Name: TypoScriptHtmlData + - Aliases: + - typst + Name: Typst + - Aliases: null + Name: ucode + - Aliases: + - v + - vlang + Name: V + - Aliases: + - vsh + - vshell + Name: V shell + - Aliases: + - vala + - vapi + Name: Vala + - Aliases: + - vb.net + - vbnet + Name: VB.net + - Aliases: + - verilog + - v + Name: verilog + - Aliases: + - vhdl + Name: VHDL + - Aliases: + - vhs + - tape + - cassette + Name: VHS + - Aliases: + - vim + Name: VimL + - Aliases: + - vue + - vuejs + Name: vue + - Aliases: null + Name: WDTE + - Aliases: + - wgsl + Name: WebGPU Shading Language + - Aliases: + - vtt + Name: WebVTT + - Aliases: + - whiley + Name: Whiley + - Aliases: + - xml + Name: XML + - Aliases: + - xorg.conf + Name: Xorg + - Aliases: + - yaml + Name: YAML + - Aliases: + - yang + Name: YANG + - Aliases: + - z80 + Name: Z80 Assembly + - Aliases: + - zed + Name: Zed + - Aliases: + - zig + Name: Zig + styles: + - RPGLE + - abap + - algol + - algol_nu + - arduino + - autumn + - average + - base16-snazzy + - borland + - bw + - catppuccin-frappe + - catppuccin-latte + - catppuccin-macchiato + - catppuccin-mocha + - colorful + - doom-one + - doom-one2 + - dracula + - emacs + - evergarden + - friendly + - fruity + - github + - github-dark + - gruvbox + - gruvbox-light + - hr_high_contrast + - hrdark + - igor + - lovelace + - manni + - modus-operandi + - modus-vivendi + - monokai + - monokailight + - murphy + - native + - nord + - nordic + - onedark + - onesenterprise + - paraiso-dark + - paraiso-light + - pastie + - perldoc + - pygments + - rainbow_dash + - rose-pine + - rose-pine-dawn + - rose-pine-moon + - rrt + - solarized-dark + - solarized-dark256 + - solarized-light + - swapoff + - tango + - tokyonight-day + - tokyonight-moon + - tokyonight-night + - tokyonight-storm + - trac + - vim + - vs + - vulcan + - witchhazel + - xcode + - xcode-dark +config: + HTTPCache: + cache: + for: + excludes: + - '**' + includes: null + polls: + - disable: true + for: + excludes: null + includes: + - '**' + high: 0s + low: 0s + respectCacheControlNoStoreInRequest: true + respectCacheControlNoStoreInResponse: false + archeTypeDir: archetypes + assetDir: assets + author: {} - baseURL: '' ++ baseURL: "" + build: + buildStats: + disableClasses: false + disableIDs: false + disableTags: false + enable: false + cacheBusters: - - source: '(postcss|tailwind)\.config\.js' ++ - source: (postcss|tailwind)\.config\.js + target: (css|styles|scss|sass) + noJSConfigInAssets: false + useResourceCacheWhen: fallback + buildDrafts: false + buildExpired: false + buildFuture: false - cacheDir: '' ++ cacheDir: "" + caches: + assets: + dir: :resourceDir/_gen + maxAge: -1 + getcsv: + dir: :cacheDir/:project + maxAge: -1 + getjson: + dir: :cacheDir/:project + maxAge: -1 + getresource: + dir: :cacheDir/:project + maxAge: -1 + images: + dir: :resourceDir/_gen + maxAge: -1 + misc: + dir: :cacheDir/:project + maxAge: -1 + modules: + dir: :cacheDir/modules + maxAge: -1 + canonifyURLs: false + capitalizeListTitles: true - cascade: null ++ cascade: [] + cleanDestinationDir: false + contentDir: content + contentTypes: + text/asciidoc: {} + text/html: {} + text/markdown: {} + text/org: {} + text/pandoc: {} + text/rst: {} - copyright: '' ++ copyright: "" + dataDir: data + defaultContentLanguage: en + defaultContentLanguageInSubdir: false - defaultContentRole: guest - defaultContentRoleInSubdir: false - defaultContentVersion: '' - defaultContentVersionInSubdir: false + defaultOutputFormat: html + deployment: + confirm: false + dryRun: false + force: false + invalidateCDN: true + matchers: null + maxDeletes: 256 + order: null - target: '' ++ target: "" + targets: null + workers: 10 + disableAliases: false + disableDefaultLanguageRedirect: false + disableHugoGeneratorInject: false + disableKinds: null + disableLanguages: null + disableLiveReload: false + disablePathToLower: false + enableEmoji: false + enableGitInfo: false + enableMissingTranslationPlaceholders: false + enableRobotsTXT: false + environment: production + frontmatter: + date: + - date + - publishdate + - pubdate + - published + - lastmod + - modified + expiryDate: + - expirydate + - unpublishdate + lastmod: + - :git + - lastmod + - modified + - date + - publishdate + - pubdate + - published + publishDate: + - publishdate + - pubdate + - published + - date + hasCJKLanguage: false + i18nDir: i18n + ignoreCache: false + ignoreFiles: null + ignoreLogs: null - ignoreVendorPaths: '' ++ ignoreVendorPaths: "" + imaging: + bgColor: '#ffffff' + hint: photo + quality: 75 + resampleFilter: box - languageCode: '' ++ languageCode: "" + languages: + en: + disabled: false - languageCode: '' - languageDirection: '' - languageName: '' - title: '' ++ languageCode: "" ++ languageDirection: "" ++ languageName: "" ++ title: "" + weight: 0 + layoutDir: layouts + mainSections: null + markup: - asciiDocExt: ++ asciidocExt: + attributes: {} + backend: html5 + extensions: [] + failureLevel: fatal + noHeaderOrFooter: true + preserveTOC: false + safeMode: unsafe + sectionNumbers: false + trace: false + verbose: false + workingFolderCurrent: false + defaultMarkdownHandler: goldmark + goldmark: + duplicateResourceFiles: false + extensions: + cjk: + eastAsianLineBreaks: false + eastAsianLineBreaksStyle: simple + enable: false + escapedSpace: false + definitionList: true + extras: + delete: + enable: false + insert: + enable: false + mark: + enable: false + subscript: + enable: false + superscript: + enable: false + footnote: + backlinkHTML: '↩︎' + enable: true + enableAutoIDPrefix: false + linkify: true + linkifyProtocol: https + passthrough: + delimiters: + block: [] + inline: [] + enable: false + strikethrough: true + table: true + taskList: true + typographer: + apostrophe: '’' + disable: false + ellipsis: '…' + emDash: '—' + enDash: '–' + leftAngleQuote: '«' + leftDoubleQuote: '“' + leftSingleQuote: '‘' + rightAngleQuote: '»' + rightDoubleQuote: '”' + rightSingleQuote: '’' + parser: + attribute: + block: false + title: true + autoDefinitionTermID: false + autoHeadingID: true + autoIDType: github + wrapStandAloneImageWithinParagraph: true + renderHooks: + image: + enableDefault: false + useEmbedded: auto + link: + enableDefault: false + useEmbedded: auto + renderer: + hardWraps: false + unsafe: false + xhtml: false + highlight: + anchorLineNos: false + codeFences: true + guessSyntax: false - hl_Lines: '' ++ hl_Lines: "" + hl_inline: false - lineAnchors: '' ++ lineAnchors: "" + lineNoStart: 1 + lineNos: false + lineNumbersInTable: true + noClasses: true + style: monokai + tabWidth: 4 + wrapperClass: highlight + tableOfContents: + endLevel: 3 + ordered: false + startLevel: 2 + mediaTypes: + application/json: + delimiter: . + suffixes: + - json + application/manifest+json: + delimiter: . + suffixes: + - webmanifest + application/octet-stream: + delimiter: . + application/pdf: + delimiter: . + suffixes: + - pdf + application/rss+xml: + delimiter: . + suffixes: + - xml + - rss + application/toml: + delimiter: . + suffixes: + - toml + application/wasm: + delimiter: . + suffixes: + - wasm + application/xml: + delimiter: . + suffixes: + - xml + application/yaml: + delimiter: . + suffixes: + - yaml + - yml + font/otf: + delimiter: . + suffixes: + - otf + font/ttf: + delimiter: . + suffixes: + - ttf + image/bmp: + delimiter: . + suffixes: + - bmp + image/gif: + delimiter: . + suffixes: + - gif + image/jpeg: + delimiter: . + suffixes: + - jpg + - jpeg + - jpe + - jif + - jfif + image/png: + delimiter: . + suffixes: + - png + image/svg+xml: + delimiter: . + suffixes: + - svg + image/tiff: + delimiter: . + suffixes: + - tif + - tiff + image/webp: + delimiter: . + suffixes: + - webp + text/asciidoc: + delimiter: . + suffixes: + - adoc + - asciidoc + - ad + text/calendar: + delimiter: . + suffixes: + - ics + text/css: + delimiter: . + suffixes: + - css + text/csv: + delimiter: . + suffixes: + - csv + text/html: + delimiter: . + suffixes: + - html + - htm + text/javascript: + delimiter: . + suffixes: + - js + - jsm + - mjs + text/jsx: + delimiter: . + suffixes: + - jsx + text/markdown: + delimiter: . + suffixes: + - md + - mdown + - markdown + text/org: + delimiter: . + suffixes: + - org + text/pandoc: + delimiter: . + suffixes: + - pandoc + - pdc + text/plain: + delimiter: . + suffixes: + - txt + text/rst: + delimiter: . + suffixes: + - rst + text/tsx: + delimiter: . + suffixes: + - tsx + text/typescript: + delimiter: . + suffixes: + - ts + text/x-gotmpl: + delimiter: . + suffixes: + - gotmpl + text/x-sass: + delimiter: . + suffixes: + - sass + text/x-scss: + delimiter: . + suffixes: + - scss + video/3gpp: + delimiter: . + suffixes: + - 3gpp + - 3gp + video/mp4: + delimiter: . + suffixes: + - mp4 + video/mpeg: + delimiter: . + suffixes: + - mpg + - mpeg + video/ogg: + delimiter: . + suffixes: + - ogv + video/webm: + delimiter: . + suffixes: + - webm + video/x-msvideo: + delimiter: . + suffixes: + - avi + menus: {} + minify: + disableCSS: false + disableHTML: false + disableJS: false + disableJSON: false + disableSVG: false + disableXML: false + minifyOutput: false + tdewolff: + css: + inline: false ++ keepCSS2: false + precision: 0 + version: 0 + html: + keepComments: false + keepConditionalComments: false + keepDefaultAttrVals: true + keepDocumentTags: true + keepEndTags: true + keepQuotes: false + keepSpecialComments: true + keepWhitespace: false + templateDelims: - - '' - - '' ++ - "" ++ - "" + js: + keepVarNames: false + precision: 0 + version: 2022 + json: + keepNumbers: false + precision: 0 + svg: ++ inline: false + keepComments: false + precision: 0 + xml: + keepWhitespace: false + module: - auth: '' ++ auth: "" + hugoVersion: + extended: false - max: '' - min: '' ++ max: "" ++ min: "" + imports: null + mounts: + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: content + target: content + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: data + target: data + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: layouts + target: layouts + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: i18n + target: i18n + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: archetypes + target: archetypes + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: assets + target: assets + - disableWatch: false - files: null - sites: - complements: - languages: null - roles: null - versions: null - matrix: - languages: null - roles: null - versions: null ++ excludeFiles: null ++ includeFiles: null ++ lang: "" + source: static + target: static + noProxy: none - noVendor: '' ++ noVendor: "" + params: null + private: '*.*' + proxy: direct + replacements: null + vendorClosest: false - workspace: 'off' - newContentEditor: '' ++ workspace: "off" ++ newContentEditor: "" + noBuildLock: false + noChmod: false + noTimes: false + outputFormats: - '404': - baseName: '' ++ "404": ++ baseName: "" + isHTML: true + isPlainText: false + mediaType: text/html + noUgly: false + notAlternative: true - path: '' ++ path: "" + permalinkable: true - protocol: '' - rel: '' ++ protocol: "" ++ rel: "" + root: false + ugly: true + weight: 0 + alias: - baseName: '' ++ baseName: "" + isHTML: true + isPlainText: false + mediaType: text/html + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' - rel: '' ++ protocol: "" ++ rel: "" + root: false + ugly: true + weight: 0 + amp: + baseName: index + isHTML: true + isPlainText: false + mediaType: text/html + noUgly: false + notAlternative: false + path: amp + permalinkable: true - protocol: '' ++ protocol: "" + rel: amphtml + root: false + ugly: false + weight: 0 + calendar: + baseName: index + isHTML: false + isPlainText: true + mediaType: text/calendar + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false + protocol: webcal:// + rel: alternate + root: false + ugly: false + weight: 0 + css: + baseName: styles + isHTML: false + isPlainText: true + mediaType: text/css + noUgly: false + notAlternative: true - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: stylesheet + root: false + ugly: false + weight: 0 + csv: + baseName: index + isHTML: false + isPlainText: true + mediaType: text/csv + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: alternate + root: false + ugly: false + weight: 0 + gotmpl: - baseName: '' ++ baseName: "" + isHTML: false + isPlainText: true + mediaType: text/x-gotmpl + noUgly: false + notAlternative: true - path: '' ++ path: "" + permalinkable: false - protocol: '' - rel: '' ++ protocol: "" ++ rel: "" + root: false + ugly: false + weight: 0 + html: + baseName: index + isHTML: true + isPlainText: false + mediaType: text/html + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: true - protocol: '' ++ protocol: "" + rel: canonical + root: false + ugly: false + weight: 10 + json: + baseName: index + isHTML: false + isPlainText: true + mediaType: application/json + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: alternate + root: false + ugly: false + weight: 0 + markdown: + baseName: index + isHTML: false + isPlainText: true + mediaType: text/markdown + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: alternate + root: false + ugly: false + weight: 0 + robots: + baseName: robots + isHTML: false + isPlainText: true + mediaType: text/plain + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: alternate + root: true + ugly: false + weight: 0 + rss: + baseName: index + isHTML: false + isPlainText: false + mediaType: application/rss+xml + noUgly: true + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: alternate + root: false + ugly: false + weight: 0 + sitemap: + baseName: sitemap + isHTML: false + isPlainText: false + mediaType: application/xml + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: sitemap + root: false + ugly: true + weight: 0 + sitemapindex: + baseName: sitemap + isHTML: false + isPlainText: false + mediaType: application/xml + noUgly: false + notAlternative: false - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: sitemap + root: true + ugly: true + weight: 0 + webappmanifest: + baseName: manifest + isHTML: false + isPlainText: true + mediaType: application/manifest+json + noUgly: false + notAlternative: true - path: '' ++ path: "" + permalinkable: false - protocol: '' ++ protocol: "" + rel: manifest + root: false + ugly: false + weight: 0 + outputs: + home: + - html + - rss + page: + - html + rss: + - rss + section: + - html + - rss + taxonomy: + - html + - rss + term: + - html + - rss + page: + nextPrevInSectionSortOrder: desc + nextPrevSortOrder: desc + paginate: 0 - paginatePath: '' ++ paginatePath: "" + pagination: + disableAliases: false + pagerSize: 10 + path: page + panicOnWarning: false + params: {} + permalinks: + page: {} + section: {} + taxonomy: {} + term: {} + pluralizeListTitles: true + printI18nWarnings: false + printPathWarnings: false + printUnusedTemplates: false + privacy: + disqus: + disable: false + googleAnalytics: + disable: false - respectDoNotTrack: true ++ respectDoNotTrack: false + instagram: + disable: false + simple: false ++ twitter: ++ disable: false ++ enableDNT: false ++ simple: false + vimeo: + disable: false + enableDNT: false + simple: false + x: + disable: false + enableDNT: false + simple: false + youTube: + disable: false + privacyEnhanced: false + publishDir: public - refLinksErrorLevel: '' - refLinksNotFoundURL: '' ++ refLinksErrorLevel: "" ++ refLinksNotFoundURL: "" + related: + includeNewer: false + indices: + - applyFilter: false + cardinalityThreshold: 0 + name: keywords - pattern: '' ++ pattern: "" + toLower: false + type: basic + weight: 100 + - applyFilter: false + cardinalityThreshold: 0 + name: date - pattern: '' ++ pattern: "" + toLower: false + type: basic + weight: 10 + - applyFilter: false + cardinalityThreshold: 0 + name: tags - pattern: '' ++ pattern: "" + toLower: false + type: basic + weight: 80 + threshold: 80 + toLower: false + relativeURLs: false + removePathAccents: false + renderSegments: null + resourceDir: resources - roles: - guest: - weight: 0 - sectionPagesMenu: '' ++ sectionPagesMenu: "" + security: + enableInlineShortcodes: false + exec: + allow: + - ^(dart-)?sass(-embedded)?$ + - ^go$ + - ^git$ + - ^npx$ + - ^postcss$ + - ^tailwindcss$ + osEnv: - - '(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$' ++ - (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$ + funcs: + getenv: + - ^HUGO_ + - ^CI$ + http: + mediaTypes: null + methods: + - (?i)GET|POST + urls: + - .* + segments: {} + server: + headers: null + redirects: + - force: false + from: /** + fromHeaders: null - fromRe: '' ++ fromRe: "" + status: 404 + to: /404.html + services: + disqus: - shortname: '' ++ shortname: "" + googleAnalytics: - id: '' ++ id: "" ++ instagram: ++ accessToken: "" ++ disableInlineCSS: false + rss: + limit: -1 ++ twitter: ++ disableInlineCSS: false + x: + disableInlineCSS: false + sitemap: - changeFreq: '' ++ changeFreq: "" + disable: false + filename: sitemap.xml + priority: -1 + social: null + staticDir: + - static + staticDir0: null + staticDir1: null - staticDir10: null + staticDir2: null + staticDir3: null + staticDir4: null + staticDir5: null + staticDir6: null + staticDir7: null + staticDir8: null + staticDir9: null ++ staticDir10: null + summaryLength: 70 + taxonomies: + category: categories + tag: tags + templateMetrics: false + templateMetricsHints: false + theme: null + themesDir: themes - timeZone: '' ++ timeZone: "" + timeout: 60s - title: '' ++ title: "" + titleCaseStyle: AP + uglyURLs: {} - versions: - v1.0.0: - weight: 0 - workingDir: '' ++ workingDir: "" +config_helpers: + mergeStrategy: + build: + _merge: none + caches: + _merge: none + cascade: + _merge: none + contenttypes: + _merge: none + deployment: + _merge: none + frontmatter: + _merge: none + httpcache: + _merge: none + imaging: + _merge: none + languages: + _merge: none + en: + _merge: none + menus: + _merge: shallow + params: + _merge: deep + markup: + _merge: none + mediatypes: + _merge: shallow + menus: + _merge: shallow + minify: + _merge: none + module: + _merge: none + outputformats: + _merge: shallow + outputs: + _merge: none + page: + _merge: none + pagination: + _merge: none + params: + _merge: deep + permalinks: + _merge: none + privacy: + _merge: none + related: + _merge: none - roles: - _merge: none + security: + _merge: none + segments: + _merge: none + server: + _merge: none + services: + _merge: none + sitemap: + _merge: none + taxonomies: + _merge: none - versions: - _merge: none +output: + layouts: {} +tpl: + funcs: + cast: + ToFloat: + Aliases: + - float + Args: + - v + Description: ToFloat converts v to a float. + Examples: + - - '{{ "1234" | float | printf "%T" }}' + - float64 + ToInt: + Aliases: + - int + Args: + - v + Description: ToInt converts v to an int. + Examples: + - - '{{ "1234" | int | printf "%T" }}' + - int + ToString: + Aliases: + - string + Args: + - v + Description: ToString converts v to a string. + Examples: + - - '{{ 1234 | string | printf "%T" }}' + - string + collections: + After: + Aliases: + - after + Args: - - 'n' ++ - "n" + - l + Description: After returns all the items after the first n items in list l. + Examples: [] + Append: + Aliases: + - append + Args: + - args - Description: |- - Append appends args up to the last one to the slice in the last argument. - This construct allows template constructs like this: - - {{ $pages = $pages | append $p2 $p1 }} - - Note that with 2 arguments where both are slices of the same type, - the first slice will be appended to the second: - - {{ $pages = $pages | append .Site.RegularPages }} ++ Description: "Append appends args up to the last one to the slice in the last ++ argument.\nThis construct allows template constructs like this:\n\n\t{{ ++ $pages = $pages | append $p2 $p1 }}\n\nNote that with 2 arguments where ++ both are slices of the same type,\nthe first slice will be appended to the ++ second:\n\n\t{{ $pages = $pages | append .Site.RegularPages }}" + Examples: [] + Apply: + Aliases: + - apply + Args: + - ctx + - c + - fname + - args - Description: Apply takes an array or slice c and returns a new slice with the function fname applied over it. ++ Description: Apply takes an array or slice c and returns a new slice with ++ the function fname applied over it. + Examples: [] + Complement: + Aliases: + - complement + Args: + - ls - Description: |- - Complement gives the elements in the last element of ls that are not in - any of the others. - - All elements of ls must be slices or arrays of comparable types. - - The reasoning behind this rather clumsy API is so we can do this in the templates: - - {{ $c := .Pages | complement $last4 }} ++ Description: "Complement gives the elements in the last element of ls that ++ are not in\nany of the others.\n\nAll elements of ls must be slices or arrays ++ of comparable types.\n\nThe reasoning behind this rather clumsy API is so ++ we can do this in the templates:\n\n\t{{ $c := .Pages | complement $last4 ++ }}" + Examples: - - - '{{ slice "a" "b" "c" "d" "e" "f" | complement (slice "b" "c") (slice "d" "e") }}' ++ - - '{{ slice "a" "b" "c" "d" "e" "f" | complement (slice "b" "c") (slice ++ "d" "e") }}' + - '[a f]' + D: + Aliases: null - Args: - - seed - - 'n' - - hi - Description: 'D returns a sorted slice of unique random integers in the half-open interval\n[0, hi) using the provided seed value. The number of elements in the\nresulting slice is n or hi, whichever is less.\n\nIf n <= hi, it returns a sorted random sample of size n using J. S. Vitter’s\nMethod D for sequential random sampling.\n\nIf n > hi, it returns the full, sorted range [0, hi) of size hi.\n\nIf n == 0 or hi == 0, it returns an empty slice.\n\nReference:\n\n\tJ. S. Vitter, "An efficient algorithm for sequential random sampling," ACM Trans. Math. Softw., vol. 11, no. 1, pp. 37–57, 1985.\n\tSee also: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Delimit: + Aliases: + - delimit + Args: + - ctx + - l + - sep + - last + Description: |- + Delimit takes a given list l and returns a string delimited by sep. + If last is passed to the function, it will be used as the final delimiter. + Examples: + - - '{{ delimit (slice "A" "B" "C") ", " " and " }}' + - A, B and C + Dictionary: + Aliases: + - dict + Args: + - values + Description: |- + Dictionary creates a new map from the given parameters by + treating values as key-value pairs. The number of values must be even. + The keys can be string slices, which will create the needed nested structure. + Examples: [] + First: + Aliases: + - first + Args: + - limit + - l + Description: First returns the first limit items in list l. + Examples: [] + Group: + Aliases: + - group + Args: + - key + - items + Description: |- + Group groups a set of items by the given key. + This is currently only supported for Pages. + Examples: [] + In: + Aliases: + - in + Args: + - l + - v - Description: In returns whether v is in the list l. l may be an array or slice. ++ Description: In returns whether v is in the list l. l may be an array or ++ slice. + Examples: - - - '{{ if in "this string contains a substring" "substring" }}Substring found!{{ end }}' ++ - - '{{ if in "this string contains a substring" "substring" }}Substring found!{{ ++ end }}' + - Substring found! + Index: + Aliases: + - index + Args: + - item + - args + Description: |- + Index returns the result of indexing its first argument by the following + arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each + indexed item must be a map, slice, or array. - ++ + Adapted from Go stdlib src/text/template/funcs.go. - ++ + We deviate from the stdlib mostly because of https://github.com/golang/go/issues/14751. + Examples: [] + Intersect: + Aliases: + - intersect + Args: + - l1 + - l2 + Description: |- + Intersect returns the common elements in the given sets, l1 and l2. l1 and + l2 must be of the same type and may be either arrays or slices. + Examples: [] + IsSet: + Aliases: + - isSet + - isset + Args: + - c + - key + Description: |- + IsSet returns whether a given array, channel, slice, or map in c has the given key + defined. + Examples: [] + KeyVals: + Aliases: + - keyVals + Args: + - key + - values + Description: KeyVals creates a key and values wrapper. + Examples: + - - '{{ keyVals "key" "a" "b" }}' + - 'key: [a b]' + Last: + Aliases: + - last + Args: + - limit + - l + Description: Last returns the last limit items in the list l. + Examples: [] + Merge: + Aliases: + - merge + Args: + - params + Description: |- + Merge creates a copy of the final parameter in params and merges the preceding + parameters into it in reverse order. - ++ + Currently only maps are supported. Key handling is case insensitive. + Examples: - - - '{{ dict "title" "Hugo Rocks!" | collections.Merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") | sort }}' ++ - - '{{ dict "title" "Hugo Rocks!" | collections.Merge (dict "title" "Default ++ Title" "description" "Yes, Hugo Rocks!") | sort }}' + - '[Yes, Hugo Rocks! Hugo Rocks!]' - - - '{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") (dict "title" "Hugo Rocks!") | sort }}' ++ - - '{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") ++ (dict "title" "Hugo Rocks!") | sort }}' + - '[Yes, Hugo Rocks! Hugo Rocks!]' - - - '{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") (dict "title" "Hugo Rocks!") (dict "extra" "For reals!") | sort }}' ++ - - '{{ merge (dict "title" "Default Title" "description" "Yes, Hugo Rocks!") ++ (dict "title" "Hugo Rocks!") (dict "extra" "For reals!") | sort }}' + - '[Yes, Hugo Rocks! For reals! Hugo Rocks!]' + NewScratch: + Aliases: + - newScratch + Args: null + Description: |- + NewScratch creates a new Scratch which can be used to store values in a + thread safe way. + Examples: - - - '{{ $scratch := newScratch }}{{ $scratch.Add "b" 2 }}{{ $scratch.Add "b" 2 }}{{ $scratch.Get "b" }}' - - '4' ++ - - '{{ $scratch := newScratch }}{{ $scratch.Add "b" 2 }}{{ $scratch.Add "b" ++ 2 }}{{ $scratch.Get "b" }}' ++ - "4" + Querify: + Aliases: + - querify + Args: + - params + Description: |- + Querify returns a URL query string composed of the given key-value pairs, + encoded and sorted by key. + Examples: - - - '{{ (querify "foo" 1 "bar" 2 "baz" "with spaces" "qux" "this&that=those") | safeHTML }}' ++ - - '{{ (querify "foo" 1 "bar" 2 "baz" "with spaces" "qux" "this&that=those") ++ | safeHTML }}' + - bar=2&baz=with+spaces&foo=1&qux=this%26that%3Dthose - - - Search ++ - - Search + - Search + - - '{{ slice "foo" 1 "bar" 2 | querify | safeHTML }}' + - bar=2&foo=1 + Reverse: + Aliases: null - Args: - - l - Description: Reverse creates a copy of the list l and reverses it. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Seq: + Aliases: + - seq + Args: + - args - Description: |- - Seq creates a sequence of integers from args. It's named and used as GNU's seq. - - Examples: - - 3 => 1, 2, 3 - 1 2 4 => 1, 3 - -3 => -1, -2, -3 - 1 4 => 1, 2, 3, 4 - 1 -2 => 1, 0, -1, -2 ++ Description: "Seq creates a sequence of integers from args. It's named and ++ used as GNU's seq.\n\nExamples:\n\n\t3 => 1, 2, 3\n\t1 2 4 => 1, 3\n\t-3 ++ => -1, -2, -3\n\t1 4 => 1, 2, 3, 4\n\t1 -2 => 1, 0, -1, -2" + Examples: + - - '{{ seq 3 }}' + - '[1 2 3]' + Shuffle: + Aliases: + - shuffle + Args: + - l + Description: Shuffle returns list l in a randomized order. + Examples: [] + Slice: + Aliases: + - slice + Args: + - args + Description: Slice returns a slice of all passed arguments. + Examples: + - - '{{ slice "B" "C" "A" | sort }}' + - '[A B C]' + Sort: + Aliases: + - sort + Args: + - ctx + - l + - args + Description: Sort returns a sorted copy of the list l. + Examples: [] + SymDiff: + Aliases: + - symdiff + Args: + - s2 + - s1 + Description: |- + SymDiff returns the symmetric difference of s1 and s2. + Arguments must be either a slice or an array of comparable types. + Examples: + - - '{{ slice 1 2 3 | symdiff (slice 3 4) }}' + - '[1 2 4]' + Union: + Aliases: + - union + Args: + - l1 + - l2 + Description: |- + Union returns the union of the given sets, l1 and l2. l1 and + l2 must be of the same type and may be either arrays or slices. + If l1 and l2 aren't of the same type then l1 will be returned. + If either l1 or l2 is nil then the non-nil list will be returned. + Examples: + - - '{{ union (slice 1 2 3) (slice 3 4 5) }}' + - '[1 2 3 4 5]' + Uniq: + Aliases: + - uniq + Args: + - l - Description: Uniq returns a new list with duplicate elements in the list l removed. ++ Description: Uniq returns a new list with duplicate elements in the list l ++ removed. + Examples: + - - '{{ slice 1 2 3 2 | uniq }}' + - '[1 2 3]' + Where: + Aliases: + - where + Args: + - ctx + - c + - key + - args + Description: Where returns a filtered subset of collection c. + Examples: [] + compare: + Conditional: + Aliases: + - cond + Args: + - cond + - v1 + - v2 + Description: |- + Conditional can be used as a ternary operator. - ++ + It returns v1 if cond is true, else v2. + Examples: + - - '{{ cond (eq (add 2 2) 4) "2+2 is 4" "what?" | safeHTML }}' + - 2+2 is 4 + Default: + Aliases: + - default + Args: + - defaultv + - givenv + Description: |- + Default checks whether a givenv is set and returns the default value defaultv if it + is not. "Set" in this context means non-zero for numeric types and times; + non-zero length for strings, arrays, slices, and maps; + any boolean or struct value; or non-nil for any other types. + Examples: + - - '{{ "Hugo Rocks!" | default "Hugo Rules!" }}' + - Hugo Rocks! + - - '{{ "" | default "Hugo Rules!" }}' + - Hugo Rules! + Eq: + Aliases: + - eq + Args: + - first + - others - Description: Eq returns the boolean truth of arg1 == arg2 || arg1 == arg3 || arg1 == arg4. ++ Description: Eq returns the boolean truth of arg1 == arg2 || arg1 == arg3 ++ || arg1 == arg4. + Examples: + - - '{{ if eq .Section "blog" }}current-section{{ end }}' + - current-section + Ge: + Aliases: + - ge + Args: + - first + - others - Description: Ge returns the boolean truth of arg1 >= arg2 && arg1 >= arg3 && arg1 >= arg4. ++ Description: Ge returns the boolean truth of arg1 >= arg2 && arg1 >= arg3 ++ && arg1 >= arg4. + Examples: + - - '{{ if ge hugo.Version "0.80" }}Reasonable new Hugo version!{{ end }}' + - Reasonable new Hugo version! + Gt: + Aliases: + - gt + Args: + - first + - others - Description: Gt returns the boolean truth of arg1 > arg2 && arg1 > arg3 && arg1 > arg4. ++ Description: Gt returns the boolean truth of arg1 > arg2 && arg1 > arg3 && ++ arg1 > arg4. + Examples: [] + Le: + Aliases: + - le + Args: + - first + - others - Description: Le returns the boolean truth of arg1 <= arg2 && arg1 <= arg3 && arg1 <= arg4. ++ Description: Le returns the boolean truth of arg1 <= arg2 && arg1 <= arg3 ++ && arg1 <= arg4. + Examples: [] + Lt: + Aliases: + - lt + Args: + - first + - others - Description: Lt returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4. ++ Description: Lt returns the boolean truth of arg1 < arg2 && arg1 < arg3 && ++ arg1 < arg4. + Examples: [] + LtCollate: + Aliases: null - Args: - - collator - - first - - others - Description: |- - LtCollate returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4. - The provided collator will be used for string comparisons. - This is for internal use. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Ne: + Aliases: + - ne + Args: + - first + - others - Description: Ne returns the boolean truth of arg1 != arg2 && arg1 != arg3 && arg1 != arg4. ++ Description: Ne returns the boolean truth of arg1 != arg2 && arg1 != arg3 ++ && arg1 != arg4. + Examples: [] + crypto: + FNV32a: + Aliases: null - Args: - - v - Description: 'FNV32a hashes v using fnv32a algorithm.\n{"newIn": "0.98.0" }' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + HMAC: + Aliases: + - hmac + Args: + - h + - k + - m + - e + Description: HMAC returns a cryptographic hash that uses a key to sign a message. + Examples: + - - '{{ hmac "sha256" "Secret key" "Hello world, gophers!" }}' + - b6d11b6c53830b9d87036272ca9fe9d19306b8f9d8aa07b15da27d89e6e34f40 + MD5: + Aliases: + - md5 + Args: + - v + Description: MD5 hashes the v and returns its MD5 checksum. + Examples: + - - '{{ md5 "Hello world, gophers!" }}' + - b3029f756f98f79e7f1b7f1d1f0dd53b + - - '{{ crypto.MD5 "Hello world, gophers!" }}' + - b3029f756f98f79e7f1b7f1d1f0dd53b + SHA1: + Aliases: + - sha1 + Args: + - v + Description: SHA1 hashes v and returns its SHA1 checksum. + Examples: + - - '{{ sha1 "Hello world, gophers!" }}' + - c8b5b0e33d408246e30f53e32b8f7627a7a649d4 + SHA256: + Aliases: + - sha256 + Args: + - v + Description: SHA256 hashes v and returns its SHA256 checksum. + Examples: + - - '{{ sha256 "Hello world, gophers!" }}' + - 6ec43b78da9669f50e4e422575c54bf87536954ccd58280219c393f2ce352b46 + css: + PostCSS: + Aliases: + - postCSS + Args: + - args + Description: PostCSS processes the given Resource with PostCSS. + Examples: [] + Quoted: + Aliases: null - Args: - - v - Description: Quoted returns a string that needs to be quoted in CSS. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Sass: + Aliases: + - toCSS + Args: + - args + Description: Sass processes the given Resource with SASS. + Examples: [] + TailwindCSS: + Aliases: null - Args: - - args - Description: TailwindCSS processes the given Resource with tailwindcss. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Unquoted: + Aliases: null - Args: - - v - Description: Unquoted returns a string that does not need to be quoted in CSS. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + data: + GetCSV: + Aliases: + - getCSV + Args: + - sep + - args + Description: |- + GetCSV expects the separator sep and one or n-parts of a URL to a resource which + can either be a local or a remote one. + The data separator can be a comma, semi-colon, pipe, etc, but only one character. + If you provide multiple parts for the URL they will be joined together to the final URL. + GetCSV returns nil or a slice slice to use in a short code. + Examples: [] + GetJSON: + Aliases: + - getJSON + Args: + - args + Description: |- + GetJSON expects one or n-parts of a URL in args to a resource which can either be a local or a remote one. + If you provide multiple parts they will be joined together to the final URL. + GetJSON returns nil or parsed JSON to use in a short code. + Examples: [] + debug: + Dump: + Aliases: null + Args: + - val + Description: |- + Dump returns a object dump of val as a string. + Note that not every value passed to Dump will print so nicely, but + we'll improve on that. - ++ + We recommend using the "go" Chroma lexer to format the output + nicely. - ++ + Also note that the output from Dump may change from Hugo version to the next, + so don't depend on a specific output. + Examples: - - - '{{ $m := newScratch }}\n{{ $m.Set "Hugo" "Rocks!" }}\n{{ $m.Values | debug.Dump | safeHTML }}' - - '{\n "Hugo": "Rocks!"\n}' ++ - - |- ++ {{ $m := newScratch }} ++ {{ $m.Set "Hugo" "Rocks!" }} ++ {{ $m.Values | debug.Dump | safeHTML }} ++ - |- ++ { ++ "Hugo": "Rocks!" ++ } + TestDeprecationErr: + Aliases: null - Args: - - item - - alternative - Description: Internal template func, used in tests only. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + TestDeprecationInfo: + Aliases: null - Args: - - item - - alternative - Description: Internal template func, used in tests only. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + TestDeprecationWarn: + Aliases: null - Args: - - item - - alternative - Description: Internal template func, used in tests only. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Timer: + Aliases: null - Args: - - name - Description: '' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + VisualizeSpaces: + Aliases: null - Args: - - val - Description: VisualizeSpaces returns a string with spaces replaced by a visible string. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + diagrams: + Goat: + Aliases: null - Args: - - v - Description: Goat creates a new SVG diagram from input v. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + encoding: + Base64Decode: + Aliases: + - base64Decode + Args: + - content + Description: Base64Decode returns the base64 decoding of the given content. + Examples: + - - '{{ "SGVsbG8gd29ybGQ=" | base64Decode }}' + - Hello world + - - '{{ 42 | base64Encode | base64Decode }}' - - '42' ++ - "42" + Base64Encode: + Aliases: + - base64Encode + Args: + - content + Description: Base64Encode returns the base64 encoding of the given content. + Examples: + - - '{{ "Hello world" | base64Encode }}' + - SGVsbG8gd29ybGQ= + Jsonify: + Aliases: + - jsonify + Args: + - args + Description: |- + Jsonify encodes a given object to JSON. To pretty print the JSON, pass a map + or dictionary of options as the first value in args. Supported options are + "prefix" and "indent". Each JSON element in the output will begin on a new + line beginning with prefix followed by one or more copies of indent according + to the indentation nesting. + Examples: + - - '{{ (slice "A" "B" "C") | jsonify }}' + - '["A","B","C"]' + - - '{{ (slice "A" "B" "C") | jsonify (dict "indent" " ") }}' - - '[\n "A",\n "B",\n "C"\n]' ++ - |- ++ [ ++ "A", ++ "B", ++ "C" ++ ] + fmt: + Errorf: + Aliases: + - errorf + Args: + - format + - args + Description: |- + Errorf formats args according to a format specifier and logs an ERROR. + It returns an empty string. + Examples: + - - '{{ errorf "%s." "failed" }}' - - '' ++ - "" + Erroridf: + Aliases: + - erroridf + Args: + - id + - format + - args + Description: |- + Erroridf formats args according to a format specifier and logs an ERROR and + an information text that the error with the given id can be suppressed in config. + It returns an empty string. + Examples: + - - '{{ erroridf "my-err-id" "%s." "failed" }}' - - '' ++ - "" + Errormf: + Aliases: null - Args: - - m - - format - - args - Description: Errormf is experimental and subject to change at any time. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Print: + Aliases: + - print + Args: + - args + Description: Print returns a string representation of args. + Examples: + - - '{{ print "works!" }}' + - works! + Printf: + Aliases: + - printf + Args: + - format + - args - Description: Printf returns string representation of args formatted with the layout in format. ++ Description: Printf returns string representation of args formatted with the ++ layout in format. + Examples: + - - '{{ printf "%s!" "works" }}' + - works! + Println: + Aliases: + - println + Args: + - args - Description: Println returns string representation of args ending with a newline. ++ Description: Println returns string representation of args ending with a ++ newline. + Examples: + - - '{{ println "works!" }}' + - | + works! + Warnf: + Aliases: + - warnf + Args: + - format + - args + Description: |- + Warnf formats args according to a format specifier and logs a WARNING. + It returns an empty string. + Examples: + - - '{{ warnf "%s." "warning" }}' - - '' ++ - "" + Warnidf: + Aliases: + - warnidf + Args: + - id + - format + - args + Description: |- + Warnidf formats args according to a format specifier and logs an WARNING and + an information text that the warning with the given id can be suppressed in config. + It returns an empty string. + Examples: + - - '{{ warnidf "my-warn-id" "%s." "warning" }}' - - '' ++ - "" + Warnmf: + Aliases: null - Args: - - m - - format - - args - Description: Warnmf is experimental and subject to change at any time. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + hash: + FNV32a: + Aliases: null + Args: + - v + Description: FNV32a hashes v using fnv32a algorithm. + Examples: + - - '{{ hash.FNV32a "Hugo Rocks!!" }}' - - '1515779328' ++ - "1515779328" + XxHash: + Aliases: + - xxhash + Args: + - v + Description: XxHash returns the xxHash of the input string. + Examples: + - - '{{ hash.XxHash "The quick brown fox jumps over the lazy dog" }}' + - 0b242d361fda71bc + hugo: + Deps: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Generator: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsDevelopment: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsExtended: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsMultiHost: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsMultihost: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsMultilingual: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsProduction: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsServer: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Store: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Version: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + WorkingDir: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + images: + AutoOrient: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Brightness: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + ColorBalance: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Colorize: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Config: + Aliases: + - imageConfig + Args: + - path + Description: |- + Config returns the image.Config for the specified path relative to the + working directory. + Examples: [] + Contrast: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Dither: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Filter: + Aliases: null - Args: - - args - Description: Filter applies the given filters to the image given as the last element in args. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Gamma: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + GaussianBlur: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Grayscale: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Hue: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Invert: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Mask: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Opacity: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Overlay: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Padding: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Pixelate: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Process: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + QR: + Aliases: null - Args: - - args - Description: |- - QR encodes the given text into a QR code using the specified options, - returning an image resource. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Saturation: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Sepia: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Sigmoid: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Text: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + UnsharpMask: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + inflect: + Humanize: + Aliases: + - humanize + Args: + - v + Description: |- + Humanize returns the humanized form of v. - ++ + If v is either an integer or a string containing an integer + value, the behavior is to add the appropriate ordinal. + Examples: + - - '{{ humanize "my-first-post" }}' + - My first post + - - '{{ humanize "myCamelPost" }}' + - My camel post + - - '{{ humanize "52" }}' + - 52nd + - - '{{ humanize 103 }}' + - 103rd + Pluralize: + Aliases: + - pluralize + Args: + - v + Description: Pluralize returns the plural form of the single word in v. + Examples: + - - '{{ "cat" | pluralize }}' + - cats + Singularize: + Aliases: + - singularize + Args: + - v + Description: Singularize returns the singular form of a single word in v. + Examples: + - - '{{ "cats" | singularize }}' + - cat + js: + Babel: + Aliases: + - babel + Args: + - args + Description: Babel processes the given Resource with Babel. + Examples: [] + Batch: + Aliases: null - Args: - - id - Description: |- - Batch creates a new Batcher with the given ID. - Repeated calls with the same ID will return the same Batcher. - The ID will be used to name the root directory of the batch. - Forward slashes in the ID is allowed. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Build: + Aliases: null - Args: - - args - Description: Build processes the given Resource with ESBuild. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + lang: + FormatAccounting: + Aliases: null + Args: + - precision + - currency + - number + Description: |- + FormatAccounting returns the currency representation of number for the given currency and precision + for the current language in accounting notation. - ++ + The return value is formatted with at least two decimal places. + Examples: + - - '{{ 512.5032 | lang.FormatAccounting 2 "NOK" }}' + - NOK512.50 + FormatCurrency: + Aliases: null + Args: + - precision + - currency + - number + Description: |- + FormatCurrency returns the currency representation of number for the given currency and precision + for the current language. - ++ + The return value is formatted with at least two decimal places. + Examples: + - - '{{ 512.5032 | lang.FormatCurrency 2 "USD" }}' + - $512.50 + FormatNumber: + Aliases: null + Args: + - precision + - number - Description: FormatNumber formats number with the given precision for the current language. ++ Description: FormatNumber formats number with the given precision for the ++ current language. + Examples: + - - '{{ 512.5032 | lang.FormatNumber 2 }}' - - '512.50' ++ - "512.50" + FormatNumberCustom: + Aliases: null + Args: + - precision + - number + - options - Description: 'FormatNumberCustom formats a number with the given precision. The first\noptions parameter is a space-delimited string of characters to represent\nnegativity, the decimal point, and grouping. The default value is `- . ,`.\nThe second options parameter defines an alternate delimiting character.\n\nNote that numbers are rounded up at 5 or greater.\nSo, with precision set to 0, 1.5 becomes `2`, and 1.4 becomes `1`.\n\nFor a simpler function that adapts to the current language, see FormatNumber.' ++ Description: |- ++ FormatNumberCustom formats a number with the given precision. The first ++ options parameter is a space-delimited string of characters to represent ++ negativity, the decimal point, and grouping. The default value is `- . ,`. ++ The second options parameter defines an alternate delimiting character. ++ ++ Note that numbers are rounded up at 5 or greater. ++ So, with precision set to 0, 1.5 becomes `2`, and 1.4 becomes `1`. ++ ++ For a simpler function that adapts to the current language, see FormatNumber. + Examples: + - - '{{ lang.FormatNumberCustom 2 12345.6789 }}' + - 12,345.68 + - - '{{ lang.FormatNumberCustom 2 12345.6789 "- , ." }}' + - 12.345,68 + - - '{{ lang.FormatNumberCustom 6 -12345.6789 "- ." }}' - - '-12345.678900' ++ - "-12345.678900" + - - '{{ lang.FormatNumberCustom 0 -12345.6789 "- . ," }}' + - -12,346 + - - '{{ lang.FormatNumberCustom 0 -12345.6789 "-|.| " "|" }}' + - -12 346 + - - '{{ -98765.4321 | lang.FormatNumberCustom 2 }}' + - -98,765.43 + FormatPercent: + Aliases: null + Args: + - precision + - number + Description: |- + FormatPercent formats number with the given precision for the current language. + Note that the number is assumed to be a percentage. + Examples: + - - '{{ 512.5032 | lang.FormatPercent 2 }}' + - 512.50% + Merge: + Aliases: null - Args: - - p2 - - p1 - Description: Merge creates a union of pages from two languages. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Translate: + Aliases: + - i18n + - T + Args: + - ctx + - id + - args + Description: Translate returns a translated string for id. + Examples: [] + math: + Abs: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Abs returns the absolute value of n. + Examples: + - - '{{ math.Abs -2.1 }}' - - '2.1' ++ - "2.1" + Acos: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Acos returns the arccosine, in radians, of n. + Examples: + - - '{{ math.Acos 1 }}' - - '0' ++ - "0" + Add: + Aliases: + - add + Args: + - inputs + Description: Add adds the multivalued addends n1 and n2 or more values. + Examples: + - - '{{ add 1 2 }}' - - '3' ++ - "3" + Asin: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Asin returns the arcsine, in radians, of n. + Examples: + - - '{{ math.Asin 1 }}' - - '1.5707963267948966' ++ - "1.5707963267948966" + Atan: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Atan returns the arctangent, in radians, of n. + Examples: + - - '{{ math.Atan 1 }}' - - '0.7853981633974483' ++ - "0.7853981633974483" + Atan2: + Aliases: null + Args: - - 'n' ++ - "n" + - m - Description: Atan2 returns the arc tangent of n/m, using the signs of the two to determine the quadrant of the return value. ++ Description: Atan2 returns the arc tangent of n/m, using the signs of the ++ two to determine the quadrant of the return value. + Examples: + - - '{{ math.Atan2 1 2 }}' - - '0.4636476090008061' ++ - "0.4636476090008061" + Ceil: + Aliases: null + Args: - - 'n' - Description: Ceil returns the least integer value greater than or equal to n. ++ - "n" ++ Description: Ceil returns the least integer value greater than or equal to ++ n. + Examples: + - - '{{ math.Ceil 2.1 }}' - - '3' ++ - "3" + Cos: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Cos returns the cosine of the radian argument n. + Examples: + - - '{{ math.Cos 1 }}' - - '0.5403023058681398' ++ - "0.5403023058681398" + Counter: + Aliases: null + Args: null - Description: 'Counter increments and returns a global counter.\nThis was originally added to be used in tests where now.UnixNano did not\nhave the needed precision (especially on Windows).\nNote that given the parallel nature of Hugo, you cannot use this to get sequences of numbers,\nand the counter will reset on new builds.\n{"identifiers": ["now.UnixNano"] }' - Examples: [] ++ Description: "" ++ Examples: null + Div: + Aliases: + - div + Args: + - inputs + Description: Div divides n1 by n2. + Examples: + - - '{{ div 6 3 }}' - - '2' ++ - "2" + Floor: + Aliases: null + Args: - - 'n' - Description: Floor returns the greatest integer value less than or equal to n. ++ - "n" ++ Description: Floor returns the greatest integer value less than or equal to ++ n. + Examples: + - - '{{ math.Floor 1.9 }}' - - '1' ++ - "1" + Log: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Log returns the natural logarithm of the number n. + Examples: + - - '{{ math.Log 1 }}' - - '0' ++ - "0" + Max: + Aliases: null + Args: + - inputs - Description: Max returns the greater of all numbers in inputs. Any slices in inputs are flattened. ++ Description: Max returns the greater of all numbers in inputs. Any slices ++ in inputs are flattened. + Examples: + - - '{{ math.Max 1 2 }}' - - '2' ++ - "2" + MaxInt64: + Aliases: null + Args: null + Description: MaxInt64 returns the maximum value for a signed 64-bit integer. + Examples: + - - '{{ math.MaxInt64 }}' - - '9223372036854775807' ++ - "9223372036854775807" + Min: + Aliases: null + Args: + - inputs - Description: Min returns the smaller of all numbers in inputs. Any slices in inputs are flattened. ++ Description: Min returns the smaller of all numbers in inputs. Any slices ++ in inputs are flattened. + Examples: + - - '{{ math.Min 1 2 }}' - - '1' ++ - "1" + Mod: + Aliases: + - mod + Args: + - n1 + - n2 + Description: Mod returns n1 % n2. + Examples: + - - '{{ mod 15 3 }}' - - '0' ++ - "0" + ModBool: + Aliases: + - modBool + Args: + - n1 + - n2 - Description: ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return true. ++ Description: ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return ++ true. + Examples: + - - '{{ modBool 15 3 }}' - - 'true' ++ - "true" + Mul: + Aliases: + - mul + Args: + - inputs + Description: Mul multiplies the multivalued numbers n1 and n2 or more values. + Examples: + - - '{{ mul 2 3 }}' - - '6' ++ - "6" + Pi: + Aliases: null + Args: null + Description: Pi returns the mathematical constant pi. + Examples: + - - '{{ math.Pi }}' - - '3.141592653589793' ++ - "3.141592653589793" + Pow: + Aliases: + - pow + Args: + - n1 + - n2 + Description: Pow returns n1 raised to the power of n2. + Examples: + - - '{{ math.Pow 2 3 }}' - - '8' ++ - "8" + Product: + Aliases: null - Args: - - inputs - Description: Product returns the product of all numbers in inputs. Any slices in inputs are flattened. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Rand: + Aliases: null + Args: null - Description: Rand returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0). ++ Description: Rand returns, as a float64, a pseudo-random number in the half-open ++ interval [0.0,1.0). + Examples: + - - '{{ math.Rand }}' - - '0.6312770459590062' ++ - "0.6312770459590062" + Round: + Aliases: null + Args: - - 'n' - Description: Round returns the integer nearest to n, rounding half away from zero. ++ - "n" ++ Description: Round returns the integer nearest to n, rounding half away from ++ zero. + Examples: + - - '{{ math.Round 1.5 }}' - - '2' ++ - "2" + Sin: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Sin returns the sine of the radian argument n. + Examples: + - - '{{ math.Sin 1 }}' - - '0.8414709848078965' ++ - "0.8414709848078965" + Sqrt: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Sqrt returns the square root of the number n. + Examples: + - - '{{ math.Sqrt 81 }}' - - '9' ++ - "9" + Sub: + Aliases: + - sub + Args: + - inputs + Description: Sub subtracts multivalued. + Examples: + - - '{{ sub 3 2 }}' - - '1' ++ - "1" + Sum: + Aliases: null - Args: - - inputs - Description: Sum returns the sum of all numbers in inputs. Any slices in inputs are flattened. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Tan: + Aliases: null + Args: - - 'n' ++ - "n" + Description: Tan returns the tangent of the radian argument n. + Examples: + - - '{{ math.Tan 1 }}' - - '1.557407724654902' ++ - "1.557407724654902" + ToDegrees: + Aliases: null + Args: - - 'n' ++ - "n" + Description: ToDegrees converts radians into degrees. + Examples: + - - '{{ math.ToDegrees 1.5707963267948966 }}' - - '90' ++ - "90" + ToRadians: + Aliases: null + Args: - - 'n' ++ - "n" + Description: ToRadians converts degrees into radians. + Examples: + - - '{{ math.ToRadians 90 }}' - - '1.5707963267948966' ++ - "1.5707963267948966" + openapi3: + Unmarshal: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: [] + os: + FileExists: + Aliases: + - fileExists + Args: + - i + Description: FileExists checks whether a file exists under the given path. + Examples: + - - '{{ fileExists "foo.txt" }}' - - 'false' ++ - "false" + Getenv: + Aliases: + - getenv + Args: + - key + Description: |- + Getenv retrieves the value of the environment variable named by the key. + It returns the value, which will be empty if the variable is not present. + Examples: [] + ReadDir: + Aliases: + - readDir + Args: + - i - Description: ReadDir lists the directory contents relative to the configured WorkingDir. ++ Description: ReadDir lists the directory contents relative to the configured ++ WorkingDir. + Examples: + - - '{{ range (readDir "files") }}{{ .Name }}{{ end }}' + - README.txt + ReadFile: + Aliases: + - readFile + Args: + - i + Description: |- + ReadFile reads the file named by filename relative to the configured WorkingDir. + It returns the contents as a string. + There is an upper size limit set at 1 megabytes. + Examples: + - - '{{ readFile "files/README.txt" }}' + - Hugo Rocks! + Stat: + Aliases: null - Args: - - i - Description: Stat returns the os.FileInfo structure describing file. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + partials: + Include: + Aliases: + - partial + Args: + - ctx + - name + - contextList + Description: |- + Include executes the named partial. + If the partial contains a return statement, that value will be returned. + Else, the rendered output will be returned: + A string if the partial is a text/template, or template.HTML when html/template. + Note that ctx is provided by Hugo, not the end user. + Examples: + - - '{{ partial "header.html" . }}' + - Hugo Rocks! + IncludeCached: + Aliases: + - partialCached + Args: + - ctx + - name + - context + - variants + Description: |- + IncludeCached executes and caches partial templates. The cache is created with name+variants as the key. + Note that ctx is provided by Hugo, not the end user. + Examples: [] + path: + Base: + Aliases: null - Args: - - path - Description: |- - Base returns the last element of path. - Trailing slashes are removed before extracting the last element. - If the path is empty, Base returns ".". - If the path consists entirely of slashes, Base returns "/". - The input path is passed into filepath.ToSlash converting any Windows slashes - to forward slashes. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + BaseName: + Aliases: null - Args: - - path - Description: |- - BaseName returns the last element of path, removing the extension if present. - Trailing slashes are removed before extracting the last element. - If the path is empty, Base returns ".". - If the path consists entirely of slashes, Base returns "/". - The input path is passed into filepath.ToSlash converting any Windows slashes - to forward slashes. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Clean: + Aliases: null - Args: - - path - Description: |- - Clean replaces the separators used with standard slashes and then - extraneous slashes are removed. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Dir: + Aliases: null - Args: - - path - Description: |- - Dir returns all but the last element of path, typically the path's directory. - After dropping the final element using Split, the path is Cleaned and trailing - slashes are removed. - If the path is empty, Dir returns ".". - If the path consists entirely of slashes followed by non-slash bytes, Dir - returns a single slash. In any other case, the returned path does not end in a - slash. - The input path is passed into filepath.ToSlash converting any Windows slashes - to forward slashes. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Ext: + Aliases: null - Args: - - path - Description: |- - Ext returns the file name extension used by path. - The extension is the suffix beginning at the final dot - in the final slash-separated element of path; - it is empty if there is no dot. - The input path is passed into filepath.ToSlash converting any Windows slashes - to forward slashes. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Join: + Aliases: null + Args: + - elements + Description: |- + Join joins any number of path elements into a single path, adding a + separating slash if necessary. All the input + path elements are passed into filepath.ToSlash converting any Windows slashes + to forward slashes. + The result is Cleaned; in particular, + all empty strings are ignored. + Examples: + - - '{{ slice "my/path" "filename.txt" | path.Join }}' + - my/path/filename.txt + - - '{{ path.Join "my" "path" "filename.txt" }}' + - my/path/filename.txt + - - '{{ "my/path/filename.txt" | path.Ext }}' + - .txt + - - '{{ "my/path/filename.txt" | path.Base }}' + - filename.txt + - - '{{ "my/path/filename.txt" | path.Dir }}' + - my/path + Split: + Aliases: null + Args: + - path + Description: |- + Split splits path immediately following the final slash, + separating it into a directory and file name component. + If there is no slash in path, Split returns an empty dir and + file set to path. + The input path is passed into filepath.ToSlash converting any Windows slashes + to forward slashes. + The returned values have the property that path = dir+file. + Examples: + - - '{{ "/my/path/filename.txt" | path.Split }}' + - /my/path/|filename.txt + - - '{{ "/my/path/filename.txt" | path.Split }}' + - /my/path/|filename.txt + reflect: + IsMap: + Aliases: null + Args: + - v + Description: IsMap reports whether v is a map. + Examples: + - - '{{ if reflect.IsMap (dict "a" 1) }}Map{{ end }}' + - Map + IsSlice: + Aliases: null + Args: + - v + Description: IsSlice reports whether v is a slice. + Examples: + - - '{{ if reflect.IsSlice (slice 1 2 3) }}Slice{{ end }}' + - Slice + resources: + Babel: + Aliases: null - Args: - - args - Description: 'Babel processes the given Resource with Babel.\nDeprecated: Moved to the js namespace in Hugo 0.128.0.' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + ByType: + Aliases: null - Args: - - typ - Description: ByType returns resources of a given resource type (e.g. "image"). - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Concat: + Aliases: null - Args: - - targetPathIn - - r - Description: |- - Concat concatenates a slice of Resource objects. These resources must - (currently) be of the same Media Type. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Copy: + Aliases: null - Args: - - s - - r - Description: Copy copies r to the new targetPath in s. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + ExecuteAsTemplate: + Aliases: null - Args: - - ctx - - args - Description: |- - ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with - the given data, and published to the relative target path. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Fingerprint: + Aliases: + - fingerprint + Args: + - args + Description: |- + Fingerprint transforms the given Resource with a MD5 hash of the content in + the RelPermalink and Permalink. + Examples: [] + FromString: + Aliases: null - Args: - - targetPathIn - - contentIn - Description: FromString creates a Resource from a string published to the relative target path. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Get: + Aliases: null + Args: + - filename + Description: |- + Get locates the filename given in Hugo's assets filesystem + and creates a Resource object that can be used for further transformations. + Examples: [] + GetMatch: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + GetRemote: + Aliases: null + Args: + - args - Description: 'GetRemote gets the URL (via HTTP(s)) in the first argument in args and creates Resource object that can be used for\nfurther transformations.\n\nA second argument may be provided with an option map.\n\nNote: This method does not return any error as a second return value,\nfor any error situations the error can be checked in .Err.' ++ Description: |- ++ GetRemote gets the URL (via HTTP(s)) in the first argument in args and creates Resource object that can be used for ++ further transformations. ++ ++ A second argument may be provided with an option map. ++ ++ Note: This method does not return any error as a second return value, ++ for any error situations the error can be checked in .Err. + Examples: [] + Match: + Aliases: null - Args: - - pattern - Description: |- - Match gets all resources matching the given base path prefix, e.g - "*.png" will match all png files. The "*" does not match path delimiters (/), - so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: - "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and - to match all PNG images below the images folder, use "images/**.jpg". - - The matching is case insensitive. - - Match matches by using the files name with path relative to the file system root - with Unix style slashes (/) and no leading slash, e.g. "images/logo.png". - - See https://github.com/gobwas/glob for the full rules set. - - It looks for files in the assets file system. - - See Match for a more complete explanation about the rules used. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Minify: + Aliases: + - minify + Args: + - r + Description: |- + Minify minifies the given Resource using the MediaType to pick the correct + minifier. + Examples: [] + PostCSS: + Aliases: null - Args: - - args - Description: 'PostCSS processes the given Resource with PostCSS.\nDeprecated: Moved to the css namespace in Hugo 0.128.0.' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + PostProcess: + Aliases: null - Args: - - r - Description: PostProcess processes r after the build. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + ToCSS: + Aliases: null - Args: - - args - Description: 'ToCSS converts the given Resource to CSS. You can optional provide an Options object\nas second argument. As an option, you can e.g. specify e.g. the target path (string)\nfor the converted CSS resource.\nDeprecated: Moved to the css namespace in Hugo 0.128.0.' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + safe: + CSS: + Aliases: + - safeCSS + Args: + - s + Description: CSS returns the string s as html/template CSS content. + Examples: + - - '{{ "Bat&Man" | safeCSS | safeCSS }}' + - Bat&Man + HTML: + Aliases: + - safeHTML + Args: + - s + Description: HTML returns the string s as html/template HTML content. + Examples: + - - '{{ "Bat&Man" | safeHTML | safeHTML }}' + - Bat&Man + - - '{{ "Bat&Man" | safeHTML }}' + - Bat&Man + HTMLAttr: + Aliases: + - safeHTMLAttr + Args: + - s + Description: HTMLAttr returns the string s as html/template HTMLAttr content. + Examples: [] + JS: + Aliases: + - safeJS + Args: + - s + Description: JS returns the given string as a html/template JS content. + Examples: + - - '{{ "(1*2)" | safeJS | safeJS }}' + - (1*2) + JSStr: + Aliases: + - safeJSStr + Args: + - s + Description: JSStr returns the given string as a html/template JSStr content. + Examples: [] + URL: + Aliases: + - safeURL + Args: + - s + Description: URL returns the string s as html/template URL content. + Examples: + - - '{{ "http://gohugo.io" | safeURL | safeURL }}' + - http://gohugo.io + site: + AllPages: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Author: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Authors: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + BaseURL: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + BuildDrafts: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + CheckReady: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Config: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Copyright: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Current: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Data: + Aliases: null + Args: null - Description: '' - Examples: null - Dimension: - Aliases: null - Args: null - Description: '' ++ Description: "" + Examples: null + ForEeachIdentityByName: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + GetPage: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Home: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Hugo: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + IsMultiLingual: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Key: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Language: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + LanguageCode: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + LanguagePrefix: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Languages: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + LastChange: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Lastmod: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + MainSections: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Menus: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Pages: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Param: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Params: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + RegularPages: + Aliases: null + Args: null - Description: '' - Examples: null - Role: - Aliases: null - Args: null - Description: '' ++ Description: "" + Examples: null + Sections: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + ServerPort: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Sites: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Social: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Store: + Aliases: null + Args: null - Description: '' - Examples: null - String: - Aliases: null - Args: null - Description: '' ++ Description: "" + Examples: null + Taxonomies: + Aliases: null + Args: null - Description: '' ++ Description: "" + Examples: null + Title: + Aliases: null + Args: null - Description: '' - Examples: null - Version: - Aliases: null - Args: null - Description: '' ++ Description: "" + Examples: null + strings: + Chomp: + Aliases: + - chomp + Args: + - s - Description: Chomp returns a copy of s with all trailing newline characters removed. ++ Description: Chomp returns a copy of s with all trailing newline characters ++ removed. + Examples: + - - '{{ chomp "

Blockhead

\n" | safeHTML }}' + -

Blockhead

+ Contains: + Aliases: null + Args: + - s + - substr + Description: Contains reports whether substr is in s. + Examples: + - - '{{ strings.Contains "abc" "b" }}' - - 'true' ++ - "true" + - - '{{ strings.Contains "abc" "d" }}' - - 'false' ++ - "false" + ContainsAny: + Aliases: null + Args: + - s + - chars - Description: ContainsAny reports whether any Unicode code points in chars are within s. ++ Description: ContainsAny reports whether any Unicode code points in chars ++ are within s. + Examples: + - - '{{ strings.ContainsAny "abc" "bcd" }}' - - 'true' ++ - "true" + - - '{{ strings.ContainsAny "abc" "def" }}' - - 'false' ++ - "false" + ContainsNonSpace: + Aliases: null - Args: - - s - Description: 'ContainsNonSpace reports whether s contains any non-space characters as defined\nby Unicode''s White Space property,\n{"newIn": "0.111.0" }' - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Count: + Aliases: null + Args: + - substr + - s + Description: |- + Count counts the number of non-overlapping instances of substr in s. + If substr is an empty string, Count returns 1 + the number of Unicode code points in s. + Examples: + - - '{{ "aabab" | strings.Count "a" }}' - - '3' ++ - "3" + CountRunes: + Aliases: + - countrunes + Args: + - s + Description: CountRunes returns the number of runes in s, excluding whitespace. + Examples: [] + CountWords: + Aliases: + - countwords + Args: + - s + Description: CountWords returns the approximate word count in s. + Examples: [] + Diff: + Aliases: null - Args: - - oldname - - old - - newname - - new - Description: |- - Diff returns an anchored diff of the two texts old and new in the “unified - diff” format. If old and new are identical, Diff returns an empty string. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + FindRE: + Aliases: + - findRE + Args: + - expr + - content + - limit + Description: |- + FindRE returns a list of strings that match the regular expression. By default all matches + will be included. The number of matches can be limited with an optional third parameter. + Examples: - - - '{{ findRE "[G|g]o" "Hugo is a static side generator written in Go." 1 }}' ++ - - '{{ findRE "[G|g]o" "Hugo is a static side generator written in Go." 1 ++ }}' + - '[go]' + FindRESubmatch: + Aliases: + - findRESubmatch + Args: + - expr + - content + - limit + Description: |- + FindRESubmatch returns a slice of all successive matches of the regular + expression in content. Each element is a slice of strings holding the text + of the leftmost match of the regular expression and the matches, if any, of + its subexpressions. - ++ + By default all matches will be included. The number of matches can be + limited with the optional limit parameter. A return value of nil indicates + no match. + Examples: - - - '{{ findRESubmatch `(.+?)` `
  • Foo
  • Bar
  • ` | print | safeHTML }}' ++ - - '{{ findRESubmatch `(.+?)` `
  • Foo
  • ++
  • Bar
  • ` | print | safeHTML }}' + - '[[Foo #foo Foo] [Bar #bar Bar]]' + FirstUpper: + Aliases: null + Args: + - s + Description: FirstUpper converts s making the first character upper case. + Examples: + - - '{{ "hugo rocks!" | strings.FirstUpper }}' + - Hugo rocks! + HasPrefix: + Aliases: + - hasPrefix + Args: + - s + - prefix + Description: HasPrefix tests whether the input s begins with prefix. + Examples: + - - '{{ hasPrefix "Hugo" "Hu" }}' - - 'true' ++ - "true" + - - '{{ hasPrefix "Hugo" "Fu" }}' - - 'false' ++ - "false" + HasSuffix: + Aliases: + - hasSuffix + Args: + - s + - suffix + Description: HasSuffix tests whether the input s begins with suffix. + Examples: + - - '{{ hasSuffix "Hugo" "go" }}' - - 'true' ++ - "true" + - - '{{ hasSuffix "Hugo" "du" }}' - - 'false' ++ - "false" + Repeat: + Aliases: null + Args: - - 'n' ++ - "n" + - s - Description: Repeat returns a new string consisting of n copies of the string s. ++ Description: Repeat returns a new string consisting of n copies of the string ++ s. + Examples: + - - '{{ "yo" | strings.Repeat 4 }}' + - yoyoyoyo + Replace: + Aliases: + - replace + Args: + - s + - old + - new + - limit + Description: |- + Replace returns a copy of the string s with all occurrences of old replaced + with new. The number of replacements can be limited with an optional fourth + parameter. + Examples: + - - '{{ replace "Batman and Robin" "Robin" "Catwoman" }}' + - Batman and Catwoman + - - '{{ replace "aabbaabb" "a" "z" 2 }}' + - zzbbaabb + ReplaceRE: + Aliases: + - replaceRE + Args: + - pattern + - repl + - s - - 'n' ++ - "n" + Description: |- + ReplaceRE returns a copy of s, replacing all matches of the regular + expression pattern with the replacement text repl. The number of replacements + can be limited with an optional fourth parameter. + Examples: + - - '{{ replaceRE "a+b" "X" "aabbaabbab" }}' + - XbXbX + - - '{{ replaceRE "a+b" "X" "aabbaabbab" 1 }}' + - Xbaabbab + RuneCount: + Aliases: null + Args: + - s + Description: RuneCount returns the number of runes in s. + Examples: [] + SliceString: + Aliases: + - slicestr + Args: + - a + - startEnd + Description: |- + SliceString slices a string by specifying a half-open range with + two indices, start and end. 1 and 4 creates a slice including elements 1 through 3. + The end index can be omitted, it defaults to the string's length. + Examples: + - - '{{ slicestr "BatMan" 0 3 }}' + - Bat + - - '{{ slicestr "BatMan" 3 }}' + - Man + Split: + Aliases: + - split + Args: + - a + - delimiter - Description: Split slices an input string into all substrings separated by delimiter. ++ Description: Split slices an input string into all substrings separated by ++ delimiter. + Examples: [] + Substr: + Aliases: + - substr + Args: + - a + - nums - Description: 'Substr extracts parts of a string, beginning at the character at the specified\nposition, and returns the specified number of characters.\n\nIt normally takes two parameters: start and length.\nIt can also take one parameter: start, i.e. length is omitted, in which case\nthe substring starting from start until the end of the string will be returned.\n\nTo extract characters from the end of the string, use a negative start number.\n\nIn addition, borrowing from the extended behavior described at http://php.net/substr,\nif length is given and is negative, then that many characters will be omitted from\nthe end of string.' ++ Description: |- ++ Substr extracts parts of a string, beginning at the character at the specified ++ position, and returns the specified number of characters. ++ ++ It normally takes two parameters: start and length. ++ It can also take one parameter: start, i.e. length is omitted, in which case ++ the substring starting from start until the end of the string will be returned. ++ ++ To extract characters from the end of the string, use a negative start number. ++ ++ In addition, borrowing from the extended behavior described at http://php.net/substr, ++ if length is given and is negative, then that many characters will be omitted from ++ the end of string. + Examples: + - - '{{ substr "BatMan" 0 -3 }}' + - Bat + - - '{{ substr "BatMan" 3 3 }}' + - Man + Title: + Aliases: + - title + Args: + - s + Description: |- + Title returns a copy of the input s with all Unicode letters that begin words + mapped to their title case. + Examples: + - - '{{ title "Bat man" }}' + - Bat Man + - - '{{ title "somewhere over the rainbow" }}' + - Somewhere Over the Rainbow + ToLower: + Aliases: + - lower + Args: + - s + Description: |- + ToLower returns a copy of the input s with all Unicode letters mapped to their + lower case. + Examples: + - - '{{ lower "BatMan" }}' + - batman + ToUpper: + Aliases: + - upper + Args: + - s + Description: |- + ToUpper returns a copy of the input s with all Unicode letters mapped to their + upper case. + Examples: + - - '{{ upper "BatMan" }}' + - BATMAN + Trim: + Aliases: + - trim + Args: + - s + - cutset + Description: |- + Trim returns converts the strings s removing all leading and trailing characters defined + contained. + Examples: + - - '{{ trim "++Batman--" "+-" }}' + - Batman + TrimLeft: + Aliases: null + Args: + - cutset + - s + Description: |- + TrimLeft returns a slice of the string s with all leading characters + contained in cutset removed. + Examples: + - - '{{ "aabbaa" | strings.TrimLeft "a" }}' + - bbaa + TrimPrefix: + Aliases: null + Args: + - prefix + - s + Description: |- + TrimPrefix returns s without the provided leading prefix string. If s doesn't + start with prefix, s is returned unchanged. + Examples: + - - '{{ "aabbaa" | strings.TrimPrefix "a" }}' + - abbaa + - - '{{ "aabbaa" | strings.TrimPrefix "aa" }}' + - bbaa + TrimRight: + Aliases: null + Args: + - cutset + - s + Description: |- + TrimRight returns a slice of the string s with all trailing characters + contained in cutset removed. + Examples: + - - '{{ "aabbaa" | strings.TrimRight "a" }}' + - aabb + TrimSpace: + Aliases: null - Args: - - s - Description: |- - TrimSpace returns the given string, removing leading and trailing whitespace - as defined by Unicode. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + TrimSuffix: + Aliases: null + Args: + - suffix + - s + Description: |- + TrimSuffix returns s without the provided trailing suffix string. If s + doesn't end with suffix, s is returned unchanged. + Examples: + - - '{{ "aabbaa" | strings.TrimSuffix "a" }}' + - aabba + - - '{{ "aabbaa" | strings.TrimSuffix "aa" }}' + - aabb + Truncate: + Aliases: + - truncate + Args: + - s + - options + Description: Truncate truncates the string in s to the specified length. + Examples: + - - '{{ "this is a very long text" | truncate 10 " ..." }}' + - this is a ... + - - '{{ "With [Markdown](/markdown) inside." | markdownify | truncate 14 }}' + - With Markdown … + templates: + Current: + Aliases: null - Args: - - ctx - Description: Get information about the currently executing template. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Defer: + Aliases: null + Args: + - args + Description: Defer defers the execution of a template block. + Examples: [] + DoDefer: + Aliases: + - doDefer + Args: + - ctx + - id + - optsv + Description: |- + DoDefer defers the execution of a template block. + For internal use only. + Examples: [] + Exists: + Aliases: null + Args: + - name + Description: |- + Exists returns whether the template with the given name exists. + Note that this is the Unix-styled relative path including filename suffix, + e.g. partials/header.html + Examples: - - - '{{ if (templates.Exists "_partials/header.html") }}Yes!{{ end }}' ++ - - '{{ if (templates.Exists "partials/header.html") }}Yes!{{ end }}' + - Yes! - - - '{{ if not (templates.Exists "_partials/doesnotexist.html") }}No!{{ end }}' ++ - - '{{ if not (templates.Exists "partials/doesnotexist.html") }}No!{{ end ++ }}' + - No! + time: + AsTime: + Aliases: null + Args: + - v + - args + Description: |- + AsTime converts the textual representation of the datetime string into + a time.Time interface. + Examples: + - - '{{ (time "2015-01-21").Year }}' - - '2015' ++ - "2015" + Duration: + Aliases: + - duration + Args: + - unit + - number + Description: |- + Duration converts the given number to a time.Duration. + Unit is one of nanosecond/ns, microsecond/us/µs, millisecond/ms, second/s, minute/m or hour/h. + Examples: + - - '{{ mul 60 60 | duration "second" }}' + - 1h0m0s + Format: + Aliases: + - dateFormat + Args: + - layout + - v + Description: |- + Format converts the textual representation of the datetime string in v into + time.Time if needed and formats it with the given layout. + Examples: + - - 'dateFormat: {{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }}' + - 'dateFormat: Wednesday, Jan 21, 2015' + In: + Aliases: null - Args: - - timeZoneName - - t - Description: |- - In returns the time t in the IANA time zone specified by timeZoneName. - If timeZoneName is "" or "UTC", the time is returned in UTC. - If timeZoneName is "Local", the time is returned in the system's local time zone. - Otherwise, timeZoneName must be a valid IANA location name (e.g., "Europe/Oslo"). - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Now: + Aliases: + - now + Args: null + Description: Now returns the current local time or `clock` time + Examples: [] + ParseDuration: + Aliases: null + Args: + - s - Description: 'ParseDuration parses the duration string s.\nA duration string is a possibly signed sequence of\ndecimal numbers, each with optional fraction and a unit suffix,\nsuch as "300ms", "-1.5h" or "2h45m".\nValid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".\nSee https://golang.org/pkg/time/#ParseDuration' ++ Description: |- ++ ParseDuration parses the duration string s. ++ A duration string is a possibly signed sequence of ++ decimal numbers, each with optional fraction and a unit suffix, ++ such as "300ms", "-1.5h" or "2h45m". ++ Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". ++ See https://golang.org/pkg/time/#ParseDuration + Examples: + - - '{{ "1h12m10s" | time.ParseDuration }}' + - 1h12m10s + transform: + CanHighlight: + Aliases: null - Args: - - language - Description: CanHighlight returns whether the given code language is supported by the Chroma highlighter. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Emojify: + Aliases: + - emojify + Args: + - s + Description: |- + Emojify returns a copy of s with all emoji codes replaced with actual emojis. - ++ + See http://www.emoji-cheat-sheet.com/ + Examples: + - - '{{ "I :heart: Hugo" | emojify }}' + - I ❤️ Hugo + HTMLEscape: + Aliases: + - htmlEscape + Args: + - s - Description: HTMLEscape returns a copy of s with reserved HTML characters escaped. ++ Description: HTMLEscape returns a copy of s with reserved HTML characters ++ escaped. + Examples: - - - '{{ htmlEscape "Cathal Garvey & The Sunshine Band " | safeHTML }}' ++ - - '{{ htmlEscape "Cathal Garvey & The Sunshine Band " | ++ safeHTML }}' + - Cathal Garvey & The Sunshine Band <cathal@foo.bar> + - - '{{ htmlEscape "Cathal Garvey & The Sunshine Band " }}' + - Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt; - - - '{{ htmlEscape "Cathal Garvey & The Sunshine Band " | htmlUnescape | safeHTML }}' ++ - - '{{ htmlEscape "Cathal Garvey & The Sunshine Band " | ++ htmlUnescape | safeHTML }}' + - Cathal Garvey & The Sunshine Band - HTMLToMarkdown: - Aliases: null - Args: - - ctx - - args - Description: |- - This was added in Hugo v0.151.0 and should be considered experimental for now. - We need to test this out in the wild for a while before committing to this API, - and there will eventually be more options here. - Examples: [] + HTMLUnescape: + Aliases: + - htmlUnescape + Args: + - s + Description: |- + HTMLUnescape returns a copy of s with HTML escape requences converted to plain + text. + Examples: - - - '{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | safeHTML }}' ++ - - '{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" ++ | safeHTML }}' + - Cathal Garvey & The Sunshine Band - - - '{{ "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | htmlUnescape | htmlUnescape | safeHTML }}' ++ - - '{{ "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" ++ | htmlUnescape | htmlUnescape | safeHTML }}' + - Cathal Garvey & The Sunshine Band - - - '{{ "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | htmlUnescape | htmlUnescape }}' ++ - - '{{ "Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" ++ | htmlUnescape | htmlUnescape }}' + - Cathal Garvey & The Sunshine Band <cathal@foo.bar> - - - '{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | htmlEscape | safeHTML }}' ++ - - '{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" ++ | htmlEscape | safeHTML }}' + - Cathal Garvey & The Sunshine Band <cathal@foo.bar> + Highlight: + Aliases: + - highlight + Args: + - s + - lang + - opts + Description: |- + Highlight returns a copy of s as an HTML string with syntax + highlighting applied. + Examples: [] + HighlightCodeBlock: + Aliases: null - Args: - - ctx - - opts - Description: HighlightCodeBlock highlights a code block on the form received in the codeblock render hooks. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Markdownify: + Aliases: + - markdownify + Args: + - ctx + - s + Description: Markdownify renders s from Markdown to HTML. + Examples: + - - '{{ .Title | markdownify }}' + - BatMan + Plainify: + Aliases: + - plainify + Args: + - s + Description: Plainify returns a copy of s with all HTML tags removed. + Examples: + - - '{{ plainify "Hello world, gophers!" }}' + - Hello world, gophers! + PortableText: + Aliases: null - Args: - - v - Description: |- - PortableText converts the portable text in v to Markdown. - We may add more options in the future. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Remarshal: + Aliases: null + Args: + - format + - data + Description: |- + Remarshal is used in the Hugo documentation to convert configuration + examples from YAML to JSON, TOML (and possibly the other way around). + The is primarily a helper for the Hugo docs site. + It is not a general purpose YAML to TOML converter etc., and may + change without notice if it serves a purpose in the docs. + Format is one of json, yaml or toml. + Examples: - - - '{{ "title = \"Hello World\"" | transform.Remarshal "json" | safeHTML }}' - - '{\n "title": "Hello World"\n}\n' ++ - - '{{ "title = \"Hello World\"" | transform.Remarshal "json" | safeHTML ++ }}' ++ - | ++ { ++ "title": "Hello World" ++ } + ToMath: + Aliases: null - Args: - - ctx - - args - Description: |- - ToMath converts a LaTeX string to math in the given format, default MathML. - This uses KaTeX to render the math, see https://katex.org/. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Unmarshal: + Aliases: + - unmarshal + Args: + - args + Description: |- + Unmarshal unmarshals the data given, which can be either a string, json.RawMessage + or a Resource. Supported formats are JSON, TOML, YAML, and CSV. + You can optionally provide an options map as the first argument. + Examples: + - - '{{ "hello = \"Hello World\"" | transform.Unmarshal }}' + - map[hello:Hello World] - - - '{{ "hello = \"Hello World\"" | resources.FromString "data/greetings.toml" | transform.Unmarshal }}' ++ - - '{{ "hello = \"Hello World\"" | resources.FromString "data/greetings.toml" ++ | transform.Unmarshal }}' + - map[hello:Hello World] + XMLEscape: + Aliases: null + Args: + - s + Description: |- + XMLEscape returns the given string, removing disallowed characters then + escaping the result to its XML equivalent. + Examples: + - - '{{ transform.XMLEscape "

    abc

    " }}' + - '<p>abc</p>' + urls: + AbsLangURL: + Aliases: + - absLangURL + Args: + - s + Description: |- + AbsLangURL the string s and converts it to an absolute URL according + to a page's position in the project directory structure and the current + language. + Examples: [] + AbsURL: + Aliases: + - absURL + Args: + - s + Description: AbsURL takes the string s and converts it to an absolute URL. + Examples: [] + Anchorize: + Aliases: + - anchorize + Args: + - s + Description: |- + Anchorize creates sanitized anchor name version of the string s that is compatible + with how your configured markdown renderer does it. + Examples: + - - '{{ "This is a title" | anchorize }}' + - this-is-a-title + JoinPath: + Aliases: null + Args: + - elements + Description: |- + JoinPath joins the provided elements into a URL string and cleans the result + of any ./ or ../ elements. If the argument list is empty, JoinPath returns + an empty string. + Examples: + - - '{{ urls.JoinPath "https://example.org" "foo" }}' + - https://example.org/foo + - - '{{ urls.JoinPath (slice "a" "b") }}' + - a/b + Parse: + Aliases: null - Args: - - rawurl - Description: |- - Parse parses rawurl into a URL structure. The rawurl may be relative or - absolute. - Examples: [] - PathEscape: - Aliases: null - Args: - - s - Description: |- - PathEscape returns the given string, applying percent-encoding to special - characters and reserved delimiters so it can be safely used as a segment - within a URL path. - Examples: [] - PathUnescape: - Aliases: null - Args: - - s - Description: |- - PathUnescape returns the given string, replacing all percent-encoded - sequences with the corresponding unescaped characters. - Examples: [] ++ Args: null ++ Description: "" ++ Examples: null + Ref: + Aliases: + - ref + Args: + - p + - args - Description: Ref returns the absolute URL path to a given content item from Page p. ++ Description: Ref returns the absolute URL path to a given content item from ++ Page p. + Examples: [] + RelLangURL: + Aliases: + - relLangURL + Args: + - s + Description: |- + RelLangURL takes the string s and prepends the relative path according to a + page's position in the project directory structure and the current language. + Examples: [] + RelRef: + Aliases: + - relref + Args: + - p + - args - Description: RelRef returns the relative URL path to a given content item from Page p. ++ Description: RelRef returns the relative URL path to a given content item ++ from Page p. + Examples: [] + RelURL: + Aliases: + - relURL + Args: + - s + Description: |- + RelURL takes the string s and prepends the relative path according to a + page's position in the project directory structure. + Examples: [] + URLize: + Aliases: + - urlize + Args: + - s + Description: URLize returns the strings s formatted as an URL. + Examples: [] diff --cc docs/data/keywords.yaml index 106929884,000000000..cd021bbdb mode 100644,000000..100644 --- a/docs/data/keywords.yaml +++ b/docs/data/keywords.yaml @@@ -1,12 -1,0 +1,13 @@@ +# 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. + ++- highlight +- menu ++- random +- resource - - highlight diff --cc docs/data/page_filters.yaml index e515f843d,000000000..ec77f4cae mode 100644,000000..100644 --- a/docs/data/page_filters.yaml +++ b/docs/data/page_filters.yaml @@@ -1,95 -1,0 +1,88 @@@ +# Do not delete. Required for layouts/_shortcodes/list-pages-in-section.html. +# +# When calling the list-pages-in-section shortcode, you can specify a page +# filter, and whether the pages in the filter should be included or excluded +# from the list. +# +# For example: +# +# {{% list-pages-in-section path=/functions/images filter=functions_images_no_filters filterType=exclude %}} + +functions_fmt_logging: + - /functions/fmt/errorf + - /functions/fmt/erroridf + - /functions/fmt/warnf + - /functions/fmt/warnidf +functions_images_no_filters: + - /functions/images/filter + - /functions/images/config +methods_site_multilingual: + - /methods/site/ismultilingual + - /methods/site/language + - /methods/site/languageprefix + - /methods/site/languages +methods_site_page_collections: + - /methods/site/allpages + - /methods/site/pages + - /methods/site/regularpages + - /methods/site/sections +methods_page_dates: + - /methods/page/date + - /methods/page/expirydate + - /methods/page/lastmod + - /methods/page/publishdate +methods_page_menu: + - /methods/page/hasmenucurrent + - /methods/page/ismenucurrent +methods_page_multilingual: + - /methods/page/alltranslations + - /methods/page/istranslated + - /methods/page/language + - /methods/page/translationkey + - /methods/page/translations +methods_page_page_collections: + - /methods/page/pages + - /methods/page/regularpages + - /methods/page/regularpagesrecursive + - /methods/page/sections +methods_page_parameters: + - /methods/page/param + - /methods/page/params +methods_page_sections: + - /methods/page/ancestors + - /methods/page/currentsection + - /methods/page/firstsection + - /methods/page/insection + - /methods/page/isancestor + - /methods/page/isdescendant + - /methods/page/parent + - /methods/page/sections + - /methods/page/section +methods_pages_sort: + - /methods/pages/bydate + - /methods/pages/byexpirydate + - /methods/pages/bylanguage + - /methods/pages/bylastmod + - /methods/pages/bylength + - /methods/pages/bylinktitle + - /methods/pages/byparam + - /methods/pages/bypublishdate + - /methods/pages/bytitle + - /methods/pages/byweight + - /methods/pages/reverse +methods_pages_group: + - /methods/pages/groupby + - /methods/pages/groupbydate + - /methods/pages/groupbyexpirydate + - /methods/pages/groupbylastmod + - /methods/pages/groupbyparam + - /methods/pages/groupbyparamdate + - /methods/pages/groupbypublishdate - - /methods/pages/groupbydate - - /methods/pages/groupbydate - - /methods/pages/groupbydate - - /methods/pages/groupbydate - - /methods/pages/groupbydate - - /methods/pages/groupbydate - - /methods/pages/reverse +methods_pages_navigation: + - /methods/pages/next + - /methods/pages/prev +methods_page_navigation: + - /methods/page/next + - /methods/page/nextinsection + - /methods/page/prev + - /methods/page/previnsection diff --cc docs/data/sponsors.toml index 84769a453,000000000..c8eda5883 mode 100644,000000..100644 --- a/docs/data/sponsors.toml +++ b/docs/data/sponsors.toml @@@ -1,14 -1,0 +1,21 @@@ +[[banners]] + name = "Linode" + link = "https://www.linode.com/" + logo = "images/sponsors/linode-logo.svg" + utm_campaign = "hugosponsor" + bgcolor = "#ffffff" + +[[banners]] + name = "GoLand" + title = "The complete IDE crafted for professional Go developers." + no_query_params = true + link = "https://www.jetbrains.com/go/?utm_source=OSS&utm_medium=referral&utm_campaign=hugo" + logo = "images/sponsors/goland.svg" + bgcolor = "#f4f4f4" ++ ++[[banners]] ++ name = "CloudCannon" ++ link = "https://cloudcannon.com/hugo-cms/?utm_campaign=HugoSponsorship&utm_content=gohugo&utm_medium=banner&utm_source=sponsor" ++ logo = "images/sponsors/cloudcannon-cms-logo.svg" ++ no_query_params = true ++ bgcolor = "#ffffff" diff --cc docs/layouts/_markup/render-codeblock.html index 13725ffcd,000000000..0f1d09d1f mode 100644,000000..100644 --- a/docs/layouts/_markup/render-codeblock.html +++ b/docs/layouts/_markup/render-codeblock.html @@@ -1,98 -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 }} + - {{- with .Attributes.copy }} - {{- if in (slice true "true" 1) . }} ++{{- if collections.IsSet .Attributes "copy" }} ++ {{- if in (slice true "true" 1) .Attributes.copy }} + {{- $copy = true }} - {{- else if in (slice false "false" 0) . }} ++ {{- else if in (slice false "false" 0) .Attributes.copy }} + {{- $copy = false }} + {{- end }} +{{- end }} + - {{- with .Attributes.details }} - {{- if in (slice true "true" 1) . }} ++{{- if collections.IsSet .Attributes "details" }} ++ {{- if in (slice true "true" 1) .Attributes.details }} + {{- $details = true }} - {{- else if in (slice false "false" 0) . }} ++ {{- else if in (slice false "false" 0) .Attributes.details }} + {{- $details = false }} + {{- end }} +{{- end }} + - {{- with .Attributes.open }} - {{- if in (slice true "true" 1) . }} ++{{- if collections.IsSet .Attributes "open" }} ++ {{- if in (slice true "true" 1) .Attributes.open }} + {{- $open = "open" }} - {{- else if in (slice false "false" 0) . }} ++ {{- 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 }} + +
    + {{- $fileSelectClass := "select-none" }} + {{- if $copy }} + {{- $fileSelectClass = "select-text" }} + + + + {{- end }} + {{- with $file }} +
    + {{ . }} +
    + {{- end }} + +
    - {{- transform.Highlight (strings.TrimSpace .Inner) $lang .Options }} ++ {{- $content := .Inner }} ++ {{- if $trim }} ++ {{- $content = strings.TrimSpace .Inner }} ++ {{- end }} ++ {{- transform.Highlight $content $lang .Options }} +
    +
    + +{{- if $details }} +
    +{{- end }} diff --cc docs/layouts/_partials/layouts/head/head.html index 550636095,000000000..265d7ccd0 mode 100644,000000..100644 --- a/docs/layouts/_partials/layouts/head/head.html +++ b/docs/layouts/_partials/layouts/head/head.html @@@ -1,39 -1,0 +1,41 @@@ + +{{ hugo.Generator }} + +{{ if hugo.IsProduction }} + +{{ else }} + +{{ end }} + + + {{ with .Title }}{{ . }} |{{ end }} + {{ .Site.Title }} + + ++ ++ ++ + + + + + + + - + +{{ range .AlternativeOutputFormats -}} + +{{ end -}} + + + +{{ partial "opengraph/opengraph.html" . }} +{{ partial "schema.html" . }} +{{ partial "twitter_cards.html" . }} + +{{ if hugo.IsProduction }} + {{ partial "helpers/gtag.html" . }} +{{ end }} diff --cc docs/layouts/_partials/layouts/hooks/body-start.html index 3430bd846,000000000..e69de29bb mode 100644,000000..100644 --- a/docs/layouts/_partials/layouts/hooks/body-start.html +++ b/docs/layouts/_partials/layouts/hooks/body-start.html diff --cc docs/layouts/_partials/layouts/related.html index dac5b8d5b,000000000..9c0146c88 mode 100644,000000..100644 --- a/docs/layouts/_partials/layouts/related.html +++ b/docs/layouts/_partials/layouts/related.html @@@ -1,22 -1,0 +1,21 @@@ +{{- $heading := "See also" }} - {{- $related := site.Pages.Related . }} - {{- $related = $related | complement .CurrentSection.Pages | first 7 }} ++{{- $related := site.Pages.Related . | first 7}} + +{{- with $related }} + {{ $.Store.Set "hasRelated" true }} +

    + {{ $heading }} +

    + +{{- end }} diff --cc docs/layouts/_shortcodes/glossary.html index 7331d5c9f,000000000..ec08cf311 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/glossary.html +++ b/docs/layouts/_shortcodes/glossary.html @@@ -1,54 -1,0 +1,54 @@@ +{{- /* +Renders the glossary of terms. + +When you call this shortcode using the {{% %}} notation, the glossary terms are +Markdown headings (level 6) which means they are members of .Fragments. This +allows the link render hook to verify links to glossary terms. + +Yes, the terms themselves are pages, but we don't want to link to the pages, at +least not right now. Instead, we want to link to the ids rendered by this +shortcode. + +@example {{% glossary %}} +*/ -}} +{{- $path := "/quick-reference/glossary" }} +{{- with site.GetPage $path }} + + {{- /* Build and render alphabetical index. */}} + {{- $m := dict }} + {{- range $p := .Pages.ByTitle }} + {{- $k := substr .Title 0 1 | strings.ToUpper }} + {{- if index $m $k }} + {{- continue }} + {{- end }} + {{- $anchor := path.BaseName .Path | anchorize }} + {{- $m = merge $m (dict $k $anchor) }} + {{- end }} + {{- range $k, $v := $m }} +[{{ $k }}](#{{ $v }}) {{/* Do not indent. */}} + {{- end }} + + {{/* Render glossary terms. */}} + {{- range $p := .Pages.ByTitle }} +{{ .Title }}{{/* Do not indent. */}} +: {{ .RawContent | strings.TrimSpace | safeHTML }}{{/* Do not indent. */}} + {{ with .Params.reference }} + {{- $destination := "" }} + {{- with $u := urls.Parse . }} + {{- if $u.IsAbs }} + {{- $destination = $u.String }} + {{- else }} + {{- with site.GetPage $u.Path }} - {{- $destination = .RelPermalink }} ++ {{- $destination = .Path }} + {{- else }} + {{- errorf "The %q shortcode was unable to find the reference link %s: see %s" $.Name . $p.String }} + {{- end }} + {{- end }} + {{- end }} +: See [details]({{ $destination }}).{{/* Do not indent. */}} + {{- end }} + {{ end }} + +{{- else }} + {{- errorf "The %q shortcode was unable to get %s: see %s" .Name $path .Position}} +{{- end }} diff --cc docs/layouts/_shortcodes/list-pages-in-section.html index f6dfe7275,000000000..df06d53ca mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/list-pages-in-section.html +++ b/docs/layouts/_shortcodes/list-pages-in-section.html @@@ -1,69 -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 >}} ++@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 . }} + {{ 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 }} - [{{ $linkTitle }}]({{ $page.RelPermalink }}){{/* Do not indent. */}} ++{{/* 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/quick-reference.html index 0ac544036,000000000..d4c4d7bc8 mode 100644,000000..100644 --- a/docs/layouts/_shortcodes/quick-reference.html +++ b/docs/layouts/_shortcodes/quick-reference.html @@@ -1,30 -1,0 +1,31 @@@ +{{- /* +Renders the child sections of the given top-level section, listing each child's +immediate descendants. + +@param {string} section The top-level section to render. + +@example {{% quick-reference section="/functions" %}} +*/ -}} +{{ $section := "" }} +{{ with .Get "section" }} + {{ $section = . }} +{{ else }} + {{ errorf "The %q shortcode requires a 'section' parameter. See %s" .Name .Position }} +{{ end }} + +{{ with site.GetPage $section }} + {{ range .Sections }} +## {{ .LinkTitle }}{{/* Do not indent. */}} +{{ .Description }}{{/* Do not indent. */}} + {{ .Content }} + {{ with .Pages }} + {{ range . }} - [{{ .LinkTitle }}]({{ .RelPermalink }}){{/* Do not indent. */}} ++{{/* Use page Path as the link destination for render hook to resolve correctly. */}} ++[{{ .LinkTitle }}]({{ .Path }}){{/* Do not indent. */}} +: {{ .Description }}{{/* Do not indent. */}} + {{ end }} + {{ end }} + {{ end }} +{{ else }} + {{ errorf "The %q shortcodes was unable to find the %q section. See %s" .Name $section .Position }} +{{ end }} diff --cc docs/layouts/baseof.html index c5df69a92,000000000..ad4dd90a9 mode 100644,000000..100644 --- a/docs/layouts/baseof.html +++ b/docs/layouts/baseof.html @@@ -1,74 -1,0 +1,77 @@@ + + + + + + {{ .Title }} + + + + {{ partial "layouts/head/head-js.html" . }} + {{ with (templates.Defer (dict "key" "global")) }} + {{ $t := debug.Timer "tailwindcss" }} + {{ with resources.Get "css/styles.css" }} + {{ $opts := dict "minify" (not hugo.IsDevelopment) }} + {{ with . | css.TailwindCSS $opts }} + {{ partial "helpers/linkcss.html" (dict "r" .) }} + {{ end }} + {{ end }} + {{ $t.Stop }} + {{ end }} + {{ $noop := .WordCount }} + {{ if .Page.Store.Get "hasMath" }} + ++ rel="stylesheet" ++ href="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.css" ++ integrity="sha384-WcoG4HRXMzYzfCgiyfrySxx90XSl2rxY5mnVY5TwtWE6KLrArNKn0T/mOgNL0Mmi" ++ crossorigin="anonymous" ++ > + {{ end }} + {{ partial "layouts/head/head.html" . }} + + + {{ $bodyClass := printf "flex flex-col min-h-full bg-white dark:bg-blue-950 kind-%s" .Kind }} + {{ if .Params.searchable }} + {{ $bodyClass = printf "%s searchable" $bodyClass }} + {{ end }} + + + {{ partial "layouts/hooks/body-start.html" . }} + {{/* Layout. */}} + {{ block "header" . }} + {{ partial "layouts/header/header.html" . }} + {{ end }} + {{ block "subheader" . }} + {{ end }} + {{ block "hero" . }} + {{ end }} +
    +
    + {{ partial "layouts/hooks/body-main-start.html" . }} + {{ block "main" . }}{{ end }} +
    + {{ block "rightsidebar" . }} + + {{ end }} +
    + {{/* Common icons. */}} + {{ partial "layouts/icons.html" . }} + {{/* Common templates. */}} + {{ partial "layouts/templates.html" . }} + {{/* Footer. */}} + {{ block "footer" . }} + {{ partial "layouts/footer.html" . }} + {{ end }} + {{ partial "layouts/hooks/body-end.html" . }} + + diff --cc docs/netlify.toml index 6d028743d,000000000..2df6ab894 mode 100644,000000..100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@@ -1,55 -1,0 +1,55 @@@ +[build] + publish = "public" + command = "hugo --gc --minify" + + [build.environment] - HUGO_VERSION = "0.148.2" ++ HUGO_VERSION = "0.152.2" + +[context.production.environment] + HUGO_ENV = "production" + HUGO_ENABLEGITINFO = "true" + +[context.split1] + command = "hugo --gc --minify --enableGitInfo" + + [context.split1.environment] + HUGO_ENV = "production" + +[context.deploy-preview] + command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL --enableGitInfo" + +[context.branch-deploy] + command = "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" diff --cc docs/package.json index 24ffc7ff5,000000000..1fda5ee85 mode 100644,000000..100644 --- a/docs/package.json +++ b/docs/package.json @@@ -1,25 -1,0 +1,25 @@@ +{ + "name": "hugoDocs", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "", + "devDependencies": { - "@awmottaz/prettier-plugin-void-html": "~1.8.0", - "@tailwindcss/cli": "~4.1.0", - "@tailwindcss/typography": "~0.5.16", - "prettier": "~3.5.3", ++ "@awmottaz/prettier-plugin-void-html": "~2.0.0", ++ "@tailwindcss/cli": "~4.1.18", ++ "@tailwindcss/typography": "~0.5.19", ++ "prettier": "~3.7.4", + "prettier-plugin-go-template": "~0.0.15", - "tailwindcss": "~4.1.0" ++ "tailwindcss": "~4.1.18" + }, + "dependencies": { - "@alpinejs/focus": "~3.14.9", - "@alpinejs/persist": "~3.14.9", - "@hotwired/turbo": "~8.0.13", - "alpinejs": "~3.14.9" ++ "@alpinejs/focus": "~3.15.3", ++ "@alpinejs/persist": "~3.15.3", ++ "@hotwired/turbo": "~8.0.20", ++ "alpinejs": "~3.15.3" + } +}