From: Bjørn Erik Pedersen Date: Fri, 26 Jan 2024 07:22:42 +0000 (+0100) Subject: Merge commit '7125ad401ad043e46262afc7eca8dceb6d54bb9e' X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=3758456b3;p=brevno-suite%2Fhugo Merge commit '7125ad401ad043e46262afc7eca8dceb6d54bb9e' --- 3758456b31695dd59ebe5eb35b19c1b054287a48 diff --cc docs/.cspell.json index ae469d646,000000000..1c386ee29 mode 100644,000000..100644 --- a/docs/.cspell.json +++ b/docs/.cspell.json @@@ -1,133 -1,0 +1,136 @@@ +{ + "version": "0.2", + "allowCompoundWords": true, + "files": [ + "**/*.md" + ], + "flagWords": [ + "alot", + "hte", ++ "langauge", + "reccommend", - "seperate" ++ "seperate", ++ "teh" + ], + "ignorePaths": [ + "**/emojis.md", + "**/commands/*", + "**/showcase/*", + "**/tools/*" + ], + "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 single quotes", + "'.+'", + "# 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": [ + "antialiasing", + "codeowners", + "composability", + "configurators", + "defang", + "deindent", + "downscale", + "downscaled", + "downscaling", + "exif", + "geolocalized", + "grayscale", + "marshal", + "marshaling", + "multihost", + "performantly", + "preconfigured", + "prerendering", + "redirection", + "redirections", + "shortcode", + "shortcodes", + "subexpression", + "subexpressions", + "suppressable", + "templating", + "transpile", + "transpiles", + "unmarshal", ++ "unmarshals", + "unmarshaling", + "# ----------------------------------------------------------------------", + "# cspell: ignore foreign language words", + "# ----------------------------------------------------------------------", + "bezpieczeństwo", + "dokumentation", + "libros", + "miesiąc", + "miesiąc", + "miesięcy", + "miesięcy", + "misérables", + "projekt", + "régime", + "# ----------------------------------------------------------------------", + "# cspell: ignore proper nouns", + "# ----------------------------------------------------------------------", + "Eliott", + "Gregor", + "Jaco", + "Noll", + "Pastorius", + "Samsa", + "# ----------------------------------------------------------------------", + "# cspell: ignore operating systems and software packages", + "# ----------------------------------------------------------------------", + "asciidoctor", + "brotli", + "corejs", + "disqus", + "doas", + "eopkg", + "gitee", + "goldmark", + "kubuntu", + "lubuntu", + "nosql", + "pandoc", + "pkgin", + "rclone", + "xubuntu", + "# ----------------------------------------------------------------------", + "# cspell: ignore miscellaneous", + "# ----------------------------------------------------------------------", + "dring", + "getenv", + "gohugo", + "inor", + "jdoe", + "milli", + "rgba", + "rsmith", + "stringifier", + "struct", + "tdewolff", + "tjones", + "toclevels", + "vals", + "xfeff", + "zgotmplz" + ] +} diff --cc docs/.github/workflows/spellcheck.yml index a650f153c,000000000..86f8f53a5 mode 100644,000000..100644 --- a/docs/.github/workflows/spellcheck.yml +++ b/docs/.github/workflows/spellcheck.yml @@@ -1,22 -1,0 +1,22 @@@ +name: "Check spelling" +on: + push: + pull_request: + branches-ignore: + - "dependabot/**" + +permissions: + contents: read + +jobs: + spellcheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 - - uses: streetsidesoftware/cspell-action@v4 ++ - uses: streetsidesoftware/cspell-action@v5 + with: + check_dot_files: false + files: content/**/*.md + incremental_files_only: true + inline: warning + strict: false diff --cc docs/.markdownlint.yaml index 58f84dc67,000000000..d9c2c5a67 mode 100644,000000..100644 --- a/docs/.markdownlint.yaml +++ b/docs/.markdownlint.yaml @@@ -1,24 -1,0 +1,25 @@@ +# https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md + ++MD001: false +MD002: false +MD003: false +MD004: false +MD007: false +MD012: + maximum: 2 +MD013: false +MD014: false +MD022: false +MD024: false +MD031: false +MD032: false +MD033: false +MD034: false +MD036: false +MD037: false +MD038: false +MD041: false +MD046: false +MD049: false +MD050: false +MD053: false diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/menutoggle.js index d0e645385,000000000..40bda0ce9 mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/menutoggle.js +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/menutoggle.js @@@ -1,31 -1,0 +1,31 @@@ - // Grab any element that has the 'js-toggle' class and add an event listner for the toggleClass function ++// Grab any element that has the 'js-toggle' class and add an event listener for the toggleClass function +var toggleBtns = document.getElementsByClassName('js-toggle') + for (var i = 0; i < toggleBtns.length; i++) { + toggleBtns[i].addEventListener('click', toggleClass, false) + } + +function toggleClass() { + // Define the data target via the dataset "target" (e.g. data-target=".docsmenu") + var content = this.dataset.target.split(' ') + // Find any menu items that are open + var mobileCurrentlyOpen = document.querySelector('.mobilemenu:not(.dn)') + var desktopCurrentlyOpen = document.querySelector('.desktopmenu:not(.dn)') + var desktopActive = document.querySelector('.desktopmenu:not(.dn)') + + // Loop through the targets' divs + for (var i = 0; i < content.length; i++) { + var matches = document.querySelectorAll(content[i]); + //for each, if the div has the 'dn' class (which is "display:none;"), remove it, otherwise, add that class + [].forEach.call(matches, function(dom) { + dom.classList.contains('dn') ? + dom.classList.remove('dn') : + dom.classList.add('dn'); + return false; + }); + // close the currently open menu items + if (mobileCurrentlyOpen) mobileCurrentlyOpen.classList.add('dn') + if (desktopCurrentlyOpen) desktopCurrentlyOpen.classList.add('dn') + if (desktopActive) desktopActive.classList.remove('db') + + } + } diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/_default/_markup/render-link.html index 7b3d58c2d,000000000..5583d53d7 mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/_default/_markup/render-link.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/_default/_markup/render-link.html @@@ -1,250 -1,0 +1,250 @@@ +{{- /* Last modified: 2023-09-04T09:23:04-07:00 */}} + +{{- /* +Copyright 2023 Veriphor LLC + +Licensed under the Apache License, Version 2.0 (the "License"); you may not +use this file except in compliance with the License. You may obtain a copy of +the License at + +https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations under +the License. +*/}} + +{{- /* +This render hook resolves internal destinations by looking for a matching: + + 1. Content page + 2. Page resource (a file in the current page bundle) + 3. Section resource (a file in the current section) + 4. Global resource (a file in the assets directory) + +It skips the section resource lookup if the current page is a leaf bundle. + +External destinations are not modified. + +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: + + [[module.mounts]] + source = 'assets' + target = 'assets' + + [[module.mounts]] + source = 'static' + target = 'assets' + +By default, if this render hook is unable to resolve a destination, including a +fragment if present, it passes the destination through without modification. To +emit a warning or error, set the error level in your site configuration: + + [params.render_hooks.link] + errorLevel = 'warning' # ignore (default), warning, or error (fails the build) + +When you set the error level to warning, and you are in a development +environment, you can visually highlight broken internal links: + + [params.render_hooks.link] + errorLevel = 'warning' # ignore (default), warning, or error (fails the build) + highlightBroken = true # true or false (default) + +This will add a "broken" class to anchor elements with invalid src attributes. +Add a rule to your CSS targeting the broken links: + + a.broken { + background: #ff0; + border: 2px solid #f00; + padding: 0.1em 0.2em; + } + +This render hook may be unable to resolve destinations created with the ref and +relref shortcodes. Unless you set the error level to ignore you should not use +either of these shortcodes in conjunction with this render hook. + +@context {string} Destination The link destination. +@context {page} Page A reference to the page containing the link. +@context {string} PlainText The link description as plain text. +@context {string} Text The link description. +@context {string} Title The link title. + +@returns {template.html} +*/}} + +{{- /* Initialize. */}} +{{- $renderHookName := "link" }} + +{{- /* Verify minimum required version. */}} +{{- $minHugoVersion := "0.120.0" }} +{{- if lt hugo.Version $minHugoVersion }} + {{- errorf "The %q render hook requires Hugo v%s or later." $renderHookName $minHugoVersion }} +{{- end }} + +{{- /* Error level when unable to resolve destination: ignore, warning, or error. */}} +{{- $errorLevel := or site.Params.render_hooks.link.errorLevel "ignore" | lower }} + +{{- /* If true, adds "broken" class to broken links. Applicable in development environment when errorLevel is warning. */}} +{{- $highlightBrokenLinks := or site.Params.render_hooks.link.highlightBroken false }} + +{{- /* Validate error level. */}} +{{- if not (in (slice "ignore" "warning" "error") $errorLevel) }} + {{- errorf "The %q render hook is misconfigured. The errorLevel %q is invalid. Please check your site configuration." $renderHookName $errorLevel }} +{{- end }} + +{{- /* Determine content path for warning and error messages. */}} +{{- $contentPath := "" }} +{{- with .Page.File }} + {{- $contentPath = .Path }} +{{- else }} + {{- $contentPath = .Path }} +{{- end }} + +{{- /* Parse destination. */}} +{{- $u := urls.Parse .Destination }} + +{{- /* Set common message. */}} +{{- $msg := printf "The %q render hook was unable to resolve the destination %q in %s" $renderHookName $u.String $contentPath }} + +{{- /* Set attributes for anchor element. */}} +{{- $attrs := dict "href" $u.String }} +{{- if $u.IsAbs }} + {{- /* Destination is a remote resource. */}} + {{- $attrs = merge $attrs (dict "rel" "external") }} +{{- else }} + {{- with $u.Path }} + {{- with $p := or ($.Page.GetPage .) ($.Page.GetPage (strings.TrimRight "/" .)) }} + {{- /* Destination is a page. */}} + {{- $href := .RelPermalink }} + {{- with $u.RawQuery }} + {{- $href = printf "%s?%s" $href . }} + {{- end }} + {{- with $u.Fragment }} + {{- $ctx := dict + "contentPath" $contentPath + "errorLevel" $errorLevel + "page" $p + "parsedURL" $u + "renderHookName" $renderHookName + }} + {{- partial "inline/h-rh-l/validate-fragment.html" $ctx }} + {{- $href = printf "%s#%s" $href . }} + {{- end }} + {{- $attrs = dict "href" $href }} + {{- else }} + {{- with $.Page.Resources.Get $u.Path }} + {{- /* Destination is a page resource; drop query and fragment. */}} + {{- $attrs = dict "href" .RelPermalink }} + {{- else }} + {{- with (and (ne $.Page.BundleType "leaf") ($.Page.CurrentSection.Resources.Get $u.Path)) }} + {{- /* Destination is a section resource, and current page is not a leaf bundle. */}} + {{- $attrs = dict "href" .RelPermalink }} + {{- else }} + {{- with resources.Get $u.Path }} + {{- /* Destination is a global resource; drop query and fragment. */}} + {{- $attrs = dict "href" .RelPermalink }} + {{- else }} + {{- if eq $errorLevel "warning" }} + {{- warnf $msg }} + {{- if and $highlightBrokenLinks hugo.IsDevelopment }} + {{- $attrs = merge $attrs (dict "class" "broken") }} + {{- end }} + {{- else if eq $errorLevel "error" }} + {{- errorf $msg }} + {{- end }} + {{- end }} + {{- end }} + {{- end }} + {{- end }} + {{- else }} + {{- with $u.Fragment }} + {{- /* Destination is on the same page; prepend relative permalink. */}} + {{- $ctx := dict + "contentPath" $contentPath + "errorLevel" $errorLevel + "page" $.Page + "parsedURL" $u + "renderHookName" $renderHookName + }} + {{- partial "inline/h-rh-l/validate-fragment.html" $ctx }} + {{- $attrs = dict "href" (printf "%s#%s" $.Page.RelPermalink .) }} + {{- else }} + {{- if eq $errorLevel "warning" }} + {{- warnf $msg }} + {{- if and $highlightBrokenLinks hugo.IsDevelopment }} + {{- $attrs = merge $attrs (dict "class" "broken") }} + {{- end }} + {{- else if eq $errorLevel "error" }} + {{- errorf $msg }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} +{{- with .Title }} + {{- $attrs = merge $attrs (dict "title" .) }} +{{- end -}} + +{{- /* Render anchor element. */ -}} +{{ .Text | safeHTML }} + +{{- define "partials/inline/h-rh-l/validate-fragment.html" }} + {{- /* + Validates the fragment portion of a link destination. + + @context {string} contentPath The page containing the link. - @context {srting} errorLevel The error level when unable to resolve destination; ignore (default), warning, or error. ++ @context {string} errorLevel The error level when unable to resolve destination; ignore (default), warning, or error. + @context {page} page The page corresponding to the link destination + @context {struct} parsedURL The link destination parsed by urls.Parse. + @context {string} renderHookName The name of the render hook. + */}} + + {{- /* Initialize. */}} + {{- $contentPath := .contentPath }} + {{- $errorLevel := .errorLevel }} + {{- $p := .page }} + {{- $u := .parsedURL }} + {{- $renderHookName := .renderHookName }} + + {{- /* Validate. */}} + {{- with $u.Fragment }} + {{- if $p.Fragments.Identifiers.Contains . }} + {{- if gt ($p.Fragments.Identifiers.Count .) 1 }} + {{- $msg := printf "The %q render hook detected duplicate heading IDs %q in %s" $renderHookName . $contentPath }} + {{- if eq $errorLevel "warning" }} + {{- warnf $msg }} + {{- else if eq $errorLevel "error" }} + {{- errorf $msg }} + {{- end }} + {{- end }} + {{- else }} + {{- /* Determine target path for warning and error message. */}} + {{- $targetPath := "" }} + {{- with $p.File }} + {{- $targetPath = .Path }} + {{- else }} + {{- $targetPath = .Path }} + {{- end }} + {{- /* Set common message. */}} + {{- $msg := printf "The %q render hook was unable to find heading ID %q in %s. See %s" $renderHookName . $targetPath $contentPath }} + {{- if eq $targetPath $contentPath }} + {{- $msg = printf "The %q render hook was unable to find heading ID %q in %s" $renderHookName . $targetPath }} + {{- end }} + {{- /* Throw warning or error. */}} + {{- if eq $errorLevel "warning" }} + {{- warnf $msg }} + {{- else if eq $errorLevel "error" }} + {{- errorf $msg }} + {{- end }} + {{- end }} + {{- end }} + +{{- end -}} diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/partials/social-follow.html index ce16953c8,000000000..7451c15d6 mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/partials/social-follow.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/partials/social-follow.html @@@ -1,9 -1,0 +1,21 @@@ - {{/* - Disable Twitter for now as we lost access to the account. - with site.Params.social.twitter }} - - {{ partial "svg/twitter.svg" (dict "size" "32px") }} - - {{ end */}} - gohugoio - Star ++ ++ {{ partial "svg/twitter.svg" (dict "size" "32px") }} ++ ++gohugoio ++Star diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/deprecated-in.html index cab85541d,000000000..7219d7f54 mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/deprecated-in.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/deprecated-in.html @@@ -1,14 -1,0 +1,14 @@@ +{{ $_hugo_config := `{ "version": 1 }` }} + +{{ with .Get 0 }} + {{ $version := printf "v%v" (strings.TrimLeft "vV" .) }} + {{ $href := printf "https://github.com/gohugoio/hugo/releases/tag/%s" $version }} + +{{ else }} + {{ errorf "The %q shortcode requires a single positional parameter indicating version. See %s" .Name .Position }} +{{ end }} diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/img.html index ea5b6de1d,000000000..50d4da9ed mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/img.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/img.html @@@ -1,374 -1,0 +1,379 @@@ +{{- /* +Renders the given image using the given filter, if any. + +@param {string} src The path to the image which must be a remote, page, or global resource. +@param {string} [filter] The filter to apply to the image (case-insensitive). +@param {string} [filterArgs] A comma-delimited list of arguments to pass to the filter. +@param {bool} [example=false] If true, renders a before/after example. +@param {int} [exampleWidth=384] Image width, in pixels, when rendering a before/after example. + +@returns {template.HTML} + +@examples + + {{< img src="zion-national-park.jpg" >}} + + {{< img src="zion-national-park.jpg" alt="Zion National Park" >}} + + {{< img + src="zion-national-park.jpg" + alt="Zion National Park" + filter="grayscale" + >}} + + {{< img + src="zion-national-park.jpg" + alt="Zion National Park" + filter="process" + filterArgs="resize 400x webp" + >}} + + {{< img + src="zion-national-park.jpg" + alt="Zion National Park" + filter="colorize" + filterArgs="180,50,20" + >}} + + {{< img + src="zion-national-park.jpg" + alt="Zion National Park" + filter="grayscale" + example=true + >}} + + {{< img + src="zion-national-park.jpg" + alt="Zion National Park" + filter="grayscale" + example=true + exampleWidth=400 + >}} + + When using the text filter, provide the arguments in this order: + + 0. The text + 1. The horizontal offset, in pixels, relative to the left of the image (default 20) + 2. The vertical offset, in pixels, relative to the top of the image (default 20) + 3. The font size in pixels (default 64) + 4. The line height (default 1.2) + 5. The font color (default #ffffff) + + {{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Text" + filterArgs="Zion National Park,25,250,56" + example=true + >}} + + When using the padding filter, provide all arguments in this order: + + 0. Padding top + 1. Padding right + 2. Padding bottom + 3. Padding right + 4. Canvas color + + {{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Padding" + filterArgs="20,50,20,50,#0705" + example=true + >}} + +*/}} + +{{- /* Initialize. */}} +{{- $alt := "" }} +{{- $src := "" }} +{{- $filter := "" }} +{{- $filterArgs := slice }} +{{- $example := false }} +{{- $exampleWidth := 384 }} + +{{- /* Default values to use with the text filter. */}} +{{ $textFilterOpts := dict + "xOffset" 20 + "yOffset" 20 + "fontSize" 64 + "lineHeight" 1.2 + "fontColor" "#ffffff" - "fontPath" "https://github.com/google/fonts/raw/main/apache/roboto/static/Roboto-Regular.ttf" ++ "fontPath" "https://github.com/google/fonts/raw/main/ofl/lato/Lato-Regular.ttf" +}} + +{{- /* Get and validate parameters. */}} +{{- with .Get "alt" }} + {{- $alt = .}} +{{- end }} + +{{- with .Get "src" }} + {{- $src = . }} +{{- else }} + {{- errorf "The %q shortcode requires a file parameter. See %s" .Name .Position }} +{{- end }} + +{{- with .Get "filter" }} + {{- $filter = . | lower }} +{{- end }} + +{{- $validFilters := slice - "brightness" "colorbalance" "colorize" "contrast" "gamma" "gaussianblur" - "grayscale" "hue" "invert" "none" "opacity" "overlay" "padding" "pixelate" - "process" "saturation" "sepia" "sigmoid" "text" "unsharpmask" ++ "autoorient" "brightness" "colorbalance" "colorize" "contrast" "gamma" ++ "gaussianblur" "grayscale" "hue" "invert" "none" "opacity" "overlay" ++ "padding" "pixelate" "process" "saturation" "sepia" "sigmoid" "text" ++ "unsharpmask" +}} + +{{- with $filter }} + {{- if not (in $validFilters .) }} + {{- errorf "The filter passed to the %q shortcode is invalid. The filter must be one of %s. See %s" $.Name (delimit $validFilters ", " ", or ") $.Position }} + {{- end }} +{{- end }} + +{{- with .Get "filterArgs" }} + {{- $filterArgs = split . "," }} + {{- $filterArgs = apply $filterArgs "trim" "." " " }} +{{- end }} + +{{- if in (slice "false" false 0) (.Get "example") }} + {{- $example = false }} +{{- else if in (slice "true" true 1) (.Get "example")}} + {{- $example = true }} +{{- end }} + +{{- with .Get "exampleWidth" }} + {{- $exampleWidth = . | int }} +{{- end }} + +{{- /* Get image. */}} +{{- $ctx := dict "page" .Page "src" $src "name" .Name "position" .Position }} +{{- $i := partial "inline/get-resource.html" $ctx }} + +{{- /* Resize if rendering before/after examples. */}} +{{- if $example }} + {{- $i = $i.Resize (printf "%dx" $exampleWidth) }} +{{- end }} + +{{- /* Create filter. */}} +{{- $f := "" }} +{{- $ctx := dict "filter" $filter "args" $filterArgs "name" .Name "position" .Position }} - {{- if eq $filter "brightness" }} ++{{- if eq $filter "autoorient" }} ++ {{- $ctx = merge $ctx (dict "argsRequired" 0) }} ++ {{- template "validate-arg-count" $ctx }} ++ {{- $f = images.AutoOrient }} ++{{- else if eq $filter "brightness" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "percentage" "argValue" (index $filterArgs 0) "min" -100 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Brightness (index $filterArgs 0) }} +{{- else if eq $filter "colorbalance" }} + {{- $ctx = merge $ctx (dict "argsRequired" 3) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "percentage red" "argValue" (index $filterArgs 0) "min" -100 "max" 500) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "percentage green" "argValue" (index $filterArgs 1) "min" -100 "max" 500) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "percentage blue" "argValue" (index $filterArgs 2) "min" -100 "max" 500) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.ColorBalance (index $filterArgs 0) (index $filterArgs 1) (index $filterArgs 2) }} +{{- else if eq $filter "colorize" }} + {{- $ctx = merge $ctx (dict "argsRequired" 3) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "hue" "argValue" (index $filterArgs 0) "min" 0 "max" 360) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "saturation" "argValue" (index $filterArgs 1) "min" 0 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "percentage" "argValue" (index $filterArgs 2) "min" 0 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Colorize (index $filterArgs 0) (index $filterArgs 1) (index $filterArgs 2) }} +{{- else if eq $filter "contrast" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "percentage" "argValue" (index $filterArgs 0) "min" -100 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Contrast (index $filterArgs 0) }} +{{- else if eq $filter "gamma" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "gamma" "argValue" (index $filterArgs 0) "min" 0 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Gamma (index $filterArgs 0) }} +{{- else if eq $filter "gaussianblur" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "sigma" "argValue" (index $filterArgs 0) "min" 0 "max" 1000) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.GaussianBlur (index $filterArgs 0) }} +{{- else if eq $filter "grayscale" }} + {{- $ctx = merge $ctx (dict "argsRequired" 0) }} + {{- template "validate-arg-count" $ctx }} + {{- $f = images.Grayscale }} +{{- else if eq $filter "hue" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "shift" "argValue" (index $filterArgs 0) "min" -180 "max" 180) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Hue (index $filterArgs 0) }} +{{- else if eq $filter "invert" }} + {{- $ctx = merge $ctx (dict "argsRequired" 0) }} + {{- template "validate-arg-count" $ctx }} + {{- $f = images.Invert }} +{{- else if eq $filter "opacity" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "opacity" "argValue" (index $filterArgs 0) "min" 0 "max" 1) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Opacity (index $filterArgs 0) }} +{{- else if eq $filter "overlay" }} + {{- $ctx = merge $ctx (dict "argsRequired" 3) }} + {{- template "validate-arg-count" $ctx }} + {{- $ctx := dict "src" (index $filterArgs 0) "name" .Name "position" .Position }} + {{- $overlayImg := partial "inline/get-resource.html" $ctx }} + {{- $f = images.Overlay $overlayImg (index $filterArgs 1 | float ) (index $filterArgs 2 | float) }} +{{- else if eq $filter "padding" }} + {{- $ctx = merge $ctx (dict "argsRequired" 5) }} + {{- template "validate-arg-count" $ctx }} + {{- $f = images.Padding + (index $filterArgs 0 | int) + (index $filterArgs 1 | int) + (index $filterArgs 2 | int) + (index $filterArgs 3 | int) + (index $filterArgs 4) + }} +{{- else if eq $filter "pixelate" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "size" "argValue" (index $filterArgs 0) "min" 0 "max" 1000) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Pixelate (index $filterArgs 0) }} +{{- else if eq $filter "process" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $f = images.Process (index $filterArgs 0) }} +{{- else if eq $filter "saturation" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "percentage" "argValue" (index $filterArgs 0) "min" -100 "max" 500) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Saturation (index $filterArgs 0) }} +{{- else if eq $filter "sepia" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "percentage" "argValue" (index $filterArgs 0) "min" 0 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Sepia (index $filterArgs 0) }} +{{- else if eq $filter "sigmoid" }} + {{- $ctx = merge $ctx (dict "argsRequired" 2) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "midpoint" "argValue" (index $filterArgs 0) "min" 0 "max" 1) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "factor" "argValue" (index $filterArgs 1) "min" -10 "max" 10) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.Sigmoid (index $filterArgs 0) (index $filterArgs 1) }} +{{- else if eq $filter "text" }} + {{- $ctx = merge $ctx (dict "argsRequired" 1) }} + {{- template "validate-arg-count" $ctx }} + {{- $ctx := dict "src" $textFilterOpts.fontPath "name" .Name "position" .Position }} + {{- $font := or (partial "inline/get-resource.html" $ctx) }} + {{- $fontSize := or (index $filterArgs 3 | int) $textFilterOpts.fontSize }} + {{- $lineHeight := math.Max (or (index $filterArgs 4 | float) $textFilterOpts.lineHeight) 1 }} + {{- $opts := dict + "x" (or (index $filterArgs 1 | int) $textFilterOpts.xOffset) + "y" (or (index $filterArgs 2 | int) $textFilterOpts.yOffset) + "size" $fontSize + "linespacing" (mul (sub $lineHeight 1) $fontSize) + "color" (or (index $filterArgs 5) $textFilterOpts.fontColor) + "font" $font + }} + {{- $f = images.Text (index $filterArgs 0) $opts }} +{{- else if eq $filter "unsharpmask" }} + {{- $ctx = merge $ctx (dict "argsRequired" 3) }} + {{- template "validate-arg-count" $ctx }} + {{- $filterArgs = apply $filterArgs "float" "." }} + {{- $ctx = merge $ctx (dict "argName" "sigma" "argValue" (index $filterArgs 0) "min" 0 "max" 500) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "amount" "argValue" (index $filterArgs 1) "min" 0 "max" 100) }} + {{- template "validate-arg-value" $ctx }} + {{- $ctx = merge $ctx (dict "argName" "threshold" "argValue" (index $filterArgs 2) "min" 0 "max" 1) }} + {{- template "validate-arg-value" $ctx }} + {{- $f = images.UnsharpMask (index $filterArgs 0) (index $filterArgs 1) (index $filterArgs 2) }} +{{- end }} + +{{- /* Apply filter. */}} +{{- $fi := $i }} +{{- with $f }} + {{- $fi = $i.Filter . }} +{{- end }} + +{{- /* Render. */}} +{{- if $example }} +

Original

+ {{ $alt }} +

Processed

+ {{ $alt }} +{{- else -}} + {{ $alt }} +{{- end }} + +{{- define "validate-arg-count" }} + {{- $msg := "When using the %q filter, the %q shortcode requires an args parameter with %d %s. See %s" }} + {{- if lt (len .args) .argsRequired }} + {{- $text := "values" }} + {{- if eq 1 .argsRequired }} + {{- $text = "value" }} + {{- end }} + {{- errorf $msg .filter .name .argsRequired $text .position }} + {{- end }} +{{- end }} + +{{- define "validate-arg-value" }} + {{- $msg := "The %q argument passed to the %q shortcode is invalid. Expected a value in the range [%v,%v], but received %v. See %s" }} + {{- if or (lt .argValue .min) (gt .argValue .max) }} + {{- errorf $msg .argName .name .min .max .argValue .position }} + {{- end }} +{{- end }} + +{{- define "partials/inline/get-resource.html" }} + {{- $r := "" }} + {{- $u := urls.Parse .src }} + {{- $msg := "The %q shortcode was unable to resolve %s. See %s" }} + {{- if $u.IsAbs }} + {{- with resources.GetRemote $u.String }} + {{- with .Err }} + {{- errorf "%s" }} + {{- else }} + {{- /* This is a remote resource. */}} + {{- $r = . }} + {{- end }} + {{- else }} + {{- errorf $msg $.name $u.String $.position }} + {{- end }} + {{- else }} + {{- with .page.Resources.Get (strings.TrimPrefix "./" $u.Path) }} + {{- /* This is a page resource. */}} + {{- $r = . }} + {{- else }} + {{- with resources.Get $u.Path }} + {{- /* This is a global resource. */}} + {{- $r = . }} + {{- else }} + {{- errorf $msg $.name $u.Path $.position }} + {{- end }} + {{- end }} + {{- end }} + {{- return $r}} +{{- end -}} diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/include.html index a13dd756a,000000000..9ad6e4ecb mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/include.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/include.html @@@ -1,20 -1,0 +1,20 @@@ +{{- /* +Renders the page using the RenderShortcode method on the Page object. + +You must call this shortcode using the {{% %}} notation. + - @param {string} (postional parameter 0) The path to the page, relative to the content directory. ++@param {string} (positional parameter 0) The path to the page, relative to the content directory. +@returns template.HTML + +@example {{% include "functions/_common/glob-patterns" %}} +*/}} + +{{- with .Get 0 }} + {{- with site.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 path of the file to include. See %s" .Name .Position }} +{{- end }} diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/list-pages-in-section.html index 07a41d613,000000000..73e7f85a9 mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/list-pages-in-section.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/list-pages-in-section.html @@@ -1,96 -1,0 +1,96 @@@ +{{- /* - Renders a desciption list of the pages in the given section. ++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. + +The definition term elements (dt) have an id attribute derived from the title +of the page. This is probably unique, because pages of the same title in the +same section is unlikely. + +If you render a complete list on a page, then call the shortcode again to +render a subset, you will generate duplicate element ids. In this case, set +omitElementIDs to true for the subset. + +@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} [omitElementIDs=false] Whether to omit dt element ids. +@param {string} [titlePrefix=""] The string to prepend to the link title. + +@returns template.HTML + +@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=/functions/images filter=some_filter filterType=exclude titlePrefix=foo omitElementIDs=true >}} +*/}} + +{{- /* Initialize. */}} +{{- $filter := or "" (.Get "filter" | lower)}} +{{- $filterType := or (.Get "filterType") "none" | lower }} +{{- $filteredPages := slice }} +{{- $titlePrefix := or (.Get "titlePrefix") "" }} +{{- $omitElementIDs := false }} + +{{- /* Get boolean parameters. */}} +{{- if in (slice "false" false 0) (.Get "omitElementIDs") }} + {{- $omitElementIDs = false }} +{{- else if in (slice "true" true 1) (.Get "omitElementIDs")}} + {{- $omitElementIDs = true }} +{{- end }} + +{{- /* 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 }} + {{- $idAttribute := "" }} + {{- if not $omitElementIDs }} + {{- $id := path.Join .File.Dir .File.ContentBaseName | replaceRE `[\|/]` ":" | lower }} + {{- $idAttribute = printf " id=%q" $id }} + {{- end }} +
{{ $linkTitle }}
+
{{- $page.Description | $page.RenderString }}
+ {{- 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/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/new-in.html index 9236cf2bc,000000000..e22a91f3d mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/new-in.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/new-in.html @@@ -1,13 -1,0 +1,36 @@@ - {{ $version := .Get 0 }} - {{ if not $version }} - {{ errorf "Missing version in new-in shortcode " }} - {{ end }} - {{ $version = $version | strings.TrimPrefix "v" }} - ++{{- /* ++Renders a "new in" button indicating the version in which a feature was added. ++ ++When comparing the current version to the specified version, the "new in" ++button will be hidden if any of the following conditions is true: ++ ++- The major version difference exceeds the majorVersionDiffThreshold ++- The minor version difference exceeds the minorVersionDiffThreshold ++ ++@param {string} version The semantic version string, with or without a leading v. ++@returns {template.HTML} ++ ++@example {{< new-in 0.100.0 >}} ++*/}} ++ ++{{- /* Set defaults. */}} ++{{- $majorVersionDiffThreshold := 0 }} ++{{- $minorVersionDiffThreshold := 30 }} ++{{- $displayExpirationWarning := true }} ++ ++{{- /* Render. */}} ++{{- with $version := .Get 0 | strings.TrimPrefix "v" }} ++ {{- $majorVersionDiff := sub (index (split hugo.Version ".") 0 | int) (index (split $version ".") 0 | int) }} ++ {{- $minorVersionDiff := sub (index (split hugo.Version ".") 1 | int) (index (split $version ".") 1 | int) }} ++ {{- if or (gt $majorVersionDiff $majorVersionDiffThreshold) (gt $minorVersionDiff $minorVersionDiffThreshold) }} ++ {{- if $displayExpirationWarning }} ++ {{- warnf "This call to the %q shortcode should be removed: %s. The button is now hidden because the specified version (%s) is older than the display threshold." $.Name $.Position $version }} ++ {{- end }} ++ {{- else }} ++ ++ {{- end }} ++{{- else }} ++ {{- errorf "The %q shortcode requires a positional parameter (version). See %s" .Name .Position }} ++{{- end -}} diff --cc docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/quick-reference.html index 250bfc065,000000000..fc53c93bd mode 100644,000000..100644 --- a/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/quick-reference.html +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/layouts/shortcodes/quick-reference.html @@@ -1,37 -1,0 +1,39 @@@ +{{/* - Renders the child sections of the given top-level section, listing each childs's immediate descendants. ++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. +@returns template.HTML + +@example {{% quick-reference section="functions" %}} +*/}} + +{{ $section := "" }} +{{ with .Get "section" }} + {{ $section = . }} +{{ else }} - {{ errorf "The %q shortcodes requires a 'section' parameter. See %s" .Name .Postion }} ++ {{ errorf "The %q shortcodes requires a 'section' parameter. See %s" .Name .Position }} +{{ end }} + +{{/* Do not change the markdown indentation, and do not remove blank lines. */}} +{{ with site.GetPage $section }} + {{ range .Sections }} + +## {{ .LinkTitle }} +{{ .RawContent }} + + {{ range .Pages }} + {{ $aliases := "" }} + {{ if eq .Section "functions" }} - {{ $aliases = delimit .Params.action.aliases " or " }} ++ {{ with .Params.action.aliases }} ++ {{ $aliases = delimit . " or " }} ++ {{ end }} + {{ end }} + +[{{ .LinkTitle }}]({{ .RelPermalink }}) {{ with $aliases }}({{ . }}){{ end }} +: {{ .Description }} + + {{ end }} + {{ end }} +{{ else }} - {{ errorf "The %q shortcodes was unable to find the %q section. See %s" .Name $section .Postion }} ++ {{ errorf "The %q shortcodes was unable to find the %q section. See %s" .Name $section .Position }} +{{ end }} diff --cc docs/_vendor/modules.txt index 7a692e0ce,000000000..a7e53c51c mode 100644,000000..100644 --- a/docs/_vendor/modules.txt +++ b/docs/_vendor/modules.txt @@@ -1,1 -1,0 +1,1 @@@ - # github.com/gohugoio/gohugoioTheme v0.0.0-20231111235806-77931ac4875e ++# github.com/gohugoio/gohugoioTheme v0.0.0-20240125093153-bea12fdc0b15 diff --cc docs/config/_default/params.toml index b41679c61,000000000..dddd53b5b mode 100644,000000..100644 --- a/docs/config/_default/params.toml +++ b/docs/config/_default/params.toml @@@ -1,27 -1,0 +1,27 @@@ + +description = "The world’s fastest framework for building websites" +## Setting this to true will add a "noindex" to *EVERY* page on the site.. +removefromexternalsearch = false +## Gh repo for site footer (include trailing slash) +ghrepo = "https://github.com/gohugoio/hugoDocs/" +## GH Repo for filing a new issue +github_repo = "https://github.com/gohugoio/hugo/issues/new" +### Edit content repo (set to automatically enter "edit" mode; this is good for "improve this page" links) +ghdocsrepo = "https://github.com/gohugoio/hugoDocs/tree/master/docs" +## Discuss Forum URL +forum = "https://discourse.gohugo.io/" +## Google Tag Manager +gtmid = "" + +# First one is picked as the Twitter card image if not set on page. +images = ["images/gohugoio-card.png"] + +flex_box_interior_classes = "flex-auto w-100 w-40-l mr3 mb3 bg-white ba b--moon-gray nested-copy-line-height" + +#sidebar_direction = "sidebar_left" + +[social] - twitter = "GoHugoIO" ++ twitter = "GoHugoIOv2" + +[render_hooks.link] - errorLevel = 'warning' # ignore (default), warning, or error (fails the build) ++ errorLevel = 'warning' # ignore (default), warning, or error (fails the build) diff --cc docs/content/en/content-management/comments.md index 9985dd1e6,000000000..6e58b36e4 mode 100644,000000..100644 --- a/docs/content/en/content-management/comments.md +++ b/docs/content/en/content-management/comments.md @@@ -1,73 -1,0 +1,74 @@@ +--- +title: Comments +description: Hugo ships with an internal Disqus template, but this isn't the only commenting system that will work with your new Hugo website. +categories: [content management] +keywords: [sections,content,organization] +menu: + docs: + parent: content-management + weight: 220 +weight: 220 +toc: true +aliases: [/extras/comments/] +--- + +Hugo ships with support for [Disqus](https://disqus.com/), a third-party service that provides comment and community capabilities to websites via JavaScript. + +Your theme may already support Disqus, but if not, it is easy to add to your templates via [Hugo's built-in Disqus partial][disquspartial]. + +## Add Disqus + +Hugo comes with all the code you need to load Disqus into your templates. Before adding Disqus to your site, you'll need to [set up an account][disqussetup]. + +### Configure Disqus + +Disqus comments require you set a single value in your [site's configuration file][configuration] like so: + - {{< code-toggle file="hugo" >}} ++{{< code-toggle file=hugo >}} +[services.disqus] +shortname = 'your-disqus-shortname' +{{}} + +For many websites, this is enough configuration. However, you also have the option to set the following in the [front matter] of a single content file: + +* `disqus_identifier` +* `disqus_title` +* `disqus_url` + +### Render Hugo's built-in Disqus partial template + +Disqus has its own [internal template](/templates/internal/#disqus) available, to render it add the following code where you want comments to appear: + +```go-html-template +{{ template "_internal/disqus.html" . }} +``` + +## Alternatives + +These are some alternatives to Disqus: + +* [Cactus Comments](https://cactus.chat/docs/integrations/hugo/) (Open Source, Matrix appservice, Docker install) ++* [Comentario](https://gitlab.com/comentario/comentario) (Open Source, self-hosted, Go/Angular, run locally, in Docker or Kubernetes) +* [Commento](https://commento.io/) (Open Source, available as a service, local install, or docker image) +* [Giscus](https://giscus.app/) (Open source, comments system powered by GitHub Discussions) +* [Graph Comment](https://graphcomment.com/) +* [Hyvor Talk](https://talk.hyvor.com/) (Available as a service) +* [IntenseDebate](https://intensedebate.com/) +* [Isso](https://isso-comments.de/) (Self-hosted, Python) ([tutorial][issotutorial]) +* [Muut](https://muut.com/) +* [Remark42](https://remark42.com/) (Open source, Golang, Easy to run docker) +* [ReplyBox](https://getreplybox.com/) +* [Staticman](https://staticman.net/) +* [Talkyard](https://blog-comments.talkyard.io/) (Open source, & serverless hosting) +* [Utterances](https://utteranc.es/) (Open source, GitHub comments widget built on GitHub issues) + +[configuration]: /getting-started/configuration/ +[disquspartial]: /templates/internal/#disqus +[disqussetup]: https://disqus.com/profile/signup/ +[forum]: https://discourse.gohugo.io +[front matter]: /content-management/front-matter/ +[kaijuissue]: https://github.com/spf13/kaiju/issues/new +[issotutorial]: https://stiobhart.net/2017-02-24-isso-comments/ +[partials]: /templates/partials/ +[MongoDB]: https://www.mongodb.com/ +[tweet]: https://twitter.com/spf13 diff --cc docs/content/en/content-management/image-processing/index.md index 511365700,000000000..9a4f55da1 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,521 -1,0 +1,521 @@@ +--- +title: Image processing +description: Resize, crop, rotate, filter, and convert images. +categories: [content management,fundamentals] +keywords: [resources,images] +menu: + docs: + parent: content-management + weight: 90 +toc: true +weight: 90 +--- + +## Image resources + +To process an image you must access the file as a page resource, global resource, or remote resource. + +### Page resource + +A page resource is a file within a [page bundle]. A page bundle is a directory with an `index.md` or `_index.md` file at its root. + +```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 + +A global resource is a file within the `assets` directory, or within any directory [mounted] to the `assets` directory. + +```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 + +A remote resource is a file on a remote server, accessible via HTTP or HTTPS. 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 either a page resource or a global 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 +{{ $u := "https://gohugo.io/img/hugo-logo.png" }} +{{ with resources.GetRemote $u }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} + + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $u }} +{{ 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 or TIFF images. +{{% /note %}} + +### 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). +{{% /note %}} + +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 + +{{< new-in 0.104.0 >}} + +`.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 and TIFF 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 }} + +{{ end }} +``` + +#### EXIF variables + +.Date +: Image creation date/time. Format with the [time.Format] function. + +.Lat +: GPS latitude in degrees. + +.Long +: GPS longitude in degrees. + +.Tags +: A collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration](#exif-data). + +## 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. + +[`cwebp`]: https://developers.google.com/speed/webp/docs/cwebp + +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://commons.wikimedia.org/wiki/User:Bep) (Creative Commons Attribution-Share Alike 4.0 International license)_ + +{{< imgproc "sunset.jpg" "resize 300x" />}} + +{{< imgproc "sunset.jpg" "fill 90x120 left" />}} + +{{< imgproc "sunset.jpg" "fill 90x120 right" />}} + +{{< imgproc "sunset.jpg" "fit 90x90" />}} + +{{< imgproc "sunset.jpg" "crop 250x250 center" />}} + +{{< imgproc "sunset.jpg" "resize 300x q10" />}} + +This is the shortcode used to generate the examples above: + +{{< readfile file=layouts/shortcodes/imgproc.html highlight=go-html-template >}} + +Call the shortcode from your Markdown like this: + +```go-html-template +{{}} +``` + +{{% note %}} +Note the self-closing shortcode syntax above. You may call the `imgproc` shortcode with or without **inner content**. +{{% /note %}} + +## Imaging configuration + +### Processing options + +Define an `imaging` section in your site configuration to set the default [image processing options](#image-processing-options). + +{{< code-toggle config=imaging />}} + +anchor +: See image processing options: [anchor](#anchor). + +bgColor +: See image processing options: [background color](#background-color). + +hint +: See image processing options: [hint](#hint). + +quality +: See image processing options: [quality](#quality). + +resampleFilter +: See image processing options: [resampling filter](#resampling-filter). + +### EXIF data + +Define an `imaging.exif` section in your site configuration to control the availability of EXIF data. + +{{< code-toggle file=hugo >}} +[imaging.exif] +includeFields = "" +excludeFields = "" +disableDate = false +disableLatLong = false +{{< /code-toggle >}} + +disableDate +: Hugo extracts the image creation date/time into `.Date`. Set this to `true` to disable. Default is `false`. + +disableLatLong +: Hugo extracts the GPS latitude and longitude into `.Lat` and `.Long`. Set this to `true` to disable. Default is `false`. + +excludeFields +: Regular expression matching the EXIF tags to exclude from the `.Tags` collection. Default is `""`. + +includeFields +: Regular expression matching the EXIF tags to include in the `.Tags` collection. Default is `""`. To include all available tags, set this value to `".*"`. + +{{% note %}} +To improve performance and decrease cache size, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`. + +To control tag availability, change the `excludeFields` or `includeFields` settings as described above. +{{% /note %}} + +## 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 "sunset.jpg" "fill 200x200 smart" />}} + +{{< imgproc "sunset.jpg" "crop 200x200 smart" />}} + +## 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 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 +``` + +[time.Format]: /functions/time/format +[`anchor`]: /content-management/image-processing#anchor +[mounted]: /hugo-modules/configuration#module-configuration-mounts +[page bundle]: /content-management/page-bundles +[`lang.FormatNumber`]: /functions/lang/formatnumber - [filters]: /functions/images ++[filters]: /functions/images/filter/#image-filters +[github.com/disintegration/imaging]: +[Smartcrop]: +[Exif]: +[`Process`]: #process +[`Colors`]: #colors +[`Crop`]: #crop +[`Exif`]: #exif +[`Fill`]: #fill +[`Filter`]: #filter +[`Fit`]: #fit +[`Resize`]: #resize +[site configuration]: #processing-options +[`with`]: /functions/go-template/with/ diff --cc docs/content/en/content-management/menus.md index e2a72f124,000000000..1f5d1ef71 mode 100644,000000..100644 --- a/docs/content/en/content-management/menus.md +++ b/docs/content/en/content-management/menus.md @@@ -1,224 -1,0 +1,232 @@@ +--- +title: Menus +description: Create menus by defining entries, localizing each entry, and rendering the resulting data structure. +categories: [content management] +keywords: [menus] +menu: + docs: + parent: content-management + weight: 190 +weight: 190 +toc: true +aliases: [/extras/menus/] +--- + +## Overview + +To create a menu for your site: + +1. Define the menu entries +2. [Localize] each entry +3. Render the menu with a [template] + +Create multiple menus, either flat or nested. For example, create a main menu for the header, and a separate menu for the footer. + +There are three ways to define menu entries: + +1. Automatically +1. In front matter +1. In site configuration + +{{% note %}} +Although you can use these methods in combination when defining a menu, the menu will be easier to conceptualize and maintain if you use one method throughout the site. +{{% /note %}} + +## Define automatically + +To automatically define menu entries for each top-level section of your site, enable the section pages menu in your site configuration. + +{{< code-toggle file=hugo >}} +sectionPagesMenu = "main" +{{< /code-toggle >}} + +This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details. + +## Define in front matter + +To add a page to the "main" menu: + +{{< code-toggle file=content/about.md fm=true >}} +title = 'About' - menu = 'main' ++menus = 'main' +{{< /code-toggle >}} + +Access the entry with `site.Menus.main` in your templates. See [menu templates] for details. + +To add a page to the "main" and "footer" menus: + +{{< code-toggle file=content/contact.md fm=true >}} +title = 'Contact' - menu = ['main','footer'] ++menus = ['main','footer'] +{{< /code-toggle >}} + +Access the entry with `site.Menus.main` and `site.Menus.footer` in your templates. See [menu templates] for details. + ++{{% note %}} ++The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`. ++{{% /note %}} ++ +### Properties {#properties-front-matter} + +Use these properties when defining menu entries in front matter: + +identifier +: (`string`) Required when two or more menu entries have the same `name`, or when localizing the `name` using translation tables. Must start with a letter, followed by letters, digits, or underscores. + +name +: (`string`) The text to display when rendering the menu entry. + +params +: (`map`) User-defined properties for the menu entry. + +parent +: (`string`) The `identifier` of the parent menu entry. If `identifier` is not defined, use `name`. Required for child entries in a nested menu. + +post +: (`string`) The HTML to append when rendering the menu entry. + +pre +: (`string`) The HTML to prepend when rendering the menu entry. + +title +: (`string`) The HTML `title` attribute of the rendered menu entry. + +weight +: (`int`) A non-zero integer indicating the entry's position relative the root of the menu, or to its parent for a child entry. Lighter entries float to the top, while heavier entries sink to the bottom. + +### Example {#example-front-matter} + +This front matter menu entry demonstrates some of the available properties: + +{{< code-toggle file=content/products/software.md fm=true >}} +title = 'Software' - [menu.main] ++[[menus.main]] +parent = 'Products' +weight = 20 +pre = '' - [menu.main.params] ++[menus.main.params] +class = 'center' +{{< /code-toggle >}} + +Access the entry with `site.Menus.main` in your templates. See [menu templates] for details. + +## Define in site configuration + +To define entries for the "main" menu: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Home' +pageRef = '/' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Products' +pageRef = '/products' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 30 +{{< /code-toggle >}} + +This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details. + +To define entries for the "footer" menu: + +{{< code-toggle file=hugo >}} - [[menu.footer]] ++[[menus.footer]] +name = 'Terms' +pageRef = '/terms' +weight = 10 + - [[menu.footer]] ++[[menus.footer]] +name = 'Privacy' +pageRef = '/privacy' +weight = 20 +{{< /code-toggle >}} + +This creates a menu structure that you can access with `site.Menus.footer` in your templates. See [menu templates] for details. + ++{{% note %}} ++The configuration key in the examples above is `menus`. The `menu` (singular) configuration key is an alias for `menus`. ++{{% /note %}} ++ +### Properties {#properties-site-configuration} + +{{% note %}} +The [properties available to entries defined in front matter] are also available to entries defined in site configuration. + +[properties available to entries defined in front matter]: /content-management/menus/#properties-front-matter +{{% /note %}} + +Each menu entry defined in site configuration requires two or more properties: + +- Specify `name` and `pageRef` for internal links +- Specify `name` and `url` for external links + +pageRef +: (`string`) The file path of the target page, relative to the `content` directory. Omit language code and file extension. Required for *internal* links. + +Kind|pageRef +:--|:-- +home|`/` +page|`/books/book-1` +section|`/books` +taxonomy|`/tags` +term|`/tags/foo` + +url +: (`string`) Required for *external* links. + +### Example {#example-site-configuration} + +This nested menu demonstrates some of the available properties: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Products' +pageRef = '/products' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Hardware' +pageRef = '/products/hardware' +parent = 'Products' +weight = 1 + - [[menu.main]] ++[[menus.main]] +name = 'Software' +pageRef = '/products/software' +parent = 'Products' +weight = 2 + - [[menu.main]] ++[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Hugo' +pre = '' +url = 'https://gohugo.io/' +weight = 30 - [menu.main.params] ++[menus.main.params] +rel = 'external' +{{< /code-toggle >}} + +This creates a menu structure that you can access with `site.Menus.main` in your templates. See [menu templates] for details. + +## Localize + +Hugo provides two methods to localize your menu entries. See [multilingual]. + +## Render + +See [menu templates]. + +[localize]: /content-management/multilingual/#menus +[menu templates]: /templates/menu-templates/ +[multilingual]: /content-management/multilingual/#menus +[template]: /templates/menu-templates/ diff --cc docs/content/en/content-management/multilingual.md index 07eecbaaf,000000000..ea9f71787 mode 100644,000000..100644 --- a/docs/content/en/content-management/multilingual.md +++ b/docs/content/en/content-management/multilingual.md @@@ -1,717 -1,0 +1,716 @@@ +--- +title: Multilingual mode +linkTitle: Multilingual +description: Hugo supports the creation of websites with multiple languages side by side. +categories: [content management] +keywords: [multilingual,i18n,internationalization] +menu: + docs: + parent: content-management + weight: 230 +weight: 230 +toc: true +aliases: [/content/multilingual/,/tutorials/create-a-multilingual-site/] +--- + +You should define the available languages in a `languages` section in your site configuration. + +Also See [Hugo Multilingual Part 1: Content translation]. + +## Configure languages + +This is the default language configuration: + +{{< code-toggle config=languages />}} + +This is an example of a site configuration for a multilingual project. Any key not defined in a `languages` object will fall back to the global value in the root of your site configuration. + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'de' +defaultContentLanguageInSubdir = true + +[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 >}} + +defaultContentLanguage +: (`string`) The project's default language tag as defined by [RFC 5646]. Must be lower case, and must match one of the defined language keys. Default is `en`. Examples: + +- `en` +- `en-gb` +- `pt-br` + +defaultContentLanguageInSubdir +: (`bool`) If `true`, Hugo renders the default language site in a subdirectory matching the `defaultContentLanguage`. Default is `false`. + +contentDir +: (`string`) The content directory for this language. Omit if [translating by file name]. + +disabled +: (`bool`) If `true`, Hugo will not render content for this language. Default is `false`. + +languageCode - : (`string`) The language tag as defined by [RFC 5646]. This value may include upper and lower case characters, hyphens or underscores, and does not affect localization or URLs. Hugo uses this value to populate the `language` element in the [built-in RSS template], and the `lang` attribute of the `html` element in the [built-in alias template]. Examples: ++: (`string`) The language tag as defined by [RFC 5646]. This value may include upper and lower case characters, hyphens, or underscores, and does not affect localization or URLs. Hugo uses this value to populate the `language` element in the [built-in RSS template], and the `lang` attribute of the `html` element in the [built-in alias template]. Examples: + +- `en` +- `en-GB` +- `pt-BR` + +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. + +languageName +: (`string`) The language name, typically used when rendering a language switcher. + +title +: (`string`) The language title. When set, this overrides the site title for this language. + +weight +: (`int`) The language weight. When set to a non-zero value, this is the primary sort criteria for this language. + +[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir +[built-in RSS template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml +[built-in alias template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/alias.html +[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646 +[translating by file name]: #translation-by-file-name + +### Changes in Hugo 0.112.0 + +{{< new-in 0.112.0 >}} + +In Hugo `v0.112.0` we consolidated all configuration options, and improved how the languages and their parameters are merged with the main configuration. But while testing this on Hugo sites out there, we received some error reports and reverted some of the changes in favor of deprecation warnings: + +1. `site.Language.Params` is deprecated. Use `site.Params` directly. +1. Adding custom parameters to the top level language configuration is deprecated. Define custom parameters within `languages.xx.params`. See `color` in the example below. + +{{< code-toggle file=hugo >}} + +title = "My blog" +languageCode = "en-us" + +[languages] +[languages.sv] +title = "Min blogg" +languageCode = "sv" +[languages.en.params] +color = "blue" +{{< /code-toggle >}} + +In the example above, all settings except `color` below `params` map to predefined configuration options in Hugo for the site and its language, and should be accessed via the documented accessors: + +```go-html-template +{{ site.Title }} +{{ site.LanguageCode }} +{{ site.Params.color }} +``` + +### Disable a language + +To disable a language within a `languages` object in your site configuration: + +{{< code-toggle file=hugo >}} +[languages.es] +disabled = true +{{< /code-toggle >}} + +To disable one or more languages in the root of your site configuration: + +{{< code-toggle file=hugo >}} +disableLanguages = ["es", "fr"] +{{< /code-toggle >}} + +To disable one or more languages using an environment variable: + +```sh +HUGO_DISABLELANGUAGES="es fr" hugo +``` + +Note that you cannot disable the default content language. + +### Configure multilingual multihost + +From **Hugo 0.31** we support multiple languages in a multihost configuration. See [this issue](https://github.com/gohugoio/hugo/issues/4027) for details. + +This means that you can now configure a `baseURL` per `language`: + +{{% note %}} +If a `baseURL` is set on the `language` level, then all languages must have one and they must all be different. +{{% /note %}} + +Example: + +{{< code-toggle file=hugo >}} +[languages] +[languages.fr] +baseURL = "https://example.fr" +languageName = "Français" +weight = 1 +title = "En Français" + +[languages.en] +baseURL = "https://example.org/" +languageName = "English" +weight = 2 +title = "In English" +{{}} + +With the above, the two sites will be generated into `public` with their own root: + +```text +public +├── en +└── fr +``` + +**All URLs (i.e `.Permalink` etc.) will be generated from that root. So the English home page above will have its `.Permalink` set to `https://example.org/`.** + +When you run `hugo server` we will start multiple HTTP servers. You will typically see something like this in the console: + +```text +Web Server is available at 127.0.0.1:1313 (bind address 127.0.0.1) fr +Web Server is available at 127.0.0.1:1314 (bind address 127.0.0.1) en +Press Ctrl+C to stop +``` + +Live reload and `--navigateToChanged` between the servers work as expected. + +## Translate your content + +There are two ways to manage your content translations. Both ensure each page is assigned a language and is linked to its counterpart translations. + +### Translation by file name + +Considering the following example: + +1. `/content/about.en.md` +2. `/content/about.fr.md` + +The first file is assigned the English language and is linked to the second. +The second file is assigned the French language and is linked to the first. + +Their language is __assigned__ according to the language code added as a __suffix to the file name__. + +By having the same **path and base file name**, the content pieces are __linked__ together as translated pages. + +{{% note %}} +If a file has no language code, it will be assigned the default language. +{{% /note %}} + +### Translation by content directory + +This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` parameter. + +{{< code-toggle file=hugo >}} +languages: + en: + weight: 10 + languageName: "English" + contentDir: "content/english" + fr: + weight: 20 + languageName: "Français" + contentDir: "content/french" +{{< /code-toggle >}} + +The value of `contentDir` can be any valid path -- even absolute path references. The only restriction is that the content directories cannot overlap. + +Considering the following example in conjunction with the configuration above: + +1. `/content/english/about.md` +2. `/content/french/about.md` + +The first file is assigned the English language and is linked to the second. +The second file is assigned the French language and is linked to the first. + +Their language is __assigned__ according to the content directory they are __placed__ in. + +By having the same **path and basename** (relative to their language content directory), the content pieces are __linked__ together as translated pages. + +### Bypassing default linking + +Any pages sharing the same `translationKey` set in front matter will be linked as translated pages regardless of basename or location. + +Considering the following example: + +1. `/content/about-us.en.md` +2. `/content/om.nn.md` +3. `/content/presentation/a-propos.fr.md` + +{{< code-toggle >}} +translationKey: "about" +{{< /code-toggle >}} + +By setting the `translationKey` front matter parameter to `about` in all three pages, they will be __linked__ as translated pages. + +### Localizing permalinks + +Because paths and file names are used to handle linking, all translated pages will share the same URL (apart from the language subdirectory). + +To localize URLs: + +- For a regular page, set either [`slug`] or [`url`] in front matter +- For a section page, set [`url`] in front matter + +[`slug`]: /content-management/urls/#slug +[`url`]: /content-management/urls/#url + +For example, a French translation can have its own localized slug. + +{{< code-toggle file=content/about.fr.md fm=true >}} +title: A Propos +slug: "a-propos" +{{< /code-toggle >}} + +At render, Hugo will build both `/about/` and `/fr/a-propos/` without affecting the translation link. + +### Page bundles + +To avoid the burden of having to duplicate files, each Page Bundle inherits the resources of its linked translated pages' bundles except for the content files (Markdown files, HTML files etc...). + +Therefore, from within a template, the page will have access to the files from all linked pages' bundles. + +If, across the linked bundles, two or more files share the same basename, only one will be included and chosen as follows: + +* File from current language bundle, if present. +* First file found across bundles by order of language `Weight`. + +{{% note %}} +Page Bundle resources follow the same language assignment logic as content files, both by file name (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`). +{{%/ note %}} + +## Reference translated content + +To create a list of links to translated content, use a template similar to the following: + +{{< code file=layouts/partials/i18nlist.html >}} +{{ if .IsTranslated }} +

{{ i18n "translations" }}

+ +{{ end }} +{{< /code >}} + +The above can be put in a `partial` (i.e., inside `layouts/partials/`) and included in any template, whether a [single content page][contenttemplate] or the [homepage]. It will not print anything if there are no translations for a given page. + +The above also uses the [`i18n` function][i18func] described in the next section. + +### List all available languages + +`.AllTranslations` on a `Page` can be used to list all translations, including the page itself. On the home page it can be used to build a language navigator: + +{{< code file=layouts/partials/allLanguages.html >}} + +{{< /code >}} + +## Translation of strings + +Hugo uses [go-i18n] to support string translations. [See the project's source repository][go-i18n-source] to find tools that will help you manage your translation workflows. + +Translations are collected from the `themes//i18n/` folder (built into the theme), as well as translations present in `i18n/` at the root of your project. In the `i18n`, the translations will be merged and take precedence over what is in the theme folder. Language files should be named according to [RFC 5646] with names such as `en-US.toml`, `fr.toml`, etc. + +Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7](https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7) are also supported. You may omit the `art-x-` prefix for brevity. For example: + +```text +art-x-hugolang +hugolang +``` + +Private use subtags must not exceed 8 alphanumeric characters. + +### Query basic translation + +From within your templates, use the [`i18n`] function like this: + +[`i18n`]: /functions/lang/translate + +```go-html-template +{{ i18n "home" }} +``` + +The function will search for the `"home"` id: + +{{< code-toggle file=i18n/en-US >}} +[home] +other = "Home" +{{< /code-toggle >}} + +The result will be + +```text +Home +``` + +### Query a flexible translation with variables + +Often you will want to use the page variables in the translation strings. To do so, pass the `.` context when calling `i18n`: + +```go-html-template +{{ i18n "wordCount" . }} +``` + +The function will pass the `.` context to the `"wordCount"` id: + +{{< code-toggle file=i18n/en-US >}} +[wordCount] +other = "This article has {{ .WordCount }} words." +{{< /code-toggle >}} + +Assume `.WordCount` in the context has value is 101. The result will be: + +```text +This article has 101 words. +``` + +### Query a singular/plural translation + +To enable pluralization when translating, pass a map with a numeric `.Count` property to the `i18n` function. The example below uses `.ReadingTime` variable which has a built-in `.Count` property. + +```go-html-template +{{ i18n "readingTime" .ReadingTime }} +``` + +The function will read `.Count` from `.ReadingTime` and evaluate whether the number is singular (`one`) or plural (`other`). After that, it will pass to `readingTime` id in `i18n/en-US.toml` file: + +{{< code-toggle file=i18n/en-US >}} +[readingTime] +one = "One minute to read" +other = "{{ .Count }} minutes to read" +{{< /code-toggle >}} + +Assuming `.ReadingTime.Count` in the context has value is 525600. The result will be: + +```text +525600 minutes to read +``` + +If `.ReadingTime.Count` in the context has value is 1. The result is: + +```text +One minute to read +``` + +In case you need to pass a custom data: (`(dict "Count" numeric_value_only)` is minimum requirement) + +```go-html-template +{{ i18n "readingTime" (dict "Count" 25 "FirstArgument" true "SecondArgument" false "Etc" "so on, so far") }} +``` + +## Localization + +The following localization examples assume your site's primary language is English, with translations to French and German. + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages] +[languages.en] +contentDir = 'content/en' +languageName = 'English' +weight = 1 +[languages.fr] +contentDir = 'content/fr' +languageName = 'Français' +weight = 2 +[languages.de] +contentDir = 'content/de' +languageName = 'Deutsch' +weight = 3 + +{{< /code-toggle >}} + +### Dates + +With this front matter: + +{{< code-toggle >}} +date = 2021-11-03T12:34:56+01:00 +{{< /code-toggle >}} + +And this template code: + +```go-html-template +{{ .Date | time.Format ":date_full" }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|Wednesday, November 3, 2021 +Français|mercredi 3 novembre 2021 +Deutsch|Mittwoch, 3. November 2021 + +See [`time.Format`] for details. + +### Currency + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatCurrency 2 "USD" }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|$512.50 +Français|512,50 $US +Deutsch|512,50 $ + +See [lang.FormatCurrency] and [lang.FormatAccounting] for details. + +### Numbers + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatNumber 2 }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|512.50 +Français|512,50 +Deutsch|512,50 + +See [lang.FormatNumber] and [lang.FormatNumberCustom] for details. + +### Percentages + +With this template code: + +```go-html-template +{{ 512.5032 | lang.FormatPercent 2 }} +``` + +The rendered page displays: + +Language|Value +:--|:-- +English|512.50% +Français|512,50 % +Deutsch|512,50 % + +See [lang.FormatPercent] for details. + +## Menus + +Localization of menu entries depends on how you define them: + +- When you define menu entries [automatically] using the section pages menu, you must use translation tables to localize each entry. +- When you define menu entries [in front matter], they are already localized based on the front matter itself. If the front matter values are insufficient, use translation tables to localize each entry. +- When you define menu entries [in site configuration], you must create language-specific menu entries under each language key. If the names of the menu entries are insufficient, use translation tables to localize each entry. + +### Create language-specific menu entries + +#### Method 1 -- Use a single configuration file + +For a simple menu with a small number of entries, use a single configuration file. For example: + +{{< code-toggle file=hugo >}} +[languages.de] +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 1 + - [[languages.de.menu.main]] ++[[languages.de.menus.main]] +name = 'Produkte' +pageRef = '/products' +weight = 10 + - [[languages.de.menu.main]] ++[[languages.de.menus.main]] +name = 'Leistungen' +pageRef = '/services' +weight = 20 + +[languages.en] +languageCode = 'en-US' +languageName = 'English' +weight = 2 + - [[languages.en.menu.main]] ++[[languages.en.menus.main]] +name = 'Products' +pageRef = '/products' +weight = 10 + - [[languages.en.menu.main]] ++[[languages.en.menus.main]] +name = 'Services' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +#### Method 2 -- Use a configuration directory + +With a more complex menu structure, create a [configuration directory] and split the menu entries into multiple files, one file per language. For example: + +```text +config/ +└── _default/ - ├── menus/ - │ ├── menu.de.toml - │ └── menu.en.toml ++ ├── menus.de.toml ++ ├── menus.en.toml + └── hugo.toml +``` + - {{< code-toggle file=config/_default/menus/menu.de >}} ++{{< code-toggle file=config/_default/menus.de >}} +[[main]] +name = 'Produkte' +pageRef = '/products' +weight = 10 +[[main]] +name = 'Leistungen' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + - {{< code-toggle file=config/_default/menus/menu.en >}} ++{{< code-toggle file=config/_default/menus.en >}} +[[main]] +name = 'Products' +pageRef = '/products' +weight = 10 +[[main]] +name = 'Services' +pageRef = '/services' +weight = 20 +{{< /code-toggle >}} + +[configuration directory]: /getting-started/configuration/#configuration-directory + +### Use translation tables + +When rendering the text that appears in menu each entry, the [example menu template] does this: + +```go-html-template +{{ or (T .Identifier) .Name | safeHTML }} +``` + +It queries the translation table for the current language using the menu entry's `identifier` and returns the translated string. If the translation table does not exist, or if the `identifier` key is not present in the translation table, it falls back to `name`. + +The `identifier` depends on how you define menu entries: + +- If you define the menu entry [automatically] using the section pages menu, the `identifier` is the page's `.Section`. +- If you define the menu entry [in site configuration] or [in front matter], set the `identifier` property to the desired value. + +For example, if you define menu entries in site configuration: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] + identifier = 'products' + name = 'Products' + pageRef = '/products' + weight = 10 - [[menu.main]] ++[[menus.main]] + identifier = 'services' + name = 'Services' + pageRef = '/services' + weight = 20 +{{< / code-toggle >}} + +Create corresponding entries in the translation tables: + +{{< code-toggle file=i18n/de >}} +products = 'Produkte' +services = 'Leistungen' +{{< / code-toggle >}} + +[example menu template]: /templates/menu-templates/#example +[automatically]: /content-management/menus/#define-automatically +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/#define-in-site-configuration + +## Missing translations + +If a string does not have a translation for the current language, Hugo will use the value from the default language. If no default value is set, an empty string will be shown. + +While translating a Hugo website, it can be handy to have a visual indicator of missing translations. The [`enableMissingTranslationPlaceholders` configuration option][config] will flag all untranslated strings with the placeholder `[i18n] identifier`, where `identifier` is the id of the missing translation. + +{{% note %}} +Hugo will generate your website with these missing translation placeholders. It might not be suitable for production environments. +{{% /note %}} + +For merging of content from other languages (i.e. missing content translations), see [lang.Merge]. + +To track down missing translation strings, run Hugo with the `--printI18nWarnings` flag: + +```sh +hugo --printI18nWarnings | grep i18n +i18n|MISSING_TRANSLATION|en|wordCount +``` + +## Multilingual themes support + +To support Multilingual mode in your themes, some considerations must be taken for the URLs in the templates. If there is more than one language, URLs must meet the following criteria: + +* Come from the built-in `.Permalink` or `.RelPermalink` +* Be constructed with the [`relLangURL`] or [`absLangURL`] template function, or be prefixed with `{{ .LanguagePrefix }}` + +If there is more than one language defined, the `LanguagePrefix` variable will equal `/en` (or whatever your `CurrentLanguage` is). If not enabled, it will be an empty string (and is therefore harmless for single-language Hugo websites). + +## Generate multilingual content with `hugo new content` + +If you organize content with translations in the same directory: + +```sh +hugo new content post/test.en.md +hugo new content post/test.de.md +``` + +If you organize content with translations in different directories: + +```sh +hugo new content content/en/post/test.md +hugo new content content/de/post/test.md +``` + +[`abslangurl`]: /functions/urls/abslangurl +[config]: /getting-started/configuration/ +[contenttemplate]: /templates/single-page-templates/ +[go-i18n-source]: https://github.com/nicksnyder/go-i18n +[go-i18n]: https://github.com/nicksnyder/go-i18n +[homepage]: /templates/homepage/ +[Hugo Multilingual Part 1: Content translation]: https://regisphilibert.com/blog/2018/08/hugo-multilingual-part-1-managing-content-translation/ +[i18func]: /functions/lang/translate +[lang.FormatAccounting]: /functions/lang/formataccounting +[lang.FormatCurrency]: /functions/lang/formatcurrency +[lang.FormatNumber]: /functions/lang/formatnumber +[lang.FormatNumberCustom]: /functions/lang/formatnumbercustom +[lang.FormatPercent]: /functions/lang/formatpercent +[lang.Merge]: /functions/lang/merge/ +[menus]: /content-management/menus/ +[OS environment]: /getting-started/configuration/#configure-with-environment-variables +[`rellangurl`]: /functions/urls/rellangurl +[RFC 5646]: https://tools.ietf.org/html/rfc5646 +[single page templates]: /templates/single-page-templates/ +[`time.Format`]: /functions/time/format diff --cc docs/content/en/content-management/summaries.md index 2ff1fec34,000000000..22ed3fc81 mode 100644,000000..100644 --- a/docs/content/en/content-management/summaries.md +++ b/docs/content/en/content-management/summaries.md @@@ -1,110 -1,0 +1,110 @@@ +--- +title: Content summaries +linkTitle: Summaries +description: Hugo generates summaries of your content. +categories: [content management] +keywords: [summaries,abstracts,read more] +menu: + docs: + parent: content-management + weight: 160 +weight: 160 +toc: true +aliases: [/content/summaries/,/content-management/content-summaries/] +--- + + + +With the use of the `.Summary` [page variable][pagevariables], Hugo generates summaries of content to use as a short version in summary views. + +## Summary splitting options + +* Automatic Summary Split +* Manual Summary Split +* Front Matter Summary + +It is natural to accompany the summary with links to the original content, and a common design pattern is to see this link in the form of a "Read More ..." button. See the `.RelPermalink`, `.Permalink`, and `.Truncated` [page variables][pagevariables]. + +### Automatic summary splitting + +By default, Hugo automatically takes the first 70 words of your content as its summary and stores it into the `.Summary` page variable for use in your templates. You may customize the summary length by setting `summaryLength` in your [site configuration](/getting-started/configuration/). + +{{% note %}} +You can customize how HTML tags in the summary are loaded using functions such as `plainify` and `safeHTML`. +{{% /note %}} + +{{% note %}} +The Hugo-defined summaries are set to use word count calculated by splitting the text by one or more consecutive whitespace characters. If you are creating content in a `CJK` language and want to use Hugo's automatic summary splitting, set `hasCJKLanguage` to `true` in your [site configuration](/getting-started/configuration/). +{{% /note %}} + +### Manual summary splitting + +Alternatively, you may add the `` summary divider where you want to split the article. + +For [Org mode content][org], use `# more` where you want to split the article. + +Content that comes before the summary divider will be used as that content's summary and stored in the `.Summary` page variable with all HTML formatting intact. + +{{% note %}} +The concept of a *summary divider* is not unique to Hugo. It is also called the "more tag" or "excerpt separator" in other literature. +{{% /note %}} + +Pros +: Freedom, precision, and improved rendering. All HTML tags and formatting are preserved. + +Cons +: Extra work for content authors, since they need to remember to type `` (or `# more` for [org content][org]) in each content file. This can be automated by adding the summary divider below the front matter of an [archetype](/content-management/archetypes/). + +{{% note %}} +Be careful to enter `` exactly; i.e., all lowercase and with no whitespace. +{{% /note %}} + +### Front matter summary + +You might want your summary to be something other than the text that starts the article. In this case you can provide a separate summary in the `summary` variable of the article front matter. + +Pros +: Complete freedom of text independent of the content of the article. Markup can be used within the summary. + +Cons +: Extra work for content authors as they need to write an entirely separate piece of text as the summary of the article. + +## Summary selection order + +Because there are multiple ways in which a summary can be specified it is useful to understand the order of selection Hugo follows when deciding on the text to be returned by `.Summary`. It is as follows: + - 1. If there is a ``> summary divider present in the article the text up to the divider will be provided as per the manual summary split method ++1. If there is a `` summary divider present in the article, the text up to the divider will be provided as per the manual summary split method +2. If there is a `summary` variable in the article front matter the value of the variable will be provided as per the front matter summary method +3. The text at the start of the article will be provided as per the automatic summary split method + +{{% note %}} +Hugo uses the _first_ of the above steps that returns text. So if, for example, your article has both `summary` variable in its front matter and a `` summary divider Hugo will use the manual summary split method. +{{% /note %}} + +## Example: first 10 articles with summaries + +You can show content summaries with the following code. You could use the following snippet, for example, in a [section template]. + +{{< code file=page-list-with-summaries.html >}} +{{ range first 10 .Pages }} + +{{ end }} +{{< /code >}} + +Note how the `.Truncated` boolean variable value may be used to hide the "Read More..." link when the content is not truncated; i.e., when the summary contains the entire article. + +[org]: /content-management/formats/ +[pagevariables]: /variables/page/ +[section template]: /templates/section-templates/ diff --cc docs/content/en/contribute/documentation.md index 14df5cdee,000000000..862df619f mode 100644,000000..100644 --- a/docs/content/en/contribute/documentation.md +++ b/docs/content/en/contribute/documentation.md @@@ -1,375 -1,0 +1,371 @@@ +--- +title: Documentation +description: Help us to improve the documentation by identifying issues and suggesting changes. +categories: [contribute] +keywords: [documentation] +menu: + docs: + parent: contribute + weight: 30 +weight: 30 +toc: true +aliases: [/contribute/docs/] +--- + +## Introduction + +We welcome corrections and improvements to the documentation. Please note that the documentation resides in its own repository, separate from the project repository. + +For corrections and improvements to the current documentation, please submit issues and pull requests to the [documentation repository]. + +For documentation related to a new feature, please include the documentation changes when you submit a pull request to the [project repository]. + +## Guidelines + +### Markdown + +Please follow these markdown guidelines: + +- Use [ATX] headings, not [setext] headings, levels 2 through 4 +- Use [fenced code blocks], not [indented code blocks] +- Use hyphens, not asterisks, with unordered [list items] +- Use the [note shortcode] instead of blockquotes +- Do not mix [raw HTML] within markdown +- Do not use bold text instead of a heading or description term (`dt`) +- Remove consecutive blank lines (maximum of two) +- Remove trailing spaces + +### Style + +Although we do not strictly adhere to the [Microsoft Writing Style Guide], it is an excellent resource for questions related to style, grammar, and voice. + +#### Terminology + +Please link to the [glossary of terms] when necessary, and use the terms consistently throughout the documentation. Of special note: + +- The term "front matter" is two words unless you are referring to the configuration key +- Use the word "map" instead of "dictionary" +- Use the word "flag" instead of "option" when referring to a command line flag + +#### Page titles and headings + +Please follow these guidelines for page titles and headings: + +- Use sentence-style capitalization +- Avoid markdown in headings and page titles +- Shorter is better + +#### Use active voice with present tense + +In software documentation, passive voice is unavoidable in some cases. Please use active voice when 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. + +#### Avoid adverbs when possible + +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). +{{% /note %}} + +#### Miscellaneous + +Other guidelines to consider: + +- Do not place list items directly under a heading; include an introductory sentence or phrase before the list. +- Avoid use of **bold** text. Use the [note shortcode] to draw attention to important content. +- Do not place description terms (`dt`) within backticks unless required for syntactic clarity. +- Do not use Hugo's `ref` or `relref` shortcodes. We use a link render hook to resolve and validate link destinations, including fragments. +- Shorter is better. If there is more than one way to do something, describe the current best practice. For example, avoid phrases such as "you can also do..." and "in older versions you had to..." +- When including code samples, use short snippets that demonstrate the concept. +- The Hugo user community is global; use [basic english](https://simple.wikipedia.org/wiki/Basic_English) when possible. + +#### Level 6 markdown headings + +Level 6 markdown headings are styled as `dt` elements. This was implemented to support a [glossary] with linkable terms. + +[glossary]: /getting-started/glossary + +## Code examples + - Indent code by two spaces. With examples of template code, include a space after opening action delimiters, and include a space before closing action delimeters. ++Indent code by two spaces. With examples of template code, include a space after opening action delimiters, and include a space before closing action delimiters. + +### Fenced code blocks + +Always include the language code when using a fenced code block: + +````text +```go-html-template +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} +``` +```` + +Rendered: + +```go-html-template +{{ if eq $foo "bar" }} + {{ print "foo is bar" }} +{{ end }} +``` + +### Shortcode calls + +Use this syntax to include shortcodes calls within your code examples: + +```text +{{}} +{{%/*/* foo */*/%}} +``` + +Rendered: + +```text +{{}} +{{%/* foo */%}} +``` + +### Site configuration + +Use the [code-toggle shortcode] to include site configuration examples: + +```text +{{}} +baseURL = 'https://example.org/' +languageCode = 'en-US' +title = 'My Site' +{{}} +``` + +Rendered: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/' +languageCode = 'en-US' +title = 'My Site' +{{< /code-toggle >}} + +### Front matter + +Use the [code-toggle shortcode] to include front matter examples: + +```text +{{}} +title = 'My first post' +date = 2023-11-09T12:56:07-08:00 +draft = false +{{}} +``` + +Rendered: + +{{< code-toggle file=content/posts/my-first-post.md fm=true >}} +title = 'My first post' +date = 2023-11-09T12:56:07-08:00 +draft = false +{{< /code-toggle >}} + +### Other code examples + +Use the [code shortcode] for other code examples that require a file name: + +```text +{{}} +{{ range .Site.RegularPages }} +

{{ .LinkTitle }}

+{{ end }} +{{}} +``` + +Rendered: + +{{< code file=layouts/_default/single.html >}} +{{ range .Site.RegularPages }} +

{{ .LinkTitle }}

+{{ end }} +{{< /code >}} + +## Shortcodes + +These shortcodes are commonly used throughout the documentation. Other shortcodes are available for specialized use. + +### deprecated-in + +Use the “deprecated-in” shortcode to indicate that a feature is deprecated: + +```text +{{%/* deprecated-in 0.120.0 */%}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver +{{%/* /deprecated-in */%}} +``` + +Rendered: + +{{% deprecated-in 0.120.0 %}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver +{{% /deprecated-in %}} + +### code + +Use the "code" shortcode for other code examples that require a file name. See the [code examples] above. This shortcode takes these arguments: + +copy +: (`bool`) Whether to display a copy-to-clipboard button. Default is `false`. + +file +: (`string`) The file name to display. + +lang +: (`string`) The code language. If you do not provide a `lang` argument, the code language is determined by the file extension. If the file extension is "html", sets the code language to `go-html-template`. Default is `text`. + +### code-toggle + +Use the "code-toggle" shortcode to display examples of site configuration, front matter, or data files. See the [code examples] above. This shortcode takes these arguments: + +copy +: (`bool`) Whether to display a copy-to-clipboard button. Default is `false`. + +file +: (`string`) The file name to display. Omit the file extension for site configuration examples. + +fm +: (`bool`) Whether the example is front matter. Default is `false`. + +### new-in + +Use the "new-in" shortcode to indicate a new feature: + +```text +{{}} +``` + +Rendered: + +{{< new-in 0.120.0 >}} + +### note + +Use the "note" shortcode with `{{%/* */%}}` delimiters to call attention to important content: + +```text +{{%/* note */%}} +Use the [`math.Mod`] function to control... + +[`math.Mod`]: /functions/math/mod/ - {{%/* /code */%}} ++{{%/* /note */%}} +``` + +Rendered: + +{{% note %}} +Use the [`math.Mod`] function to control... + +[`math.Mod`]: /functions/math/mod/ - {{% /code %}} ++{{% /note %}} + +## New features + +Use the "new-in" shortcode to indicate a new feature: + +{{< code file=content/something/foo.md lang=text >}} +{{}} +{{< /code >}} + +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/layouts/shortcodes/new-in.html). + +## Deprecated features + +Use the "deprecated-in" shortcode to indicate that a feature is deprecated: + +{{< code file=content/something/foo.md >}} +{{%/* deprecated-in 0.120.0 */%}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver +{{%/* /deprecated-in */%}} +{{< /code >}} + +When deprecating a function or method, add this to front matter: + +{{< code-toggle file=content/something/foo.md fm=true >}} +expiryDate: 2024-10-30 - _build: - list: never +{{< /code-toggle >}} + - Set the `expiryDate` to one year from the date of deprecation, and add a brief front matter comment to explain the settings. - - Users will be able to search for the page, but the page will not appear in any list views, including section menus. ++Set the `expiryDate` to one year 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. +{{% /note %}} + +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. + +```sh +git checkout -b fix/typos-shortcode-templates +``` + +Step 4 +: Make changes. + +Step 5 +: Commit your changes with a descriptive commit message, typically 50 characters or less. Add the "Closes" keyword if your change addresses one or more open [issues]. + +```sh +git commit -m "Fix typos on the shortcode templates page + +Closes #1234 +Closes #5678" +``` + - Step 5 ++Step 6 +: Push the new branch to your fork of the documentation repository. + - Step 6 ++Step 7 +: Visit the [documentation repository] and create a pull request (PR). + - Step 7 ++Step 8 +: 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/0.30/#atx-headings +[Microsoft Writing Style Guide]: https://learn.microsoft.com/en-us/style-guide/welcome/ +[basic english]: https://simple.wikipedia.org/wiki/Basic_English +[code examples]: #code-examples +[code shortcode]: #code +[code-toggle shortcode]: #code-toggle +[documentation repository]: https://github.com/gohugoio/hugoDocs/ +[fenced code blocks]: https://spec.commonmark.org/0.30/#fenced-code-blocks +[glossary of terms]: /getting-started/glossary/ +[indented code blocks]: https://spec.commonmark.org/0.30/#indented-code-blocks +[issues]: https://github.com/gohugoio/hugoDocs/issues +[list items]: https://spec.commonmark.org/0.30/#list-items +[note shortcode]: #note +[project repository]: https://github.com/gohugoio/hugo +[raw HTML]: https://spec.commonmark.org/0.30/#raw-html +[setext]: https://spec.commonmark.org/0.30/#setext-heading diff --cc docs/content/en/functions/collections/Append.md index 5632dccfb,000000000..cb29dc2f2 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Append.md +++ b/docs/content/en/functions/collections/Append.md @@@ -1,102 -1,0 +1,101 @@@ +--- +title: collections.Append +description: Appends one or more elements to a slice and returns the resulting slice. +categories: [] +keywords: [] +action: + aliases: [append] + related: + - functions/collections/Merge - - functions/collections/Slice + returnType: any + signatures: + - collections.Append ELEMENT [ELEMENT...] COLLECTION + - collections.Append COLLECTION1 COLLECTION2 +aliases: [/functions/append] +--- + +This function appends all elements, excluding the last, to the last element. This allows [pipe](/getting-started/glossary/#pipeline) constructs as shown below. + +Append a single element to a slice: + +```go-html-template +{{ $s := slice "a" "b" }} +{{ $s }} → [a b] + +{{ $s = $s | append "c" }} +{{ $s }} → [a b c] +``` + +Append two elements to a slice: + +```go-html-template +{{ $s := slice "a" "b" }} +{{ $s }} → [a b] + +{{ $s = $s | append "c" "d" }} +{{ $s }} → [a b c d] +``` + +Append two elements, as a slice, to a slice. This produces the same result as the previous example: + +```go-html-template +{{ $s := slice "a" "b" }} +{{ $s }} → [a b] + +{{ $s = $s | append (slice "c" "d") }} +{{ $s }} → [a b c d] +``` + +Start with an empty slice: + +```go-html-template +{{ $s := slice }} +{{ $s }} → [] + +{{ $s = $s | append "a" }} +{{ $s }} → [a] + +{{ $s = $s | append "b" "c" }} +{{ $s }} → [a b c] + +{{ $s = $s | append (slice "d" "e") }} +{{ $s }} → [a b c d e] +``` + +If you start with a slice of a slice: + +```go-html-template +{{ $s := slice (slice "a" "b") }} +{{ $s }} → [[a b]] + +{{ $s = $s | append (slice "c" "d") }} +{{ $s }} → [[a b] [c d]] +``` + +To create a slice of slices, starting with an empty slice: + +```go-html-template +{{ $s := slice }} +{{ $s }} → [] + +{{ $s = $s | append (slice (slice "a" "b")) }} +{{ $s }} → [[a b]] + - {{ $s = $s | append (slice "c" "d") }} ++{{ $s = $s | append (slice "c" "d") }} +{{ $s }} → [[a b] [c d]] +``` + +Although the elements in the examples above are strings, you can use the `append` function with any data type, including Pages. For example, on the home page of a corporate site, to display links to the two most recent press releases followed by links to the four most recent articles: + +```go-html-template +{{ $p := where site.RegularPages "Type" "press-releases" | first 2 }} +{{ $p = $p | append (where site.RegularPages "Type" "articles" | first 4) }} + +{{ with $p }} + +{{ end }} +``` diff --cc docs/content/en/functions/collections/Apply.md index abd6fca77,000000000..9153e546a mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Apply.md +++ b/docs/content/en/functions/collections/Apply.md @@@ -1,31 -1,0 +1,26 @@@ +--- +title: collections.Apply +description: Returns a new collection with each element transformed by the given function. +categories: [] +keywords: [] +action: + aliases: [apply] ++ related: [] + returnType: '[]any' + signatures: [collections.Apply COLLECTION FUNCTION PARAM...] - relatedFunctions: - - collections.Delimit - - collections.In - - collections.Reverse - - collections.Seq - - collections.Slice +aliases: [/functions/apply] +--- + +The `apply` function takes three or more arguments, depending on the function being applied to the collection elements. + +The first argument is the collection itself, the second argument is the function name, and the remaining arguments are passed to the function, with the string `"."` representing the collection element. + +```go-html-template +{{ $s := slice "hello" "world" }} + +{{ $s = apply $s "strings.FirstUpper" "." }} +{{ $s }} → [Hello World] + +{{ $s = apply $s "strings.Replace" "." "l" "_" }} +{{ $s }} → [He__o Wor_d] +``` diff --cc docs/content/en/functions/collections/Delimit.md index 6aea467ee,000000000..b85059d4b mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Delimit.md +++ b/docs/content/en/functions/collections/Delimit.md @@@ -1,38 -1,0 +1,33 @@@ +--- +title: collections.Delimit +description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter. +categories: [] +keywords: [] +action: + aliases: [delimit] + related: - - functions/collections/Apply - - functions/collections/In - - functions/collections/Reverse - - functions/collections/Seq - - functions/collections/Slice + - functions/strings/Split + returnType: string + signatures: ['collections.Delimit COLLECTION DELIMITER [LAST]'] +aliases: [/functions/delimit] +--- + +Delimit a slice: + +```go-html-template +{{ $s := slice "b" "a" "c" }} +{{ delimit $s ", " }} → b, a, c +{{ delimit $s ", " " and "}} → b, a and c +``` + +Delimit a map: + +{{% note %}} +The `delimit` function sorts maps by key, returning the values. +{{% /note %}} + +```go-html-template +{{ $m := dict "b" 2 "a" 1 "c" 3 }} +{{ delimit $m ", " }} → 1, 2, 3 +{{ delimit $m ", " " and "}} → 1, 2 and 3 +``` diff --cc docs/content/en/functions/collections/Dictionary.md index 2e933aca9,000000000..f46b02e75 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Dictionary.md +++ b/docs/content/en/functions/collections/Dictionary.md @@@ -1,71 -1,0 +1,68 @@@ +--- +title: collections.Dictionary +description: Creates a map from a list of key and value pairs. +categories: [] +keywords: [] +action: + aliases: [dict] + related: - - functions/collections/Group - - functions/collections/IndexFunction - - functions/collections/IsSet - - functions/collections/Where ++ - functions/collections/Slice + returnType: mapany + signatures: ['collections.Dictionary KEY VALUE [VALUE...]'] +aliases: [/functions/dict] +--- + +```go-html-template +{{ $m := dict "a" 1 "b" 2 }} +``` + +The above produces this data structure: + +```json +{ + "a": 1, + "b": 2 +} +``` + + +Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deeply nested structure, e.g.: + +```go-html-template +{{ $m := dict (slice "a" "b" "c") "value" }} +``` + +The above produces this data structure: + +```json +{ + "a": { + "b": { + "c": "value" + } + } +} +``` + +## Pass values to a partial template + +The partial below creates an SVG and expects `fill`, `height` and `width` from the caller: + +### Partial definition + +{{< code file=layouts/partials/svgs/external-links.svg >}} + + + +{{< /code >}} + +### Partial call + +The `fill`, `height` and `width` values can be stored in one object with `dict` and passed to the partial: + +{{< code file=layouts/_default/list.html >}} +{{ partial "svgs/external-links.svg" (dict "fill" "#01589B" "width" 10 "height" 20 ) }} +{{< /code >}} + +[partials]: /templates/partials/ diff --cc docs/content/en/functions/collections/First.md index 49a0362f5,000000000..cb2397af1 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/First.md +++ b/docs/content/en/functions/collections/First.md @@@ -1,36 -1,0 +1,37 @@@ +--- +title: collections.First +description: Returns the given collection, limited to the first N elements. +categories: [] +keywords: [] +action: + aliases: [first] + related: + - functions/collections/After + - functions/collections/Last ++ - methods/pages/Limit + returnType: any + signatures: [collections.First N COLLECTION] +aliases: [/functions/first] +--- + +```go-html-template +{{ range first 5 .Pages }} + {{ .Render "summary" }} +{{ end }} +``` + +Set `N` to zero to return an empty collection. + +```go-html-template +{{ $emptyPageCollection := first 0 .Pages}} +``` + +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/Group.md index 74aa869df,000000000..2f5a333c0 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Group.md +++ b/docs/content/en/functions/collections/Group.md @@@ -1,35 -1,0 +1,31 @@@ +--- +title: collections.Group +description: Groups the given page collection by the given key. +categories: [] +keywords: [] +action: + aliases: [group] - related: - - functions/collections/Dictionary - - functions/collections/IndexFunction - - functions/collections/IsSet - - functions/collections/Where ++ related: [] + returnType: any + signatures: [collections.Group KEY PAGES] +aliases: [/functions/group] +--- + +```go-html-template +{{ $new := .Site.RegularPages | first 10 | group "New" }} +{{ $old := .Site.RegularPages | last 10 | group "Old" }} +{{ $groups := slice $new $old }} +{{ range $groups }} +

{{ .Key }}{{/* Prints "New", "Old" */}}

+
    + {{ range .Pages }} +
  • + {{ .LinkTitle }} +
    {{ .Date.Format "Mon, Jan 2, 2006" }}
    +
  • + {{ end }} +
+{{ end }} +``` + +The page group you get from `group` is of the same type you get from the built-in [group methods](/templates/lists#group-content) in Hugo. The above example can be [paginated](/templates/pagination/#list-paginator-pages). diff --cc docs/content/en/functions/collections/In.md index a3ec83d9b,000000000..131c0abcf mode 100644,000000..100644 --- a/docs/content/en/functions/collections/In.md +++ b/docs/content/en/functions/collections/In.md @@@ -1,44 -1,0 +1,43 @@@ +--- +title: collections.In +description: Reports whether the given value is a member of the given set. +categories: [] +keywords: [] +action: + aliases: [in] + related: - - functions/collections/Slice + - functions/strings/Contains + - functions/strings/ContainsAny + - functions/strings/ContainsNonSpace + - functions/strings/HasPrefix + - functions/strings/HasSuffix + returnType: bool + signatures: [collections.In SET VALUE] +aliases: [/functions/in] +--- + +The `SET` can be an [array], [slice], or [string]. + +[array]: /getting-started/glossary/#array +[slice]: /getting-started/glossary/#slice +[string]: /getting-started/glossary/#string + +```go-html-template +{{ $s := slice "a" "b" "c" }} +{{ in $s "b" }} → true +``` + +```go-html-template +{{ $s := slice 1 2 3 }} +{{ in $s 2 }} → true +``` + +```go-html-template +{{ $s := slice 1.11 2.22 3.33 }} +{{ in $s 2.22 }} → true +``` + +```go-html-template +{{ $s := "abc" }} +{{ in $s "b" }} → true +``` diff --cc docs/content/en/functions/collections/IndexFunction.md index e595d2b41,000000000..6482884fd mode 100644,000000..100644 --- a/docs/content/en/functions/collections/IndexFunction.md +++ b/docs/content/en/functions/collections/IndexFunction.md @@@ -1,99 -1,0 +1,95 @@@ +--- +title: collections.Index +description: Looks up the index(es) or key(s) of the data structure passed into it. +categories: [] +keywords: [] +action: + aliases: [index] - related: - - functions/collections/Dictionary - - functions/collections/Group - - functions/collections/IsSet - - functions/collections/Where ++ related: [] + returnType: any + signatures: + - collections.Index COLLECTION INDEXES + - collections.Index COLLECTION KEYS +aliases: [/functions/index,/functions/index-function] +--- + +The `index` functions returns the result of indexing its first argument by the following arguments. Each indexed item must be a map or a slice, e.g.: + +```go-html-template +{{ $slice := slice "a" "b" "c" }} +{{ index $slice 0 }} → a +{{ index $slice 1 }} → b + +{{ $map := dict "a" 100 "b" 200 }} +{{ index $map "b" }} → 200 +``` + +The function takes multiple indices as arguments, and this can be used to get nested values, e.g.: + +```go-html-template +{{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }} +{{ index $map "c" 1 }} → 20 +{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }} +{{ index $map "c" "e" }} → 20 +``` + +You may write multiple indices as a slice: + +```go-html-template +{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }} +{{ $slice := slice "c" "e" }} +{{ index $map $slice }} → 20 +``` + +## Example: load data from a path based on front matter parameters + +Assume you want to add a `location = ""` field to your front matter for every article written in `content/vacations/`. You want to use this field to populate information about the location at the bottom of the article in your `single.html` template. You also have a directory in `data/locations/` that looks like the following: + +```text +data/ + └── locations/ + ├── abilene.toml + ├── chicago.toml + ├── oslo.toml + └── provo.toml +``` + +Here is an example: + +{{< code-toggle file=data/locations/oslo >}} +website = "https://www.oslo.kommune.no" +pop_city = 658390 +pop_metro = 1717900 +{{< /code-toggle >}} + +The example we will use will be an article on Oslo, whose front matter should be set to exactly the same name as the corresponding file name in `data/locations/`: + +{{< code-toggle file=content/articles/oslo.md fm=true >}} +title = "My Norwegian Vacation" +location = "oslo" +{{< /code-toggle >}} + +The content of `oslo.toml` can be accessed from your template using the following node path: `.Site.Data.locations.oslo`. However, the specific file you need is going to change according to the front matter. + +This is where the `index` function is needed. `index` takes 2 arguments in this use case: + +1. The node path +2. A string corresponding to the desired data; e.g.— + +```go-html-template +{{ index .Site.Data.locations "oslo" }} +``` + +The variable for `.Params.location` is a string and can therefore replace `oslo` in the example above: + +```go-html-template +{{ index .Site.Data.locations .Params.location }} +=> map[website:https://www.oslo.kommune.no pop_city:658390 pop_metro:1717900] +``` + +Now the call will return the specific file according to the location specified in the content's front matter, but you will likely want to write specific properties to the template. You can do this by continuing down the node path via dot notation (`.`): + +```go-html-template +{{ (index .Site.Data.locations .Params.location).pop_city }} +=> 658390 +``` diff --cc docs/content/en/functions/collections/IsSet.md index 76b336ae3,000000000..62b81b712 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/IsSet.md +++ b/docs/content/en/functions/collections/IsSet.md @@@ -1,49 -1,0 +1,45 @@@ +--- +title: collections.IsSet +description: Reports whether the key exists within the collection. +categories: [] +keywords: [] +action: + aliases: [isset] + related: - - functions/collections/Dictionary - - functions/collections/Group - - functions/collections/IndexFunction - - functions/collections/Where + - functions/go-template/if + - functions/go-template/with + 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`: + +```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. +{{% /note %}} diff --cc docs/content/en/functions/collections/NewScratch.md index 793b2b4b5,000000000..96f85a8d0 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/NewScratch.md +++ b/docs/content/en/functions/collections/NewScratch.md @@@ -1,115 -1,0 +1,124 @@@ +--- +title: collections.NewScratch +description: Returns a locally scoped "scratch pad" to store and manipulate data. +categories: [] +keywords: [] +action: + aliases: [newScratch] + related: + - methods/page/scratch + - methods/page/store ++ - methods/shortcode/scratch + returnType: maps.Scratch + signatures: [collections.NewScratch ] +--- + +The `collections.NewScratch` function creates a locally scoped [scratch pad] to store and manipulate data. To create a scratch pad that is attached to a `Page` object, use the [`Scratch`] or [`Store`] method. + +[`Scratch`]: /methods/page/scratch +[`Store`]: /methods/page/store +[scratch pad]: /getting-started/glossary/#scratch-pad + +## Methods + - Set - : Sets the value of a given key. ++###### Set ++ ++Sets the value of a given key. + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "greeting" "Hello" }} +``` + - Get - : Gets the value of a given key. ++###### Get ++ ++Gets the value of a given key. + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "greeting" "Hello" }} +{{ $s.Get "greeting" }} → Hello +``` + - Add - : Adds a given value to existing value(s) of the given key. ++###### Add + - : For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. ++Adds a given value to existing value(s) of the given key. ++ ++For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "greeting" "Hello" }} +{{ $s.Add "greeting" "Welcome" }} +{{ $s.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "total" 3 }} +{{ $s.Add "total" 7 }} +{{ $s.Get "total" }} → 10 +``` + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "greetings" (slice "Hello") }} +{{ $s.Add "greetings" (slice "Welcome" "Cheers") }} +{{ $s.Get "greetings" }} → [Hello Welcome Cheers] +``` + - SetInMap - : Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. ++###### SetInMap ++ ++Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. + +```go-html-template +{{ $s := newScratch }} +{{ $s.SetInMap "greetings" "english" "Hello" }} +{{ $s.SetInMap "greetings" "french" "Bonjour" }} +{{ $s.Get "greetings" }} → map[english:Hello french:Bonjour] +``` + - DeleteInMap - : Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. ++###### DeleteInMap ++ ++Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. + +```go-html-template +{{ $s := newScratch }} +{{ $s.SetInMap "greetings" "english" "Hello" }} +{{ $s.SetInMap "greetings" "french" "Bonjour" }} +{{ $s.DeleteInMap "greetings" "english" }} +{{ $s.Get "greetings" }} → map[french:Bonjour] +``` + - GetSortedMapValues - : Returns an array of values from `key` sorted by `mapKey`. ++###### GetSortedMapValues ++ ++Returns an array of values from `key` sorted by `mapKey`. + +```go-html-template +{{ $s := newScratch }} +{{ $s.SetInMap "greetings" "english" "Hello" }} +{{ $s.SetInMap "greetings" "french" "Bonjour" }} +{{ $s.GetSortedMapValues "greetings" }} → [Hello Bonjour] +``` + - Delete - : Removes the given key. ++###### Delete ++ ++Removes the given key. + +```go-html-template +{{ $s := newScratch }} +{{ $s.Set "greeting" "Hello" }} +{{ $s.Delete "greeting" }} +``` + - Values - : Returns the raw backing map. Do not use with `Scratch` or `Store` methods on a `Page` object due to concurrency issues. ++###### Values ++ ++Returns the raw backing map. Do not use with `Scratch` or `Store` methods on a `Page` object due to concurrency issues. + +```go-html-template +{{ $s := newScratch }} +{{ $s.SetInMap "greetings" "english" "Hello" }} +{{ $s.SetInMap "greetings" "french" "Bonjour" }} + +{{ $map := $s.Values }} +``` diff --cc docs/content/en/functions/collections/Querify.md index e195c417f,000000000..ea0434fc5 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Querify.md +++ b/docs/content/en/functions/collections/Querify.md @@@ -1,33 -1,0 +1,32 @@@ +--- +title: collections.Querify +description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs. +categories: [] +keywords: [] +action: + aliases: [querify] ++ related: ++ - functions/go-template/urlquery.md + returnType: string + signatures: + - collections.Querify VALUE [VALUE...] + - collections.Querify COLLECTION - related: - - collections.Querify - - urlquery +aliases: [/functions/querify] +--- + +`querify` takes a set or slice of key-value pairs and returns a [query string](https://en.wikipedia.org/wiki/Query_string) that can be appended to a URL. + +The following examples create a link to a search results page on Google. + +```go-html-template +Search + +{{ $qs := slice "q" "test" "page" 3 }} +Search +``` + +Both of these examples render the following HTML: + +```html +Search +``` diff --cc docs/content/en/functions/collections/Reverse.md index 12c964c76,000000000..d0a449763 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Reverse.md +++ b/docs/content/en/functions/collections/Reverse.md @@@ -1,22 -1,0 +1,19 @@@ +--- +title: collections.Reverse +description: Reverses the order of a collection. +categories: [] +keywords: [] +action: + aliases: [] ++ related: ++ - functions/collections/Sort ++ - functions/collections/Shuffle ++ - functions/collections/Uniq + returnType: any + signatures: [collections.Reverse COLLECTION] - related: - - collections.Apply - - collections.Delimit - - collections.In - - collections.Reverse - - collections.Seq - - collections.Slice +aliases: [/functions/collections.reverse] +--- + +```go-html-template +{{ slice 2 1 3 | collections.Reverse }} → [3 1 2] +``` diff --cc docs/content/en/functions/collections/Seq.md index e7430e0d0,000000000..b572bd7c0 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Seq.md +++ b/docs/content/en/functions/collections/Seq.md @@@ -1,46 -1,0 +1,36 @@@ +--- +title: collections.Seq +description: Returns a slice of integers. +categories: [] +keywords: [] +action: + aliases: [seq] ++ related: [] + returnType: '[]int' + signatures: + - collections.Seq LAST + - collections.Seq FIRST LAST + - collections.Seq FIRST INCREMENT LAST - related: - - collections.Apply - - collections.Delimit - - collections.In - - collections.Reverse - - collections.Seq - - collections.Slice +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] +``` + - Iterate over a sequence of integers: ++A contrived example of iterating over a sequence of integers: + +```go-html-template +{{ $product := 1 }} +{{ range seq 4 }} + {{ $product = mul $product . }} +{{ end }} +{{ $product }} → 24 +``` + - The example above is contrived. To calculate the product of 2 or more numbers, use the [`math.Product`] function: - - ```go-html-template - {{ math.Product (seq 4) }} → 24 - ``` - - [`math.Product`]: /functions/math/product ++{{% note %}} ++The slice created by the `seq` function is limited to 2000 elements. ++{{% /note %}} diff --cc docs/content/en/functions/collections/Shuffle.md index 18b8cc664,000000000..0f28eb4d8 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Shuffle.md +++ b/docs/content/en/functions/collections/Shuffle.md @@@ -1,23 -1,0 +1,22 @@@ +--- +title: collections.Shuffle +description: Returns a random permutation of a given array or slice. +categories: [] +keywords: [] +action: + aliases: [shuffle] ++ related: ++ - functions/collections/Reverse ++ - functions/collections/Sort ++ - functions/collections/Uniq + returnType: any + signatures: [collections.Shuffle COLLECTION] - related: - - collections.Reverse - - collections.Shuffle - - collections.Sort - - collections.Uniq +aliases: [/functions/shuffle] +--- + +```go-html-template +{{ shuffle (seq 1 2 3) }} → [3 1 2] +{{ shuffle (slice "a" "b" "c") }} → [b a c] +``` + +The result will vary from one build to the next. diff --cc docs/content/en/functions/collections/Slice.md index e24b394ca,000000000..56c068d4b mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Slice.md +++ b/docs/content/en/functions/collections/Slice.md @@@ -1,24 -1,0 +1,18 @@@ +--- +title: collections.Slice +description: Creates a slice of all passed arguments. +categories: [] +keywords: [] +action: + aliases: [slice] ++ related: ++ - functions/collections/Dictionary + returnType: any + signatures: [collections.Slice ITEM...] - related: - - collections.Append - - collections.Apply - - collections.Delimit - - collections.In - - collections.Reverse - - collections.Seq - - collections.Slice +aliases: [/functions/slice] +--- + +```go-html-template +{{ $s := slice "a" "b" "c" }} +{{ $s }} → [a b c] +``` diff --cc docs/content/en/functions/collections/Sort.md index 6b9ea2c34,000000000..2277f883c mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Sort.md +++ b/docs/content/en/functions/collections/Sort.md @@@ -1,122 -1,0 +1,156 @@@ +--- +title: collections.Sort +description: Sorts slices, maps, and page collections. +categories: [] +keywords: [] +action: + aliases: [sort] ++ related: ++ - functions/collections/Reverse ++ - functions/collections/Shuffle ++ - functions/collections/Uniq + returnType: any + signatures: ['collections.Sort COLLECTION [KEY] [ORDER]'] - related: - - collections.Reverse - - collections.Shuffle - - collections.Sort - - collections.Uniq ++toc: true +aliases: [/functions/sort] +--- + +The `KEY` is optional when sorting slices in ascending order, otherwise it is required. When sorting slices, use the literal `value` in place of the `KEY`. See examples below. + +The `ORDER` may be either `asc` (ascending) or `desc` (descending). The default sort order is ascending. + +## Sort a slice + +The examples below assume this site configuration: + +{{< code-toggle file=hugo >}} +[params] +grades = ['b','a','c'] +{{< /code-toggle >}} + +### Ascending order {#slice-ascending-order} + +Sort slice elements in ascending order using either of these constructs: + +```go-html-template +{{ sort site.Params.grades }} → [a b c] +{{ sort site.Params.grades "value" "asc" }} → [a b c] +``` + +In the examples above, `value` is the `KEY` representing the value of the slice element. + +### Descending order {#slice-descending-order} + +Sort slice elements in descending order: + +```go-html-template +{{ sort site.Params.grades "value" "desc" }} → [c b a] +``` + +In the example above, `value` is the `KEY` representing the value of the slice element. + +## Sort a map + +The examples below assume this site configuration: + +{{< code-toggle file=hugo >}} +[params.authors.a] +firstName = "Marius" +lastName = "Pontmercy" +[params.authors.b] +firstName = "Victor" +lastName = "Hugo" +[params.authors.c] +firstName = "Jean" +lastName = "Valjean" +{{< /code-toggle >}} + +{{% note %}} +When sorting maps, the `KEY` argument must be lowercase. +{{% /note %}} + +### Ascending order {#map-ascending-order} + +Sort map objects in ascending order using either of these constructs: + +```go-html-template +{{ range sort site.Params.authors "firstname" }} + {{ .firstName }} +{{ end }} + +{{ range sort site.Params.authors "firstname" "asc" }} + {{ .firstName }} +{{ end }} +``` + +These produce: + +```text +Jean Marius Victor +``` + +### Descending order {#map-descending-order} + +Sort map objects in descending order: + +```go-html-template +{{ range sort site.Params.authors "firstname" "desc" }} + {{ .firstName }} +{{ end }} +``` + +This produces: + +```text +Victor Marius Jean +``` + ++### First level key removal ++ ++Hugo removes the first level keys when sorting a map. ++ ++Original map: ++ ++```json ++{ ++ "felix": { ++ "breed": "malicious", ++ "type": "cat" ++ }, ++ "spot": { ++ "breed": "boxer", ++ "type": "dog" ++ } ++} ++``` ++ ++After sorting: ++ ++```json ++[ ++ { ++ "breed": "malicious", ++ "type": "cat" ++ }, ++ { ++ "breed": "boxer", ++ "type": "dog" ++ } ++] ++``` ++ +## Sort a page collection + +{{% note %}} +Although you can use the `sort` function to sort a page collection, Hugo provides [sorting and grouping methods] as well. + +[sorting and grouping methods]: /methods/pages +{{% /note %}} + +In this contrived example, sort the site's regular pages by `.Type` in descending order: + +```go-html-template +{{ range sort site.RegularPages "Type" "desc" }} +

{{ .LinkTitle }}

+{{ end }} +``` diff --cc docs/content/en/functions/collections/SymDiff.md index 828c10ce5,000000000..7eba3ef42 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/SymDiff.md +++ b/docs/content/en/functions/collections/SymDiff.md @@@ -1,24 -1,0 +1,24 @@@ +--- +title: collections.SymDiff +description: Returns the symmetric difference of two collections. +categories: [] +keywords: [] +action: + aliases: [symdiff] ++ related: ++ - functions/collections/Complement ++ - functions/collections/Intersect ++ - functions/collections/SymDiff ++ - functions/collections/Union + returnType: any + signatures: [COLLECTION | collections.SymDiff COLLECTION] - related: - - collections.Complement - - collections.Intersect - - collections.SymDiff - - collections.Union +aliases: [/functions/symdiff] +--- + +Example: + +```go-html-template +{{ slice 1 2 3 | symdiff (slice 3 4) }} → [1 2 4] +``` + +Also see . diff --cc docs/content/en/functions/collections/Union.md index e2eb61313,000000000..7fed49a10 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Union.md +++ b/docs/content/en/functions/collections/Union.md @@@ -1,46 -1,0 +1,46 @@@ +--- +title: collections.Union +description: Given two arrays or slices, returns a new array that contains the elements that belong to either or both arrays/slices. +categories: [] +keywords: [] +action: + aliases: [union] ++ related: ++ - functions/collections/Complement ++ - functions/collections/Intersect ++ - functions/collections/SymDiff ++ - functions/collections/Union + returnType: any + signatures: [collections.Union SET1 SET2] - related: - - collections.Complement - - collections.Intersect - - collections.SymDiff - - collections.Union +aliases: [/functions/union] +--- + +Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both. + +```go-html-template +{{ union (slice 1 2 3) (slice 3 4 5) }} + + +{{ union (slice 1 2 3) nil }} + + +{{ union nil (slice 1 2 3) }} + + +{{ union nil nil }} + +``` + +## OR filter in where query + +This is also very useful to use as `OR` filters when combined with where: + +```go-html-template +{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }} +{{ $pages = $pages | union (where .Site.RegularPages "Params.pinned" true) }} +{{ $pages = $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }} +``` + +The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page parameters. + +See [intersect](/functions/collections/intersect) for `AND`. diff --cc docs/content/en/functions/collections/Uniq.md index 8266142ac,000000000..02b590c18 mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Uniq.md +++ b/docs/content/en/functions/collections/Uniq.md @@@ -1,20 -1,0 +1,20 @@@ +--- +title: collections.Uniq +description: Returns the given collection, removing duplicate elements. +categories: [] +keywords: [] +action: + aliases: [uniq] ++ related: ++ - functions/collections/Reverse ++ - functions/collections/Shuffle ++ - functions/collections/Sort ++ - functions/collections/Uniq + returnType: any + signatures: [collections.Uniq COLLECTION] - related: - - collections.Reverse - - collections.Shuffle - - collections.Sort - - collections.Uniq +aliases: [/functions/uniq] +--- + +```go-html-template +{{ slice 1 3 2 1 | uniq }} → [1 3 2] +``` diff --cc docs/content/en/functions/collections/Where.md index e053ed3d5,000000000..ca900d85e mode 100644,000000..100644 --- a/docs/content/en/functions/collections/Where.md +++ b/docs/content/en/functions/collections/Where.md @@@ -1,450 -1,0 +1,446 @@@ +--- +title: collections.Where +description: Returns the given collection, removing elements that do not satisfy the comparison condition. +categories: [] +keywords: [] +action: + aliases: [where] ++ related: [] + returnType: any + signatures: ['collections.Where COLLECTION KEY [OPERATOR] VALUE'] - related: - - collections.Dictionary - - collections.Group - - collections.Index - - collections.IsSet - - collections.Where - aliases: [/functions/where] +toc: true ++aliases: [/functions/where] +--- + +The `where` function returns the given collection, removing elements that do not satisfy the comparison condition. The comparison condition is comprised of the `KEY`, `OPERATOR`, and `VALUE` arguments: + +```text +collections.Where COLLECTION KEY [OPERATOR] VALUE + -------------------- + comparison condition +``` + +Hugo will test for equality if you do not provide an `OPERATOR` argument. For example: + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "books" }} +{{ $books := where .Site.Data.books "genres" "suspense" }} +``` + +## Arguments + +The where function takes three or four arguments. The `OPERATOR` argument is optional. + +COLLECTION - : (`any`) Typically a page collection or a [slice] of [maps]. ++: (`any`) A [page collection] or a [slice] of [maps]. + +[maps]: /getting-started/glossary/#map ++[page collection]: /getting-started/glossary/#page-collection +[slice]: /getting-started/glossary/#slice + +KEY +: (`string`) The key of the page or map value to compare with `VALUE`. With page collections, commonly used comparison keys are `Section`, `Type`, and `Params`. To compare with a member of the page `Params` map, [chain] the subkey as shown below: + +```go-html-template +{{ $result := where .Site.RegularPages "Params.foo" "bar" }} +``` + +[chain]: /getting-started/glossary/#chain - ++Typically a +OPERATOR +: (`string`) The logical comparison [operator](#operators). + +VALUE +: (`any`) The value with which to compare. The values to compare must have comparable data types. For example: + +Comparison|Result +:--|:-- +`"123" "eq" "123"`|`true` +`"123" "eq" 123`|`false` +`false "eq" "false"`|`false` +`false "eq" false`|`true` + - When one or both of the values to compare is a slice, use the `in`, `not in` or `intersect` operators as described below. ++When one or both of the values to compare is a slice, use the `in`, `not in`, or `intersect` operators as described below. + +## Operators + +Use any of the following logical operators: + +`=`, `==`, `eq` +: (`bool`) Reports whether the given field value is equal to `VALUE`. + +`!=`, `<>`, `ne` +: (`bool`) Reports whether the given field value is not equal to `VALUE`. + +`>=`, `ge` +: (`bool`) Reports whether the given field value is greater than or equal to `VALUE`. + +`>`, `gt` +: `true` Reports whether the given field value is greater than `VALUE`. + +`<=`, `le` +: (`bool`) Reports whether the given field value is less than or equal to `VALUE`. + +`<`, `lt` +: (`bool`) Reports whether the given field value is less than `VALUE`. + +`in` +: (`bool`) Reports whether the given field value is a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in). + +`not in` +: (`bool`) Reports whether the given field value is not a member of `VALUE`. Compare string to slice, or string to string. See [details](/functions/collections/in). + +`intersect` +: (`bool`) Reports whether the given field value (a slice) contains one or more elements in common with `VALUE`. See [details](/functions/collections/intersect). + +`like` {{< new-in 0.116.0 >}} +: (`bool`) Reports whether the given field value matches the regular expression specified in `VALUE`. Use the `like` operator to compare `string` values. The `like` operator returns `false` when comparing other data types to the regular expression. + +{{% note %}} +The examples below perform comparisons within a page collection, but the same comparisons are applicable to a slice of maps. +{{% /note %}} + +## String comparison + +Compare the value of the given field to a [`string`]: + +[`string`]: /getting-started/glossary/#string + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "eq" "books" }} +{{ $pages := where .Site.RegularPages "Section" "ne" "books" }} +``` + +## Numeric comparison + +Compare the value of the given field to an [`int`] or [`float`]: + +[`int`]: /getting-started/glossary/#int +[`float`]: /getting-started/glossary/#float + +```go-html-template - {{ $sectionPages := where site.RegularPages "Section" "eq" "books" }} - - {{ $pages := where $sectionPages "Params.price" "eq" 42 }} - {{ $pages := where $sectionPages "Params.price" "ne" 42.67 }} - {{ $pages := where $sectionPages "Params.price" "ge" 42 }} - {{ $pages := where $sectionPages "Params.price" "gt" 42.67 }} - {{ $pages := where $sectionPages "Params.price" "le" 42 }} - {{ $pages := where $sectionPages "Params.price" "lt" 42.67 }} ++{{ $books := where site.RegularPages "Section" "eq" "books" }} ++ ++{{ $pages := where $books "Params.price" "eq" 42 }} ++{{ $pages := where $books "Params.price" "ne" 42.67 }} ++{{ $pages := where $books "Params.price" "ge" 42 }} ++{{ $pages := where $books "Params.price" "gt" 42.67 }} ++{{ $pages := where $books "Params.price" "le" 42 }} ++{{ $pages := where $books "Params.price" "lt" 42.67 }} +``` + +## Boolean comparison + +Compare the value of the given field to a [`bool`]: + +[`bool`]: /getting-started/glossary/#bool + +```go-html-template - {{ $sectionPages := where site.RegularPages "Section" "eq" "books" }} ++{{ $books := where site.RegularPages "Section" "eq" "books" }} + - {{ $pages := where $sectionPages "Params.fiction" "eq" true }} - {{ $pages := where $sectionPages "Params.fiction" "eq" false }} - {{ $pages := where $sectionPages "Params.fiction" "ne" true }} - {{ $pages := where $sectionPages "Params.fiction" "ne" false }} ++{{ $pages := where $books "Params.fiction" "eq" true }} ++{{ $pages := where $books "Params.fiction" "eq" false }} ++{{ $pages := where $books "Params.fiction" "ne" true }} ++{{ $pages := where $books "Params.fiction" "ne" false }} +``` + +## Member comparison + +Compare a [`scalar`] to a [`slice`]. + +[`scalar`]: /getting-started/glossary/#scalar +[`slice`]: /getting-started/glossary/#slice + +For example, to return a collection of pages where the `color` page parameter is either "red" or "yellow": + +```go-html-template - {{ $sectionPages := where site.RegularPages "Section" "eq" "fruit" }} ++{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }} + +{{ $colors := slice "red" "yellow" }} - {{ $pages := where $sectionPages "Params.color" "in" $colors }} ++{{ $pages := where $fruit "Params.color" "in" $colors }} +``` + +To return a collection of pages where the "color" page parameter is neither "red" nor "yellow": + +```go-html-template - {{ $sectionPages := where site.RegularPages "Section" "eq" "fruit" }} ++{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }} + +{{ $colors := slice "red" "yellow" }} - {{ $pages := where $sectionPages "Params.color" "not in" $colors }} ++{{ $pages := where $fruit "Params.color" "not in" $colors }} +``` + +## Intersection comparison + +Compare a [`slice`] to a [`slice`], returning collection elements with common values. This is frequently used when comparing taxonomy terms. + +For example, to return a collection of pages where any of the terms in the "genres" taxonomy are "suspense" or "romance": + +```go-html-template - {{ $sectionPages := where site.RegularPages "Section" "eq" "books" }} ++{{ $books := where site.RegularPages "Section" "eq" "books" }} + +{{ $genres := slice "suspense" "romance" }} - {{ $pages := where $sectionPages "Params.genres" "intersect" $genres }} ++{{ $pages := where $books "Params.genres" "intersect" $genres }} +``` + +## Regular expression comparison + +{{< new-in 0.116.0 >}} + +To return a collection of pages where the "author" page parameter begins with either "victor" or "Victor": + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.author" "like" `(?i)^victor` }} +``` + +{{% include "functions/_common/regular-expressions.md" %}} + +{{% note %}} +Use the `like` operator to compare string values. Comparing other data types will result in an empty collection. +{{% /note %}} + +## Date comparison + +### Predefined dates + +There are four predefined front matter dates: [`date`], [`publishDate`], [`lastmod`], and [`expiryDate`]. Regardless of the front matter data format (TOML, YAML, or JSON) these are [`time.Time`] values, allowing precise comparisons. + +[`date`]: /methods/page/date +[`publishdate`]: /methods/page/publishdate +[`lastmod`]: /methods/page/lastmod +[`expirydate`]: /methods/page/expirydate +[`time.Time`]: https://pkg.go.dev/time#Time + +For example, to return a collection of pages that were created before the current year: + +```go-html-template +{{ $startOfYear := time.AsTime (printf "%d-01-01" now.Year) }} +{{ $pages := where .Site.RegularPages "Date" "lt" $startOfYear }} +``` + +### Custom dates + +With custom front matter dates, the comparison depends on the front matter data format (TOML, YAML, or JSON). + +{{% note %}} +Using TOML for pages with custom front matter dates enables precise date comparisons. +{{% /note %}} + +With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. If you quote a TOML date, it is a string. If you do not quote a TOML date value, it is [`time.Time`] value, enabling precise comparisons. + +In the TOML example below, note that the event date is not quoted. + +{{< code file="content/events/2024-user-conference.md" >}} ++++ +title = '2024 User Conference" +eventDate = 2024-04-01 ++++ +{{< /code >}} + +To return a collection of future events: + +```go-html-template +{{ $events := where .Site.RegularPages "Type" "events" }} +{{ $futureEvents := where $events "Params.eventDate" "gt" now }} +``` + +When working with YAML or JSON, or quoted TOML values, custom dates are strings; you cannot compare them with `time.Time` values. String comparisons may be possible if the custom date layout is consistent from one page to the next. However, to be safe, filter the pages by ranging through the collection: + +```go-html-template +{{ $events := where .Site.RegularPages "Type" "events" }} +{{ $futureEvents := slice }} +{{ range $events }} + {{ if gt (time.AsTime .Params.eventDate) now }} + {{ $futureEvents = $futureEvents | append . }} + {{ end }} +{{ end }} +``` + +## Nil comparison + +To return a collection of pages where the "color" parameter is present in front matter, compare to `nil`: + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }} +``` + +To return a collection of pages where the "color" parameter is not present in front matter, compare to `nil`: + +```go-html-template +{{ $pages := where .Site.RegularPages "Params.color" "eq" nil }} +``` + +In both examples above, note that `nil` is not quoted. + +## Nested comparison + +These are equivalent: + +```go-html-template +{{ $pages := where .Site.RegularPages "Type" "tutorials" }} +{{ $pages = where $pages "Params.level" "eq" "beginner" }} +``` + +```go-html-template +{{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }} +``` + +## Portable section comparison + +Useful for theme authors, avoid hardcoding section names by using the `where` function with the [`MainSections`] method on a `Site` object. + +[`MainSections`]: /methods/site/mainsections + +```go-html-template +{{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }} +``` + +With this construct, a theme author can instruct users to specify their main sections in the site configuration: + +{{< code-toggle file=hugo >}} +[params] +mainSections = ['blog','galleries'] +{{< /code-toggle >}} + +If `params.mainSections` is not defined in the site configuration, the `MainSections` method returns a slice with one element---the top level section with the most pages. + +## Boolean/undefined comparison + +Consider this site content: + +```text +content/ +├── posts/ +│ ├── _index.md +│ ├── post-1.md <-- front matter: exclude = false +│ ├── post-2.md <-- front matter: exclude = true +│ └── post-3.md <-- front matter: exclude not defined +└── _index.md +``` + +The first two pages have an "exclude" field in front matter, but the last page does not. When testing for _equality_, the third page is _excluded_ from the result. When testing for _inequality_, the third page is _included_ in the result. + +### Equality test + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "eq" false }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "eq" true }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +### Inequality test + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "ne" false }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +
    + {{ range where .Site.RegularPages "Params.exclude" "ne" true }} +
  • {{ .LinkTitle }}
  • + {{ end }} +
+``` + +Is rendered to: + +```html + +``` + +To exclude a page with an undefined field from a boolean _inequality_ test: + +1. Create a collection using a boolean comparison +2. Create a collection using a nil comparison +3. Subtract the second collection from the first collection using the [`collections.Complement`] function. + +[`collections.Complement`]: /functions/collections/complement + +This template: + +```go-html-template +{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" true }} +{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }} + +``` + +Is rendered to: + +```html + +``` + +This template: + +```go-html-template +{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" false }} +{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }} + +``` + +Is rendered to: + +```html + +``` diff --cc docs/content/en/functions/crypto/FNV32a.md index 5c091ebee,000000000..eda303e62 mode 100644,000000..100644 --- a/docs/content/en/functions/crypto/FNV32a.md +++ b/docs/content/en/functions/crypto/FNV32a.md @@@ -1,22 -1,0 +1,22 @@@ +--- +title: crypto.FNV32a - description: Returns the FNV (Fowler–Noll–Vo) 32 bit hash of a given string. ++description: Returns the FNV (Fowler–Noll–Vo) 32-bit hash of a given string. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/crypto/HMAC + - functions/crypto/MD5 + - functions/crypto/SHA1 + - functions/crypto/SHA256 + returnType: int + signatures: [crypto.FNV32a STRING] +aliases: [/functions/crypto.fnv32a] +--- + - This function calculates the 32 bit [FNV1a hash](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash) of a given string according to the [specification](https://datatracker.ietf.org/doc/html/draft-eastlake-fnv-12): ++This function calculates the 32-bit [FNV1a hash](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash) of a given string according to the [specification](https://datatracker.ietf.org/doc/html/draft-eastlake-fnv-12): + +```go-html-template +{{ crypto.FNV32a "Hello world" }} → 1498229191 +``` diff --cc docs/content/en/functions/data/GetJSON.md index 96812e7c0,000000000..4db3c8988 mode 100644,000000..100644 --- a/docs/content/en/functions/data/GetJSON.md +++ b/docs/content/en/functions/data/GetJSON.md @@@ -1,145 -1,0 +1,142 @@@ +--- +title: data.GetJSON +description: Returns a JSON object from a local or remote JSON file, or an error if the file does not exist. +categories: [] +keywords: [] +action: + aliases: [getJSON] + related: + - functions/data/GetCSV + - functions/resources/Get + - functions/resources/GetRemote + - methods/page/Resources + returnType: any + signatures: ['data.GetJSON INPUT... [OPTIONS]'] +toc: true +--- + +Given the following directory structure: + +```text +my-project/ +└── other-files/ + └── books.json +``` + +Access the data with either of the following: + +```go-html-template +{{ $data := getJSON "other-files/books.json" }} +{{ $data := getJSON "other-files/" "books.json" }} +``` + +{{% note %}} +When working with local data, the filepath is relative to the working directory. +{{% /note %}} + +Access remote data with either of the following: + +```go-html-template +{{ $data := getJSON "https://example.org/books.json" }} +{{ $data := getJSON "https://example.org/" "books.json" }} +``` + +The resulting data structure is a JSON object: + +```json +[ + { + "author": "Victor Hugo", + "rating": 5, + "title": "Les Misérables" + }, + { + "author": "Victor Hugo", + "rating": 4, + "title": "The Hunchback of Notre Dame" + } +] +``` + +## Options + +Add headers to the request by providing an options map: + +```go-html-template +{{ $opts := dict "Authorization" "Bearer abcd" }} +{{ $data := getJSON "https://example.org/books.json" $opts }} +``` + +Add multiple headers using a slice: + +```go-html-template +{{ $opts := dict "X-List" (slice "a" "b" "c") }} +{{ $data := getJSON "https://example.org/books.json" $opts }} +``` + +## Global resource alternative + +Consider using the [`resources.Get`] function with [`transform.Unmarshal`] when accessing a global resource. + +```text +my-project/ +└── assets/ + └── data/ + └── books.json +``` + +```go-html-template +{{ $data := "" }} +{{ $p := "data/books.json" }} +{{ with resources.Get $p }} - {{ $opts := dict "delimiter" "," }} - {{ $data = . | transform.Unmarshal $opts }} ++ {{ $data = . | transform.Unmarshal }} +{{ else }} + {{ errorf "Unable to get resource %q" $p }} +{{ end }} +``` + +## Page resource alternative + +Consider using the [`Resources.Get`] method with [`transform.Unmarshal`] when accessing a page resource. + +```text +my-project/ +└── content/ + └── posts/ + └── reading-list/ + ├── books.json + └── index.md +``` + +```go-html-template +{{ $data := "" }} +{{ $p := "books.json" }} +{{ with .Resources.Get $p }} - {{ $opts := dict "delimiter" "," }} - {{ $data = . | transform.Unmarshal $opts }} ++ {{ $data = . | transform.Unmarshal }} +{{ else }} + {{ errorf "Unable to get resource %q" $p }} +{{ end }} +``` + +## Remote resource alternative + +Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`] when accessing a remote resource to improve error handling and cache control. + +```go-html-template +{{ $data := "" }} +{{ $u := "https://example.org/books.json" }} +{{ with resources.GetRemote $u }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} - {{ $opts := dict "delimiter" "," }} - {{ $data = . | transform.Unmarshal $opts }} ++ {{ $data = . | transform.Unmarshal }} + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $u }} +{{ end }} +``` + +[`Resources.Get`]: methods/page/Resources +[`resources.GetRemote`]: /functions/resources/getremote +[`resources.Get`]: /functions/resources/get +[`transform.Unmarshal`]: /functions/transform/unmarshal diff --cc docs/content/en/functions/fmt/Warnf.md index b07cf3cc3,000000000..0a90251d3 mode 100644,000000..100644 --- a/docs/content/en/functions/fmt/Warnf.md +++ b/docs/content/en/functions/fmt/Warnf.md @@@ -1,22 -1,0 +1,33 @@@ +--- +title: fmt.Warnf +description: Log a WARNING from a template. +categories: [] +keywords: [] +action: + aliases: [warnf] + related: + - functions/fmt/Errorf + - functions/fmt/Erroridf + returnType: string + signatures: ['fmt.Warnf FORMAT [INPUT]'] +aliases: [/functions/warnf] +--- + +{{% include "functions/fmt/_common/fmt-layout.md" %}} + +The `warnf` function evaluates the format string, then prints the result to the WARNING log. Hugo prints each unique message once to avoid flooding the log with duplicate warnings. + +```go-html-template +{{ warnf "The %q shortcode was unable to find %s. See %s" .Name $file .Position }} +``` ++ ++To prevent suppression of duplicate messages when using `warnf` for debugging, make each message unique with the [`math.Counter`] function. For example: ++ ++ ++```go-html-template ++{{ range site.RegularPages }} ++ {{ .Section | warnf "%#[2]v [%[1]d]" math.Counter }} ++{{ end }} ++``` ++ ++[`math.Counter`]: /functions/math/counter diff --cc docs/content/en/functions/global/page.md index e17fb0767,000000000..6c96b747e mode 100644,000000..100644 --- a/docs/content/en/functions/global/page.md +++ b/docs/content/en/functions/global/page.md @@@ -1,109 -1,0 +1,109 @@@ +--- +title: page +description: Provides global access to a Page object. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/global/site + returnType: + signatures: [page] +toc: true +aliases: [/functions/page] +--- + +{{< new-in 0.111.0 >}} + +At the top level of a template that receives a `Page` object in context, these are equivalent: + +```go-html-template +{{ .Params.foo }} +{{ .Page.Params.foo }} +{{ page.Params.foo }} +``` + +When a `Page` object is not in context, you can use the global `page` function: + +```go-html-template +{{ page.Params.foo }} +``` + +{{% note %}} +Do not use the global `page` function in shortcodes, partials called by shortcodes, or cached partials. See [warnings](#warnings) below. +{{% /note %}} + +## Explanation + +Hugo almost always passes a `Page` as the data context into the top level template (e.g., `single.html`). The one exception is the multihost sitemap template. This means that you can access the current page with the `.` variable in the template. + +But when you are deeply nested inside of a [content view], [partial], or [render hook], it is not always practical or possible to access the `Page` object. + +Use the global `page` function to access the `Page` object from anywhere in any template. + +## Warnings + +### Be aware of top-level context + +The global `page` function accesses the `Page` object passed into the top-level template. + +With this content structure: + +```text +content/ +├── posts/ +│ ├── post-1.md +│ ├── post-2.md +│ └── post-3.md +└── _index.md <-- title is "My Home Page" +``` + +And this code in the home page template: + +```go-html-template +{{ range site.Sections }} + {{ range .Pages }} + {{ page.Title }} + {{ end }} +{{ end }} +``` + +The rendered output will be: + +```text +My Home Page +My Home Page +My Home Page +``` + +In the example above, the global `page` function accesses the `Page` object passed into the home page template; it does not access the `Page` object of the iterated pages. + +### Be aware of caching + +Do not use the global `page` function in: + +- Shortcodes +- Partials called by shortcodes +- Partials cached by the [`partialCached`] function + - Hugo caches rendered shortcodes. If you use the global `page` function within a shortcode, and the page content is rendered in two or more templates, the cached shortcodes may be incorrect. ++Hugo caches rendered shortcodes. If you use the global `page` function within a shortcode, and the page content is rendered in two or more templates, the cached shortcode may be incorrect. + +Consider this section template: + +```go-html-template +{{ range .Pages }} +

{{ .LinkTitle }}

+ {{ .Summary }} +{{ end }} +``` + +When you call the [`Summary`] method, Hugo renders the page content including shortcodes. In this case, within a shortcode, the global `page` function accesses the `Page` object of the section page, not the content page. + +If Hugo renders the section page before a content page, the cached rendered shortcode will be incorrect. You cannot control the rendering sequence due to concurrency. + +[`Summary`]: /methods/page/summary +[`partialCached`]: /functions/partials/includecached +[content view]: /getting-started/glossary/#content-view +[partial]: /getting-started/glossary/#partial +[render hook]: /getting-started/glossary/#render-hook +[shortcode]: getting-started/glossary/#shortcode diff --cc docs/content/en/functions/go-template/range.md index e8642e50b,000000000..e2f401371 mode 100644,000000..100644 --- a/docs/content/en/functions/go-template/range.md +++ b/docs/content/en/functions/go-template/range.md @@@ -1,199 -1,0 +1,199 @@@ +--- +title: range +description: Iterates over a non-empty collection, binds context (the dot) to successive elements, and executes the block. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/go-template/break + - functions/go-template/continue + - functions/go-template/else + - functions/go-template/end + returnType: + signatures: [range COLLECTION] +aliases: [/functions/range] +toc: true +--- + +{{% include "functions/go-template/_common/truthy-falsy.md" %}} + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} - {{ range $var }} ++{{ range $s }} + {{ . }} → foo bar baz +{{ end }} +``` + +Use with the [`else`] statement: + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} +{{ range $s }} +

{{ . }}

+{{ else }} +

The collection is empty

+{{ end }} +``` + +Within a range block: + +- Use the [`continue`] statement to stop the innermost iteration and continue to the next iteration +- Use the [`break`] statement to stop the innermost iteration and bypass all remaining iterations + +## Understanding context + +At the top of a page template, the [context] (the dot) is a `Page` object. Within the `range` block, the context is bound to each successive element. + +With this contrived example that uses the [`seq`] function to generate a slice of integers: + +```go-html-template +{{ range seq 3 }} + {{ .Title }} +{{ end }} +``` + +Hugo will throw an error: + + can't evaluate field Title in type int + +The error occurs because we are trying to use the `.Title` method on an integer instead of a `Page` object. Within the `range` block, if we want to render the page title, we need to get the context passed into the template. + +{{% note %}} +Use the `$` to get the context passed into the template. +{{% /note %}} + +This template will render the page title three times: + +```go-html-template +{{ range seq 3 }} + {{ $.Title }} +{{ end }} +``` + +{{% note %}} +Gaining a thorough understanding of context is critical for anyone writing template code. +{{% /note %}} + +[`seq`]: functions/collections/seq/ +[context]: /getting-started/glossary/#context + +## Array or slice of scalars + +This template code: + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} +{{ range $s }} +

{{ . }}

+{{ end }} +``` + +Is rendered to: + +```html +

foo

+

bar

+

baz

+``` + +This template code: + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} +{{ range $v := $s }} +

{{ $v }}

+{{ end }} +``` + +Is rendered to: + +```html +

foo

+

bar

+

baz

+``` + +This template code: + +```go-html-template +{{ $s := slice "foo" "bar" "baz" }} +{{ range $k, $v := $s }} +

{{ $k }}: {{ $v }}

+{{ end }} +``` + +Is rendered to: + +```html +

0: foo

+

1: bar

+

2: baz

+``` + +## Array or slice of maps + +This template code: + +```go-html-template +{{ $m := slice + (dict "name" "John" "age" 30) + (dict "name" "Will" "age" 28) + (dict "name" "Joey" "age" 24) +}} +{{ range $m }} +

{{ .name }} is {{ .age }}

+{{ end }} +``` + +Is rendered to: + +```html +

John is 30

+

Will is 28

+

Joey is 24

+``` + +## Array or slice of pages + +This template code: + +```go-html-template +{{ range where site.RegularPages "Type" "articles" }} +

{{ .LinkTitle }}

+{{ end }} +``` + +Is rendered to: + +```html +

Article 3

+

Article 2

+

Article 1

+``` + +## Maps + +This template code: + +```go-html-template +{{ $m := dict "name" "John" "age" 30 }} +{{ range $k, $v := $m }} +

key = {{ $k }} value = {{ $v }}

+{{ end }} +``` + +Is rendered to: + +```go-html-template +

key = age value = 30

+

key = name value = John

+``` + +Unlike ranging over an array or slice, Hugo sorts by key when ranging over a map. + +{{% include "functions/go-template/_common/text-template.md" %}} + +[`else`]: /functions/go-template/else +[`break`]: /functions/go-template/break +[`continue`]: /functions/go-template/continue diff --cc docs/content/en/functions/go-template/with.md index 197181953,000000000..0f3255b1a mode 100644,000000..100644 --- a/docs/content/en/functions/go-template/with.md +++ b/docs/content/en/functions/go-template/with.md @@@ -1,87 -1,0 +1,87 @@@ +--- +title: with +description: Binds context (the dot) to the expression and executes the block if expression is truthy. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/go-template/if + - functions/go-template/else + - functions/go-template/end + - functions/collections/IsSet + returnType: + signatures: [with EXPR] +aliases: [/functions/with] +toc: true +--- + +{{% include "functions/go-template/_common/truthy-falsy.md" %}} + +```go-html-template +{{ $var := "foo" }} +{{ with $var }} + {{ . }} → foo +{{ end }} +``` + +Use with the [`else`] statement: + +```go-html-template +{{ $var := "foo" }} +{{ with $var }} + {{ . }} → foo +{{ else }} + {{ print "var is falsy" }} +{{ end }} +``` + - Intialize a variable, scoped to the current block: ++Initialize a variable, scoped to the current block: + +```go-html-template +{{ with $var := 42 }} + {{ . }} → 42 + {{ $var }} → 42 +{{ end }} +{{ $var }} → undefined +``` + +## Understanding context + +At the top of a page template, the [context] (the dot) is a `Page` object. Inside of the `with` block, the context is bound to the value passed to the `with` statement. + +With this contrived example: + +```go-html-template +{{ with 42 }} + {{ .Title }} +{{ end }} +``` + +Hugo will throw an error: + + can't evaluate field Title in type int + +The error occurs because we are trying to use the `.Title` method on an integer instead of a `Page` object. Inside of the `with` block, if we want to render the page title, we need to get the context passed into the template. + +{{% note %}} +Use the `$` to get the context passed into the template. +{{% /note %}} + +This template will render the page title as desired: + +```go-html-template +{{ with 42 }} + {{ $.Title }} +{{ end }} +``` + +{{% note %}} +Gaining a thorough understanding of context is critical for anyone writing template code. +{{% /note %}} + +[context]: /getting-started/glossary/#context + +{{% include "functions/go-template/_common/text-template.md" %}} + +[`else`]: /functions/go-template/else diff --cc docs/content/en/functions/images/AutoOrient.md index 588f4874c,000000000..8f27a95d8 mode 100644,000000..100644 --- a/docs/content/en/functions/images/AutoOrient.md +++ b/docs/content/en/functions/images/AutoOrient.md @@@ -1,52 -1,0 +1,52 @@@ +--- +title: images.AutoOrient +description: Returns an image filter that rotates and flips an image as needed per its EXIF orientation tag. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/images/Filter + - methods/resource/Filter + returnType: images.filter + signatures: [images.AutoOrient] +toc: true +--- + - {{< new-in 0.122.0 >}} ++{{< new-in 0.121.2 >}} + +## Usage + +Create the filter: + +```go-html-template +{{ $filter := images.AutoOrient }} +``` + +{{% include "functions/images/_common/apply-image-filter.md" %}} + +{{% note %}} +When using with other filters, specify `images.AutoOrient` first. +{{% /note %}} + +```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/Text.md index 0c1e74bce,000000000..8c6670d42 mode 100644,000000..100644 --- a/docs/content/en/functions/images/Text.md +++ b/docs/content/en/functions/images/Text.md @@@ -1,95 -1,0 +1,97 @@@ +--- +title: images.Text +description: Returns an image filter that adds text to an image. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/images/Filter + - methods/resource/Filter + returnType: images.filter + signatures: ['images.Text TEXT [OPTIONS]'] +toc: true +--- + +## Options + +Although none of the options are required, at a minimum you will want to set the `size` to be some reasonable percentage of the image height. + +color +: (`string`) The font color, either a 3-digit or 6-digit hexadecimal color code. Default is `#ffffff` (white). + +font - : (`resource.Resource`) The font can be a [global resource], a [page resource], or a [remote resource]. Default is the "Go Regular" TrueType font. ++: (`resource.Resource`) The font can be a [global resource], a [page resource], or a [remote resource]. Default is [Go Regular], a proportional sans-serif TrueType font. ++ ++[Go Regular]: https://go.dev/blog/go-fonts#sans-serif + +linespacing +: (`int`) The number of pixels between each line. For a line height of 1.4, set the `linespacing` to 0.4 multiplied by the `size`. Default is `2`. + +size +: (`int`) The font size in pixels. Default is `20`. + +x +: (`int`) The horizontal offset, in pixels, relative to the left of the image. Default is `10`. + +y +: (`int`) The vertical offset, in pixels, relative to the top of the image. Default is `10`. + +[global resource]: /getting-started/glossary/#global-resource +[page resource]: /getting-started/glossary/#page-resource +[remote resource]: /getting-started/glossary/#remote-resource + +## Usage + +Capture the font as a resource: + +```go-html-template +{{ $font := "" }} - {{ $path := "https://github.com/google/fonts/raw/main/apache/roboto/static/Roboto-Regular.ttf" }} ++{{ $path := "https://github.com/google/fonts/raw/main/ofl/lato/Lato-Regular.ttf" }} +{{ with resources.GetRemote $path }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} + {{ $font = . }} + {{ end }} +{{ else }} + {{ errorf "Unable to get resource %q" $path }} +{{ end }} +``` + +Create the options map: + +```go-html-template +{{ $opts := dict + "color" "#fbfaf5" + "font" $font + "linespacing" 8 + "size" 40 + "x" 25 + "y" 190 +}} +``` + +Set the text: + +```go-html-template +{{ $text := "Zion National Park" }} +``` + +Create the filter: + +```go-html-template +{{ $filter := images.Text $text $opts }} +``` + +{{% include "functions/images/_common/apply-image-filter.md" %}} + +## Example + +{{< img + src="images/examples/zion-national-park.jpg" + alt="Zion National Park" + filter="Text" + filterArgs="Zion National Park,25,190,40,1.2,#fbfaf5" + example=true +>}} diff --cc docs/content/en/functions/inflect/Humanize.md index 41d61a4e5,000000000..71b4a5fd2 mode 100644,000000..100644 --- a/docs/content/en/functions/inflect/Humanize.md +++ b/docs/content/en/functions/inflect/Humanize.md @@@ -1,26 -1,0 +1,26 @@@ +--- +title: inflect.Humanize +description: Returns the humanized version of the input with the first letter capitalized. +categories: [] +keywords: [] +action: + aliases: [humanize] + related: + - functions/inflect/Pluralize + - functions/inflect/Singularize + returnType: string + signatures: [inflect.Humanize INPUT] +aliases: [/functions/humanize] +--- + +```go-html-template +{{ humanize "my-first-post" }} → My first post +{{ humanize "myCamelPost" }} → My camel post +``` + - If the input is either an int64 value or the string representation of an integer, humanize returns the number with the proper ordinal appended. ++If the input is an integer or a string representation of an integer, humanize returns the number with the proper ordinal appended. + +```go-html-template +{{ humanize "52" }} → 52nd +{{ humanize 103 }} → 103rd +``` diff --cc docs/content/en/functions/lang/Translate.md index 630098a96,000000000..3366d7751 mode 100644,000000..100644 --- a/docs/content/en/functions/lang/Translate.md +++ b/docs/content/en/functions/lang/Translate.md @@@ -1,118 -1,0 +1,135 @@@ +--- +title: lang.Translate +description: Translates a string using the translation tables in the i18n directory. +categories: [] +keywords: [] +action: + aliases: [T, i18n] + related: [] + returnType: string + signatures: ['lang.Translate KEY [CONTEXT]'] +aliases: [/functions/i18n] +--- + ++The `lang.Translate` function returns the value associated with given key as defined in the translation table for the current language. ++ ++If the key is not found in the translation table for the current language, the `lang.Translate` function falls back to the translation table for the [`defaultContentLanguage`]. ++ ++If the key is not found in the translation table for the `defaultContentLanguage`, the `lang.Translate` function returns an empty string. ++ ++[`defaultContentLanguage`]: /getting-started/configuration/#defaultcontentlanguage ++ ++{{% 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. ++ ++[`enableMissingTranslationPlaceholders`]: /getting-started/configuration/#enablemissingtranslationplaceholders ++{{% /note %}} ++ +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 translation tables can contain both: + +- Simple translations +- Translations with pluralization + +The Unicode [CLDR Plural Rules chart] describes the pluralization categories for each language. + +[CLDR Plural Rules chart]: https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html + +The English translation table: + +{{< code-toggle file=i18n/en >}} +privacy = 'privacy' +security = 'security' + +[day] +one = 'day' +other = 'days' + +[day_with_count] +one = '{{ . }} day' +other = '{{ . }} days' +{{< /code-toggle >}} + +The Polish translation table: + +{{< code-toggle file=i18n/pl >}} +privacy = 'prywatność' +security = 'bezpieczeństwo' + +[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. +{{% /note %}} + +When viewing the English language site: + +```go-html-template +{{ T "privacy" }} → privacy +{{ T "security" }} → security + +{{ 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 "privacy" }} → prywatność +{{ T "security" }} → bezpieczeństwo + +{{ 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. +``` diff --cc docs/content/en/functions/math/Rand.md index 4cdf02fd3,000000000..4f71cfcdf mode 100644,000000..100644 --- a/docs/content/en/functions/math/Rand.md +++ b/docs/content/en/functions/math/Rand.md @@@ -1,44 -1,0 +1,46 @@@ +--- +title: math.Rand +description: Returns a pseudo-random number in the half-open interval [0.0, 1.0). +categories: [] +keywords: [] +action: + aliases: [] + related: [] + returnType: float64 + signatures: [math.Rand] +--- + ++{{< new-in 0.121.2 >}} ++ +The `math.Rand` function returns a pseudo-random number in the [half-open interval] [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 }} +``` + +[closed interval]: /getting-started/glossary/#interval +[half-open interval]: /getting-started/glossary/#interval diff --cc docs/content/en/functions/math/Sub.md index 2865ac191,000000000..a89d0e69d mode 100644,000000..100644 --- a/docs/content/en/functions/math/Sub.md +++ b/docs/content/en/functions/math/Sub.md @@@ -1,23 -1,0 +1,24 @@@ +--- +title: math.Sub +description: Subtracts one or more numbers from the first number. +categories: [] ++keywords: [] +action: + aliases: [sub] + related: + - functions/math/Add + - functions/math/Div + - functions/math/Mul + - functions/math/Product + - functions/math/Sum + returnType: any + signatures: [math.Sub VALUE VALUE...] +--- + +If one of the numbers is a [`float`], the result is a `float`. + +```go-html-template +{{ sub 12 3 2 }} → 7 +``` + +[`float`]: /getting-started/glossary/#float diff --cc docs/content/en/functions/openapi3/Unmarshal.md index 50c793685,000000000..433337aef mode 100644,000000..100644 --- a/docs/content/en/functions/openapi3/Unmarshal.md +++ b/docs/content/en/functions/openapi3/Unmarshal.md @@@ -1,76 -1,0 +1,76 @@@ +--- +title: openapi3.Unmarshal +description: Unmarshals the given resource into an OpenAPI 3 document. +categories: [] +keywords: [] +action: + aliases: [] + related: [] + returnType: openapi3.OpenAPIDocument + signatures: ['openapi3.Unmarshal RESOURCE'] +--- + +Use the `openapi3.Unmarshal` function with [global], [page], or [remote] resources. + +[global]: /getting-started/glossary/#global-resource +[page]: /getting-started/glossary/#page-resource +[remote]: /getting-started/glossary/#remote-resource +[OpenAPI]: https://www.openapis.org/ + - For example, to work with a remote [OpenAPI] defintion: ++For example, to work with a remote [OpenAPI] definition: + +```go-html-template +{{ $url := "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.json" }} +{{ $api := "" }} +{{ with resources.GetRemote $url }} + {{ with .Err }} + {{ errorf "%s" . }} + {{ else }} + {{ $api = . | openapi3.Unmarshal }} + {{ end }} +{{ else }} + {{ errorf "Unable to get remote resource %q" $url }} +{{ end }} +``` + +To inspect the data structure: + +```go-html-template +
{{ debug.Dump $api }}
+``` + +To list the GET and POST operations for each of the API paths: + +```go-html-template +{{ range $path, $details := $api.Paths }} +

{{ $path }}

+
+ {{ with $details.Get }} +
GET
+
{{ .Summary }}
+ {{ end }} + {{ with $details.Post }} +
POST
+
{{ .Summary }}
+ {{ end }} +
+{{ end }} +``` + +Hugo renders this to: + + +```html +

/pets

+
+
GET
+
List all pets
+
POST
+
Create a pet
+
+

/pets/{petId}

+
+
GET
+
Info for a specific pet
+
+``` diff --cc docs/content/en/functions/partials/Include.md index 859f6665b,000000000..e08b32fd1 mode 100644,000000..100644 --- a/docs/content/en/functions/partials/Include.md +++ b/docs/content/en/functions/partials/Include.md @@@ -1,85 -1,0 +1,85 @@@ +--- +title: partials.Include +description: Executes the given partial template, optionally passing context. If the partial template contains a return statement, returns the given value, else returns the rendered output. +categories: [] +keywords: [] +action: + aliases: [partial] + related: + - functions/go-template/return + - functions/partials/IncludeCached + - functions/go-template/template + - methods/page/Render + returnType: any + signatures: ['partials.Include NAME [CONTEXT]'] +aliases: [/functions/partial] +--- + +Without a [`return`] statement, the `partial` function returns a string of type `template.HTML`. With a `return` statement, the `partial` function can return any data type. + +[`return`]: /functions/go-template/return + +In this example we have three partial templates: + +```text +layouts/ +└── partials/ + ├── average.html + ├── breadcrumbs.html + └── footer.html +``` + +The "average" partial returns the average of one or more numbers. We pass the numbers in context: + +```go-html-template +{{ $numbers := slice 1 6 7 42 }} +{{ $average := partial "average.html" $numbers }} +``` + +The "breadcrumbs" partial renders [breadcrumb navigation], and needs to receive the current page in context: + +```go-html-template +{{ partial "breadcrumbs.html" . }} +``` + +The "footer" partial renders the site footer. In this contrived example, the footer does not need access to the current page, so we can omit context: + +```go-html-template +{{ partial "breadcrumbs.html" }} +``` + +You can pass anything in context: a page, a page collection, a scalar value, a slice, or a map. For example: + +```go-html-template +{{ $student := dict + "name" "John Doe" + "major" "Finance" + "gpa" 4.0 +}} +{{ partial "render-student-info.html" $student }} +``` + +Then, within the partial template: + +```go-html-template +

{{ .name }} is majoring in {{ .major }}. Their grade point average is {{ .gpa }}.

+``` + +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 := false }} ++{{ $result := "" }} +{{ if math.ModBool . 2 }} + {{ $result = "even" }} +{{ else }} + {{ $result = "odd" }} +{{ end }} +{{ return $result }} +``` + +See [details][`return`]. + +[`return`]: /functions/go-template/return + +[breadcrumb navigation]: /content-management/sections/#ancestors-and-descendants +[details]: /functions/go-template/return diff --cc docs/content/en/functions/partials/IncludeCached.md index db275fa9e,000000000..66ef4a6ac mode 100644,000000..100644 --- a/docs/content/en/functions/partials/IncludeCached.md +++ b/docs/content/en/functions/partials/IncludeCached.md @@@ -1,65 -1,0 +1,65 @@@ +--- +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. +categories: [] +keywords: [] +action: + aliases: [partialCached] + related: + - functions/go-template/return + - functions/partials/Include + - functions/go-template/template + - methods/page/Render + returnType: any + signatures: ['partials.IncludeCached LAYOUT CONTEXT [VARIANT...]'] +signatures: + - partials.IncludeCached NAME CONTEXT [VARIANT...] + - partialCached NAME 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. +{{% /note %}} + +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: + +{{< code file=partial-cached-example.html >}} +{{ partialCached "footer.html" . .Section }} +{{< /code >}} + +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 := false }} ++{{ $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/Concat.md index 3bdf975bf,000000000..809ee83d0 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/Concat.md +++ b/docs/content/en/functions/resources/Concat.md @@@ -1,21 -1,0 +1,26 @@@ +--- +title: resources.Concat - description: Concatenates a slice of resources. ++description: Returns a concatenated slice of resources. +categories: [] +keywords: [] +action: + aliases: [] + related: [] + returnType: resource.Resource + signatures: ['resources.Concat TARGETPATH [RESOURCE...]'] +--- + ++The `resources.Concat` function returns a concatenated slice of resources, caching the result using the target path as its cache key. Each resource must have the same [media type]. ++ ++Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods. ++ ++[media type]: https://en.wikipedia.org/wiki/Media_type ++[`publish`]: /methods/resource/publish ++[`permalink`]: /methods/resource/permalink ++[`relpermalink`]: /methods/resource/relpermalink ++ +```go-html-template +{{ $plugins := resources.Get "js/plugins.js" }} +{{ $global := resources.Get "js/global.js" }} +{{ $js := slice $plugins $global | resources.Concat "js/bundle.js" }} +``` - - Asset files of the same [media type] can be bundled into one resource using the `resources.Concat` function which takes two arguments, the target path for the created resource bundle and a slice of resource objects to be concatenated. - - [media type]: https://en.wikipedia.org/wiki/Media_type diff --cc docs/content/en/functions/resources/ExecuteAsTemplate.md index d17f0580c,000000000..5f7e58413 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/ExecuteAsTemplate.md +++ b/docs/content/en/functions/resources/ExecuteAsTemplate.md @@@ -1,56 -1,0 +1,62 @@@ +--- +title: resources.ExecuteAsTemplate - description: Creates a resource from a Go template, parsed and executed with the given context. ++description: Returns a resource created from a Go template, parsed and executed with the given context. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/resources/FromString + returnType: resource.Resource + signatures: [resources.ExecuteAsTemplate TARGETPATH CONTEXT RESOURCE] +--- + - Hugo publishes the resource to the target path when you call its`.Publish`, `.Permalink`, or `.RelPermalink` method. The resource is cached, using the target path as the cache key. ++The `resources.ExecuteAsTemplate` function returns a resource created from a Go template, parsed and executed with the given context, caching the result using the target path as its cache key. ++ ++Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods. ++ ++[`publish`]: /methods/resource/publish ++[`permalink`]: /methods/resource/permalink ++[`relpermalink`]: /methods/resource/relpermalink + +Let's say you have a CSS file that you wish to populate with values from your site configuration: + +{{< code file=assets/css/template.css lang=go-html-template >}} +body { + background-color: {{ site.Params.style.bg_color }}; + color: {{ site.Params.style.text_color }}; +} +{{< /code >}} + +And your site configuration contains: + +{{< code-toggle file=hugo >}} +[params.style] +bg_color = '#fefefe' +text_color = '#222' +{{< /code-toggle >}} + +Place this in your baseof.html template: + +```go-html-template +{{ with resources.Get "css/template.css" }} + {{ with resources.ExecuteAsTemplate "css/main.css" $ . }} + + {{ end }} +{{ end }} +``` + +The example above: + +1. Captures the template as a resource +2. Executes the resource as a template, passing the current page in context +3. Publishes the resource to css/main.css + +The result is: + +{{< code file=public/css/main.css >}} +body { + background-color: #fefefe; + color: #222; +} +{{< /code >}} diff --cc docs/content/en/functions/resources/FromString.md index 6c22b5310,000000000..75f48ad9c mode 100644,000000..100644 --- a/docs/content/en/functions/resources/FromString.md +++ b/docs/content/en/functions/resources/FromString.md @@@ -1,71 -1,0 +1,77 @@@ +--- +title: resources.FromString - description: Creates a resource from a string. ++description: Returns a resource created from a string. +categories: [] +keywords: [] +action: + aliases: [] + related: + - functions/resources/ExecuteAsTemplate + returnType: resource.Resource + signatures: [resources.FromString TARGETPATH STRING] +--- + - Hugo publishes the resource to the target path when you call its`.Publish`, `.Permalink`, or `.RelPermalink` method. The resource is cached, using the target path as the cache key. ++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": "2023-10-03T10:50:40-07:00", + "hugo_version": "0.120.0", + "last_modified": "2023-10-02T15:21:27-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.LastChange.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 +2. Encodes the map as a JSON string using the [`jsonify`] function +3. Creates a resource from the JSON string using the `resources.FromString` function +4. 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.LastChange.Format $rfc3339) + }} + {{ $json := jsonify $m }} + ` + }} + {{ $r := resources.FromString "" $string }} + {{ $r = $r | resources.ExecuteAsTemplate "site.json" . }} + {{ $r.Publish }} +{{ end }} +``` + +[`dict`]: /functions/collections/dictionary +[`jsonify`]: /functions/encoding/jsonify +[`resources.ExecuteAsTemplate`]: /functions/resources/executeastemplate diff --cc docs/content/en/functions/resources/Minify.md index 44f5f990b,000000000..9749df20a mode 100644,000000..100644 --- a/docs/content/en/functions/resources/Minify.md +++ b/docs/content/en/functions/resources/Minify.md @@@ -1,23 -1,0 +1,23 @@@ +--- +title: resources.Minify +description: Minifies the given resource. +categories: [] +keywords: [] +action: + aliases: [minify] + related: + - functions/js/Build + - functions/resources/Babel + - functions/resources/Fingerprint + - functions/resources/PostCSS + - functions/resources/ToCSS + returnType: resource.Resource + signatures: [resources.Minify RESOURCE] +--- + +```go-html-template +{{ $css := resources.Get "css/main.css" }} +{{ $style := $css | minify }} +``` + - Any CSS, JS, JSON, HTML, SVG or XML resource can be minified using resources.Minify which takes for argument the resource object. ++Any CSS, JS, JSON, HTML, SVG, or XML resource can be minified using resources.Minify which takes for argument the resource object. diff --cc docs/content/en/functions/resources/ToCSS.md index 872bf996b,000000000..d226f2688 mode 100644,000000..100644 --- a/docs/content/en/functions/resources/ToCSS.md +++ b/docs/content/en/functions/resources/ToCSS.md @@@ -1,224 -1,0 +1,224 @@@ +--- +title: resources.ToCSS +description: Transpiles Sass to CSS. +categories: [] +keywords: [] +action: + aliases: [toCSS] + related: + - functions/resources/Fingerprint + - functions/resources/Minify + - functions/resources/PostCSS + - functions/resources/PostProcess + returnType: resource.Resource + signatures: ['resources.ToCSS [OPTIONS] RESOURCE'] +toc: true +--- + +```go-html-template +{{ with resources.Get "sass/main.scss" }} + {{ $opts := dict "transpiler" "libsass" "targetPath" "css/style.css" }} + {{ with . | toCSS $opts }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | minify | fingerprint }} + + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +Transpile Sass to CSS using the LibSass transpiler included in Hugo's extended edition, 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 + +## Options + +transpiler +: (`string`) The transpiler to use, either `libsass` (default) or `dartsass`. Hugo's extended edition includes the LibSass transpiler. To use the Dart Sass transpiler, see the [installation instructions](#dart-sass) below. + +targetPath +: (`string`) If not set, the transformed resource's target path will be the original path of the asset file with its extension replaced by `.css`. + +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; +``` + +outputStyle +: (`string`) Output styles available to LibSass include `nested` (default), `expanded`, `compact`, and `compressed`. Output styles available to Dart Sass include `expanded` (default) and `compressed`. + +precision +: (`int`) Precision of floating point math. Not applicable to Dart Sass. + +enableSourceMap +: (`bool`) If `true`, generates a source map. + +sourceMapIncludeSources +: (`bool`) If `true`, embeds sources in the generated source map. Not applicable to LibSass. + +includePaths +: (`slice`) A slice of paths, relative to the project root, that the transpiler will use when resolving `@use` and `@import` statements. + +```go-html-template +{{ $opts := dict + "transpiler" "dartsass" + "targetPath" "css/style.css" + "vars" site.Params.styles + "enableSourceMap" (not hugo.IsProduction) + "includePaths" (slice "node_modules/bootstrap/scss") +}} +{{ with resources.Get "sass/main.scss" | toCSS $opts | minify | fingerprint }} + +{{ end }} +``` + +## Dart Sass + +The extended version of Hugo includes [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. + +Run `hugo env` to list the active transpilers. + +### Installing in a production environment + +For [CI/CD] deployments (e.g., GitHub Pages, GitLab Pages, Netlify, etc.) you must edit the workflow to install Dart Sass before Hugo builds the site[^2]. Some providers allow you to use one of the package managers above, or you can download and extract one of the prebuilt binaries. + +[^2]: You do not have to do this if (a) you have not modified the assets cache location, and (b) you have not set `useResourceCacheWhen` to `never` in your [site configuration], and (c) you add and commit your resources directory to your repository. + +#### GitHub Pages + +To install Dart Sass for your builds on GitHub Pages, add this step to the GitHub Pages workflow file: + +```yaml +- name: Install Dart Sass + run: sudo snap install dart-sass +``` + +If you are using GitHub Pages for the first time with your repository, GitHub provides a [starter workflow] for Hugo that includes Dart Sass. This is the simplest way to get started. + +#### GitLab Pages + +To install Dart Sass for your builds on GitLab Pages, the `.gitlab-ci.yml` file should look something like this: + +```yaml +variables: - HUGO_VERSION: 0.115.1 - DART_SASS_VERSION: 1.63.6 ++ HUGO_VERSION: 0.121.0 ++ DART_SASS_VERSION: 1.69.5 + GIT_DEPTH: 0 + GIT_STRATEGY: clone + GIT_SUBMODULE_STRATEGY: recursive + TZ: America/Los_Angeles +image: + name: golang:1.20-buster +pages: + script: + # Install Dart Sass + - curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz + - tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz + - cp -r dart-sass/* /usr/local/bin + - rm -rf dart-sass* + # Install Hugo + - curl -LJO https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb + - apt install -y ./hugo_extended_${HUGO_VERSION}_linux-amd64.deb + - rm hugo_extended_${HUGO_VERSION}_linux-amd64.deb + # Build + - hugo --gc --minify + artifacts: + paths: + - public + rules: + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH +``` + +#### Netlify + +To install Dart Sass for your builds on Netlify, the `netlify.toml` file should look something like this: + +```toml +[build.environment] - HUGO_VERSION = "0.115.1" - DART_SASS_VERSION = "1.63.6" ++HUGO_VERSION = "0.121.0" ++DART_SASS_VERSION = "1.69.5" +TZ = "America/Los_Angeles" + +[build] +publish = "public" +command = """\ + curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \ + tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \ + rm dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \ + export PATH=/opt/build/repo/dart-sass:$PATH && \ + hugo --gc --minify \ + """ +``` + +### Example + +To transpile with Dart Sass, set `transpiler` to `dartsass` in the options map passed to `resources.ToCSS`. For example: + +```go-html-template +{{ with resources.Get "sass/main.scss" }} + {{ $opts := dict "transpiler" "dartsass" "targetPath" "css/style.css" }} + {{ with . | toCSS $opts }} + {{ if hugo.IsDevelopment }} + + {{ else }} + {{ with . | minify | fingerprint }} + + {{ end }} + {{ end }} + {{ end }} +{{ end }} +``` + +### Miscellaneous + +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. + +[brew.sh]: https://brew.sh/ +[chocolatey.org]: https://community.chocolatey.org/packages/sass +[ci/cd]: https://en.wikipedia.org/wiki/CI/CD +[dart sass]: https://sass-lang.com/dart-sass +[libsass]: https://sass-lang.com/libsass +[prebuilt binaries]: https://github.com/sass/dart-sass/releases/latest +[scoop.sh]: https://scoop.sh/#/apps?q=sass +[site configuration]: /getting-started/configuration/#configure-build +[snap package]: /installation/linux/#snap +[snapcraft.io]: https://snapcraft.io/dart-sass +[starter workflow]: https://github.com/actions/starter-workflows/blob/main/pages/hugo.yml diff --cc docs/content/en/functions/safe/HTMLAttr.md index 6e1fd2af7,000000000..198fc8ff3 mode 100644,000000..100644 --- a/docs/content/en/functions/safe/HTMLAttr.md +++ b/docs/content/en/functions/safe/HTMLAttr.md @@@ -1,55 -1,0 +1,55 @@@ +--- +title: safe.HTMLAttr +description: Declares the given key/value pair as a safe HTML attribute. +categories: [] +keywords: [] +action: + aliases: [safeHTMLAttr] + related: + - functions/safe/CSS + - functions/safe/HTML + - functions/safe/JS + - functions/safe/JSStr + - functions/safe/URL + returnType: template.HTMLAttr + signatures: [safe.HTMLAttr INPUT] +aliases: [/functions/safehtmlattr] +--- + +Given a site configuration that contains this menu entry: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] + name = "IRC" + url = "irc://irc.freenode.net/#golang" +{{< /code-toggle >}} + +Attempting to use the `url` value directly in an attribute: + +```go-html-template +{{ range site.Menus.main }} + {{ .Name }} +{{ end }} +``` + +Will produce: + +```html +IRC +``` + +`ZgotmplZ` is a special value, inserted by Go's [template/html] package, that indicates that unsafe content reached a CSS or URL context. + +To indicate that the HTML attribute is safe: + +```go-html-template +{{ range site.Menus.main }} + {{ .Name }} +{{ end }} +``` + +{{% note %}} +As demonstrated above, you must pass the HTML attribute name _and_ value through the function. Applying `safeHTMLAttr` to the attribute value has no effect. +{{% /note %}} + +[template/html]: https://pkg.go.dev/html/template diff --cc docs/content/en/functions/safe/URL.md index 2ae67bd7f,000000000..2da6895e5 mode 100644,000000..100644 --- a/docs/content/en/functions/safe/URL.md +++ b/docs/content/en/functions/safe/URL.md @@@ -1,70 -1,0 +1,70 @@@ +--- +title: safe.URL +description: Declares the given string as a safe URL or URL substring. +categories: [] +keywords: [] +action: + aliases: [safeURL] + related: + - functions/safe/CSS + - functions/safe/HTML + - functions/safe/HTMLAttr + - functions/safe/JS + - functions/safe/JSStr + returnType: template.URL + signatures: [safe.URL INPUT] +aliases: [/functions/safeurl] +--- + +`safeURL` declares the provided string as a "safe" URL or URL substring (see [RFC 3986]). A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()` from a trusted source should go in the page, but by default dynamic `javascript:` URLs are filtered out since they are a frequently exploited injection vector. + +Without `safeURL`, only the URI schemes `http:`, `https:` and `mailto:` are considered safe by Go templates. If any other URI schemes (e.g., `irc:` and `javascript:`) are detected, the whole URL will be replaced with `#ZgotmplZ`. This is to "defang" any potential attack in the URL by rendering it useless. + +The following examples use a [site `hugo.toml`][configuration] with the following [menu entry][menus]: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = "IRC: #golang at freenode" +url = "irc://irc.freenode.net/#golang" +{{< /code-toggle >}} + +The following is an example of a sidebar partial that may be used in conjunction with the preceding front matter example: + +{{< code file=layouts/partials/bad-url-sidebar-menu.html >}} + +
    + {{ range .Site.Menus.main }} +
  • {{ .Name }}
  • + {{ end }} +
+{{< /code >}} + +This partial would produce the following HTML output: + +```html + + +``` + +The odd output can be remedied by adding ` | safeURL` to our `.URL` page variable: + +{{< code file=layouts/partials/correct-url-sidebar-menu.html >}} + + +{{< /code >}} + +With the `.URL` page variable piped through `safeURL`, we get the desired output: + +```html + +``` + +[configuration]: /getting-started/configuration/ +[menus]: /content-management/menus/ +[RFC 3986]: https://tools.ietf.org/html/rfc3986 diff --cc docs/content/en/functions/strings/FindRESubmatch.md index 029cb323e,000000000..302d1d9b4 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/FindRESubmatch.md +++ b/docs/content/en/functions/strings/FindRESubmatch.md @@@ -1,90 -1,0 +1,90 @@@ +--- +title: strings.FindRESubmatch +description: Returns a slice of all successive matches of the regular expression. 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. +categories: [] +keywords: [] +action: + aliases: [findRESubmatch] + related: + - functions/strings/FindRE + - functions/strings/Replace + - functions/strings/ReplaceRE - returnType: '[]string' ++ returnType: '[][]string' + signatures: ['strings.FindRESubmatch PATTERN INPUT [LIMIT]'] +aliases: [/functions/findresubmatch] +--- + +By default, `findRESubmatch` finds all matches. You can limit the number of matches with an optional LIMIT argument. A return value of nil indicates no match. + +{{% include "functions/_common/regular-expressions.md" %}} + +## Demonstrative examples + +```go-html-template +{{ findRESubmatch `a(x*)b` "-ab-" }} → [["ab" ""]] +{{ findRESubmatch `a(x*)b` "-axxb-" }} → [["axxb" "xx"]] +{{ findRESubmatch `a(x*)b` "-ab-axb-" }} → [["ab" ""] ["axb" "x"]] +{{ findRESubmatch `a(x*)b` "-axxb-ab-" }} → [["axxb" "xx"] ["ab" ""]] +{{ findRESubmatch `a(x*)b` "-axxb-ab-" 1 }} → [["axxb" "xx"]] +``` + +## Practical example + +This markdown: + +```text +- [Example](https://example.org) +- [Hugo](https://gohugo.io) +``` + +Produces this HTML: + +```html + +``` + +To match the anchor elements, capturing the link destination and text: + +```go-html-template +{{ $regex := `(.+?)` }} +{{ $matches := findRESubmatch $regex .Content }} +``` + +Viewed as JSON, the data structure of `$matches` in the code above is: + +```json +[ + [ + "Example", + "https://example.org", + "Example" + ], + [ + "Hugo", + "https://gohugo.io", + "Hugo" + ] +] +``` + +To render the `href` attributes: + +```go-html-template +{{ range $matches }} + {{ index . 1 }} +{{ end }} +``` + +Result: + +```text +https://example.org +https://gohugo.io +``` + +{{% note %}} +You can write and test your regular expression using [regex101.com](https://regex101.com/). Be sure to select the Go flavor before you begin. +{{% /note %}} diff --cc docs/content/en/functions/strings/FindRe.md index d26bae4a3,000000000..861f38a12 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/FindRe.md +++ b/docs/content/en/functions/strings/FindRe.md @@@ -1,36 -1,0 +1,36 @@@ +--- +title: strings.FindRE +description: Returns a slice of strings that match the regular expression. +categories: [] +keywords: [] +action: + aliases: [findRE] + related: + - functions/strings/FindRESubmatch + - functions/strings/Replace + - functions/strings/ReplaceRE - returnType: string ++ returnType: '[]string' + signatures: ['strings.FindRE PATTERN INPUT [LIMIT]'] +aliases: [/functions/findre] +--- +By default, `findRE` finds all matches. You can limit the number of matches with an optional LIMIT argument. + +{{% include "functions/_common/regular-expressions.md" %}} + +This example returns a slice of all second level headings (`h2` elements) within the rendered `.Content`: + +```go-html-template +{{ findRE `(?s).*?` .Content }} +``` + +The `s` flag causes `.` to match `\n` as well, allowing us to find an `h2` element that contains newlines. + +To limit the number of matches to one: + +```go-html-template +{{ findRE `(?s).*?` .Content 1 }} +``` + +{{% note %}} +You can write and test your regular expression using [regex101.com](https://regex101.com/). Be sure to select the Go flavor before you begin. +{{% /note %}} diff --cc docs/content/en/functions/strings/HasSuffix.md index e7f253ce9,000000000..8fb12c527 mode 100644,000000..100644 --- a/docs/content/en/functions/strings/HasSuffix.md +++ b/docs/content/en/functions/strings/HasSuffix.md @@@ -1,21 -1,0 +1,21 @@@ +--- +title: strings.HasSuffix - description: Reports whether the given string begins with the given suffix. ++description: Reports whether the given string ends with the given suffix. +categories: [] +keywords: [] +action: + aliases: [hasSuffix] + related: + - functions/strings/Contains + - functions/strings/ContainsAny + - functions/strings/ContainsNonSpace + - functions/strings/HasPrefix + - functions/collections/In + returnType: bool + signatures: [strings.HasSuffix STRING SUFFIX] +aliases: [/functions/hassuffix,/functions/strings/hassuffix] +--- + +```go-html-template +{{ hasSuffix "Hugo" "go" }} → true +``` diff --cc docs/content/en/functions/transform/XMLEscape.md index 17ed2a13d,000000000..d0aafc4bd mode 100644,000000..100644 --- a/docs/content/en/functions/transform/XMLEscape.md +++ b/docs/content/en/functions/transform/XMLEscape.md @@@ -1,38 -1,0 +1,40 @@@ +--- +title: transform.XMLEscape +description: Returns the given string, removing disallowed characters then escaping the result to its XML equivalent. +categories: [] +keywords: [] +action: + aliases: [] + related: [] + 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> ++{{ 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: + +{{< code file="layouts/_default/rss.xml" >}} +{{ .Summary | transform.XMLEscape | safeHTML }} +{{< /code >}} + +[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/configuration.md index 5e861759b,000000000..3ce0077ba mode 100644,000000..100644 --- a/docs/content/en/getting-started/configuration.md +++ b/docs/content/en/getting-started/configuration.md @@@ -1,851 -1,0 +1,788 @@@ +--- +title: Configure Hugo +linkTitle: Configuration +description: How to configure your Hugo site. +categories: [getting started,fundamentals] +keywords: [configuration,toml,yaml,json] +menu: + docs: + parent: getting-started + weight: 40 +weight: 40 +toc: true +aliases: [/overview/source-directory/,/overview/configuration/] +--- + +## Configuration file + - Hugo uses the `hugo.toml`, `hugo.yaml`, or `hugo.json` (if found in the - site root) as the default site configuration file. ++Create a site configuration file in the root of your project directory, naming it `hugo.toml`, `hugo.yaml`, or `hugo.json`, with that order of precedence. + - The user can choose to override that default with one or more site configuration files using the command-line `--config` switch. ++```text ++my-project/ ++└── hugo.toml ++``` ++ ++{{% note %}} ++With v0.109.0 and earlier the basename of the site configuration file was `config` instead of `hugo`. You can use either, but should transition to the new naming convention when practical. ++{{% /note %}} + - Examples: ++A simple example: + - ```txt - hugo --config debugconfig.toml - hugo --config a.toml,b.toml,c.toml ++{{< code-toggle file=hugo >}} ++baseURL = 'https://example.org/' ++languageCode = 'en-us' ++title = 'ABC Widgets, Inc.' ++[params] ++subtitle = 'The Best Widgets on Earth' ++[params.contact] ++email = 'info@example.org' ++phone = '+1 202-555-1212' ++{{< /code-toggle >}} ++ ++To use a different configuration file when building your site, use the `--config` flag: ++ ++```sh ++hugo --config other.toml ++``` ++ ++Combine two or more configuration files, with left-to-right precedence: ++ ++```sh ++hugo --config a.toml,b.yaml,c.json +``` + +{{% note %}} - Multiple site configuration files can be specified as a comma-separated string to the `--config` switch. ++See the specifications for each file format: [TOML], [YAML], and [JSON]. ++ ++[TOML]: https://toml.io/en/latest ++[YAML]: https://yaml.org/spec/ ++[JSON]: https://datatracker.ietf.org/doc/html/rfc7159 +{{% /note %}} + - ## hugo.toml vs config.toml ++## Configuration directory + - In Hugo 0.110.0 we changed the default configuration base file name to `hugo`, e.g. `hugo.toml`. We will still look for `config.toml` etc., but we recommend you eventually rename it (but you need to wait if you want to support older Hugo versions). The main reason we're doing this is to make it easier for code editors and build tools to identify this as a Hugo configuration file and project. ++Instead of a single site configuration file, split your configuration by [environment], root configuration key, and language. For example: + - {{< new-in 0.110.0 >}} ++[environment]: /getting-started/glossary/#environment + - ## Configuration directory ++```text ++my-project/ ++└── config/ ++ ├── _default/ ++ │ ├── hugo.toml ++ │ ├── menus.en.toml ++ │ ├── menus.de.toml ++ │ └── params.toml ++ ├── production/ ++ │ ├── hugo.toml ++ │ └── params.toml ++ └── staging/ ++ ├── hugo.toml ++ └── params.toml ++``` + - In addition to using a single site configuration file, one can use the `configDir` directory (default to `config/`) to maintain easier organization and environment specific settings. ++The root configuration keys are `build`, `caches`, `cascade`, `deployment`, `frontmatter`, `imaging`, `languages`, `markup`, `mediatypes`, `menus`, `minify`, `module`, `outputformats`, `outputs`, `params`, `permalinks`, `privacy`, `related`, `security`, `server`, `services`, `sitemap`, and `taxonomies`. + - - Each file represents a configuration root object, such as `params.toml` for `[Params]`, `menu(s).toml` for `[Menu]`, `languages.toml` for `[Languages]` etc... - - Each file's content must be top-level, for example: ++### Omit the root key + - {{< code-toggle file="hugo" copy=false >}} - [Params] - foo = "bar" ++When splitting the configuration by root key, omit the root key in the given file. For example, these are equivalent: ++ ++{{< code-toggle file=hugo >}} ++[params] ++foo = 'bar' +{{< /code-toggle >}} + - {{< code-toggle file="params" copy=false >}} - foo = "bar" ++{{< code-toggle file=params >}} ++foo = 'bar' +{{< /code-toggle >}} + - - Each directory holds a group of files containing settings unique to an environment. - - Files can be localized to become language specific. ++### Recursive parsing + - ```txt - ├── config - │ ├── _default - │ │ ├── hugo.toml - │ │ ├── languages.toml - │ │ ├── menus.en.toml - │ │ ├── menus.zh.toml - │ │ └── params.toml - │ ├── production - │ │ ├── hugo.toml - │ │ └── params.toml - │ └── staging - │ ├── hugo.toml - │ └── params.toml ++Hugo parses the `config` directory recursively, allowing you to organize the files into subdirectories. For example: ++ ++```text ++my-project/ ++└── config/ ++ └── _default/ ++ ├── navigation/ ++ │ ├── menus.de.toml ++ │ └── menus.en.toml ++ └── hugo.toml ++``` ++ ++### Example ++ ++```text ++my-project/ ++└── config/ ++ ├── _default/ ++ │ ├── hugo.toml ++ │ ├── menus.en.toml ++ │ ├── menus.de.toml ++ │ └── params.toml ++ ├── production/ ++ │ ├── hugo.toml ++ │ └── params.toml ++ └── staging/ ++ ├── hugo.toml ++ └── params.toml +``` + +Considering the structure above, when running `hugo --environment staging`, Hugo will use every setting from `config/_default` and merge `staging`'s on top of those. + +Let's take an example to understand this better. Let's say you are using Google Analytics for your website. This requires you to specify a [Google tag ID] in your site configuration: + +[Google tag ID]: https://support.google.com/tagmanager/answer/12326985?hl=en + +{{< code-toggle file=hugo copy=false >}} +[services.googleAnalytics] +ID = 'G-XXXXXXXXX' +{{< /code-toggle >}} + +Now consider the following scenario: + +1. You don't want to load the analytics code when running `hugo server`. +2. You want to use different Google tag IDs for your production and staging environments. For example: + + - `G-PPPPPPPPP` for production + - `G-SSSSSSSSS` for staging + +To satisfy these requirements, configure your site as follows: + +1. `config/_default/hugo.toml` + + Exclude the `services.googleAnalytics` section. This will prevent loading of the analytics code when you run `hugo server`. + + By default, Hugo sets its `environment` to `development` when running `hugo server`. In the absence of a `config/development` directory, Hugo uses the `config/_default` directory. + +2. `config/production/hugo.toml` + + Include this section only: + + {{< code-toggle file=hugo copy=false >}} + [services.googleAnalytics] + ID = 'G-PPPPPPPPP' + {{< /code-toggle >}} + + You do not need to include other parameters in this file. Include only those parameters that are specific to your production environment. Hugo will merge these parameters with the default configuration. + + By default, Hugo sets its `environment` to `production` when running `hugo`. The analytics code will use the `G-PPPPPPPPP` tag ID. + +3. `config/staging/hugo.toml` + + Include this section only: + + {{< code-toggle file=hugo copy=false >}} + [services.googleAnalytics] + ID = 'G-SSSSSSSSS' + {{< /code-toggle >}} + + You do not need to include other parameters in this file. Include only those parameters that are specific to your staging environment. Hugo will merge these parameters with the default configuration. + + To build your staging site, run `hugo --environment staging`. The analytics code will use the `G-SSSSSSSSS` tag ID. + +## Merge configuration from themes + +The configuration value for `_merge` can be one of: + +none +: No merge. + +shallow +: Only add values for new keys. + +deep +: Add values for new keys, merge existing. + +Note that you don't need to be so verbose as in the default setup below; a `_merge` value higher up will be inherited if not set. + +{{< code-toggle file=hugo dataKey="config_helpers.mergeStrategy" skipHeader=true />}} + +## All configuration settings + - The following is the full list of Hugo-defined variables. Users may choose to override those values in their site configuration file(s). - - ### archetypeDir - - **Default value:** "archetypes" - - The directory where Hugo finds archetype files (content templates). {{% module-mounts-note %}} ++###### archetypeDir + - ### assetDir ++(`string`) The directory where Hugo finds archetype files (content templates). Default is `archetypes`. {{% module-mounts-note %}} + - **Default value:** "assets" ++###### assetDir + - The directory where Hugo finds asset files used in [Hugo Pipes](/hugo-pipes/). {{% module-mounts-note %}} ++(`string`) The directory where Hugo finds asset files used in [Hugo Pipes](/hugo-pipes/). Default is `assets`. {{% module-mounts-note %}} + - ### baseURL ++###### baseURL + - The absolute URL (protocol, host, path, and trailing slash) of your published site (e.g., `https://www.example.org/docs/`). ++(`string`) The absolute URL (protocol, host, path, and trailing slash) of your published site (e.g., `https://www.example.org/docs/`). + - ### build ++###### build + - See [Configure Build](#configure-build) ++See [Configure Build](#configure-build). + - ### buildDrafts (false) ++###### buildDrafts + - **Default value:** false ++(`bool`) Include drafts when building. Default is `false`. + - Include drafts when building. ++###### buildExpired + - ### buildExpired ++(`bool`) Include content already expired. Default is `false`. + - **Default value:** false ++###### buildFuture + - Include content already expired. ++(`bool`) Include content with publishdate in the future. Default is `false`. + - ### buildFuture ++###### caches + - **Default value:** false ++See [Configure File Caches](#configure-file-caches). + - Include content with publishdate in the future. - - ### caches - - See [Configure File Caches](#configure-file-caches) - - ### cascade ++###### cascade + +Pass down down default configuration values (front matter) to pages in the content tree. The options in site config is the same as in page front matter, see [Front Matter Cascade](/content-management/front-matter#front-matter-cascade). + +{{% note %}} +For a website in a single language, define the `[[cascade]]` in [Front Matter](/content-management/front-matter#front-matter-cascade). For a multilingual website, define the `[[cascade]]` in [Site Config](../../getting-started/configuration/#cascade). + - To remain consistent and prevent unexpected behaviour, do not mix these strategies. ++To remain consistent and prevent unexpected behavior, do not mix these strategies. +{{% /note %}} + - ### canonifyURLs - - **Default value:** false - - Enable to turn relative URLs into absolute. See [details](/content-management/urls/#canonical-urls). - - ### cleanDestinationDir - - **Default value:** false - - When building, removes files from destination not found in static directories. - - ### contentDir - - **Default value:** "content" - - The directory from where Hugo reads content files. {{% module-mounts-note %}} - - ### copyright - - **Default value:** "" - - Copyright notice for your site, typically displayed in the footer. - - ### dataDir - - **Default value:** "data" - - The directory from where Hugo reads data files. {{% module-mounts-note %}} - - ### defaultContentLanguage ++###### canonifyURLs + - **Default value:** "en" ++(`bool`) Enable to turn relative URLs into absolute. Default is `false`. See [details](/content-management/urls/#canonical-urls). + - Content without language indicator will default to this language. ++###### cleanDestinationDir + - ### defaultContentLanguageInSubdir ++(`bool`) When building, removes files from destination not found in static directories. Default is `false`. + - **Default value:** false ++###### contentDir + - Render the default content language in subdir, e.g. `content/en/`. The site root `/` will then redirect to `/en/`. ++(`string`) The directory from where Hugo reads content files. Default is `content`. {{% module-mounts-note %}} + - ### disableAliases ++###### copyright + - **Default value:** false ++(`string`) Copyright notice for your site, typically displayed in the footer. + - Will disable generation of alias redirects. Note that even if `disableAliases` is set, the aliases themselves are preserved on the page. The motivation with this is to be able to generate 301 redirects in an `.htaccess`, a Netlify `_redirects` file or similar using a custom output format. ++###### dataDir + - ### disableHugoGeneratorInject ++(`string`) The directory from where Hugo reads data files. Default is `data`. {{% module-mounts-note %}} + - **Default value:** false ++###### defaultContentLanguage + - Hugo will, by default, inject a generator meta tag in the HTML head on the _home page only_. You can turn it off, but we would really appreciate if you don't, as this is a good way to watch Hugo's popularity on the rise. ++(`string`) Content without language indicator will default to this language. Default is `en`. + - ### disableKinds ++###### defaultContentLanguageInSubdir + - **Default value:** [] ++(`bool`) Render the default content language in subdir, e.g. `content/en/`. The site root `/` will then redirect to `/en/`. Default is `false`. + - Enable disabling of all pages of the specified *Kinds*. Allowed values in this list: `"page"`, `"home"`, `"section"`, `"taxonomy"`, `"term"`, `"RSS"`, `"sitemap"`, `"robotsTXT"`, `"404"`. ++###### disableAliases + - ### disableLiveReload ++(`bool`) Will disable generation of alias redirects. Note that even if `disableAliases` is set, the aliases themselves are preserved on the page. The motivation with this is to be able to generate 301 redirects in an `.htaccess`, a Netlify `_redirects` file or similar using a custom output format. Default is `false`. + - **Default value:** false ++###### disableHugoGeneratorInject + - Disable automatic live reloading of browser window. ++(`bool`) Hugo will, by default, inject a generator meta tag in the HTML head on the _home page only_. You can turn it off, but we would really appreciate if you don't, as this is a good way to watch Hugo's popularity on the rise. Default is `false`. + - ### disablePathToLower ++###### disableKinds + - **Default value:** false ++(`string slice`) Disable rendering of the specified page [kinds], any of `404`, `home`, `page`, `robotstxt`, `rss`, `section`, `sitemap`, `taxonomy`, or `term`. + - Do not convert the url/path to lowercase. ++[kinds]: /getting-started/glossary/#page-kind + - ### enableEmoji ++###### disableLiveReload + - **Default value:** false ++(`bool`) Disable automatic live reloading of browser window. Default is `false`. + - Enable Emoji emoticons support for page content; see the [emoji shortcode quick reference guide](/quick-reference/emojis/). ++###### disablePathToLower + - ### enableGitInfo ++(`bool`) Do not convert the url/path to lowercase. Default is `false`. + - **Default value:** false ++###### enableEmoji + - Enable `.GitInfo` object for each page (if the Hugo site is versioned by Git). This will then update the `Lastmod` parameter for each page using the last git commit date for that content file. ++(`bool`) Enable Emoji emoticons support for page content; see the [emoji shortcode quick reference guide](/quick-reference/emojis/). Default is `false`. + - ### enableInlineShortcodes ++###### enableGitInfo + - **Default value:** false ++(`bool`) Enable `.GitInfo` object for each page (if the Hugo site is versioned by Git). This will then update the `Lastmod` parameter for each page using the last git commit date for that content file. Default is `false`. + - Enable inline shortcode support. See [Inline Shortcodes](/templates/shortcode-templates/#inline-shortcodes). ++###### enableMissingTranslationPlaceholders + - ### enableMissingTranslationPlaceholders ++(`bool`) Show a placeholder instead of the default value or an empty string if a translation is missing. Default is `false`. + - **Default value:** false ++###### enableRobotsTXT + - Show a placeholder instead of the default value or an empty string if a translation is missing. ++(`bool`) Enable generation of `robots.txt` file. Default is `false`. + - ### enableRobotsTXT - - **Default value:** false - - Enable generation of `robots.txt` file. - - ### frontmatter ++###### frontmatter + +See [Front matter Configuration](#configure-front-matter). + - ### hasCJKLanguage ++###### hasCJKLanguage + - **Default value:** false ++(`bool`) If true, auto-detect Chinese/Japanese/Korean Languages in the content. This will make `.Summary` and `.WordCount` behave correctly for CJK languages. Default is `false`. + - If true, auto-detect Chinese/Japanese/Korean Languages in the content. This will make `.Summary` and `.WordCount` behave correctly for CJK languages. - - ### imaging ++###### imaging + +See [image processing configuration](/content-management/image-processing/#imaging-configuration). + - ### languageCode - - **Default value:** "" ++###### languageCode + - A language tag as defined by [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646). This value is used to populate: ++(`string`) A language tag as defined by [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646). This value is used to populate: + +- The `` element in the internal [RSS template](https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml) +- The `lang` attribute of the `` element in the internal [alias template](https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/alias.html) + - ### languages ++###### languages + +See [Configure Languages](/content-management/multilingual/#configure-languages). + - ### disableLanguages ++###### disableLanguages + +See [Disable a Language](/content-management/multilingual/#disable-a-language) + - ### markup ++###### markup + +See [Configure Markup](/getting-started/configuration-markup). + - ### mediaTypes ++###### mediaTypes + +See [Configure Media Types](/templates/output-formats/#media-types). + - ### menus ++###### menus + +See [Menus](/content-management/menus/#define-in-site-configuration). + - ### minify ++###### minify + - See [Configure Minify](#configure-minify) ++See [Configure Minify](#configure-minify). + - ### module ++###### module + +Module configuration see [module configuration](/hugo-modules/configuration/). + - ### newContentEditor - - **Default value:** "" ++###### newContentEditor + - The editor to use when creating new content. ++(`string`) The editor to use when creating new content. + - ### noChmod ++###### noChmod + - **Default value:** false ++(`bool`) Don't sync permission mode of files. Default is `false`. + - Don't sync permission mode of files. ++###### noTimes + - ### noTimes ++(`bool`) Don't sync modification time of files. Default is `false`. + - **Default value:** false - - Don't sync modification time of files. - - ### outputFormats ++###### outputFormats + +See [Configure Output Formats](#configure-additional-output-formats). + - ### paginate - - **Default value:** 10 ++###### paginate + - Default number of elements per page in [pagination](/templates/pagination/). ++(`int`) Default number of elements per page in [pagination](/templates/pagination/). Default is `10`. + - ### paginatePath ++###### paginatePath + - **Default value:** "page" ++(`string`) The path element used during pagination (`https://example.org/page/2`). Default is `page`. + - The path element used during pagination (`https://example.org/page/2`). - - ### permalinks ++###### permalinks + +See [Content Management](/content-management/urls/#permalinks). + - ### pluralizeListTitles - - **Default value:** true - - Pluralize titles in lists. ++###### pluralizeListTitles + - ### publishDir ++(`bool`) Pluralize titles in lists. Default is `true`. + - **Default value:** "public" ++###### publishDir + - The directory to where Hugo will write the final static site (the HTML files etc.). ++(`string`) The directory to where Hugo will write the final static site (the HTML files etc.). Default is `public`. + - ### related ++###### related + +See [Related Content](/content-management/related/#configure-related-content). + - ### relativeURLs ++###### relativeURLs + - **Default value:** false ++(`bool`) Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. Default is `false`. See [details](/content-management/urls/#relative-urls). + - Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. See [details](/content-management/urls/#relative-urls). ++###### refLinksErrorLevel + - ### refLinksErrorLevel ++(`string`) When using `ref` or `relref` to resolve page links and a link cannot be resolved, it will be logged with this log level. Valid values are `ERROR` (default) or `WARNING`. Any `ERROR` will fail the build (`exit -1`). Default is `ERROR`. + - **Default value:** "ERROR" ++###### refLinksNotFoundURL + - When using `ref` or `relref` to resolve page links and a link cannot be resolved, it will be logged with this log level. Valid values are `ERROR` (default) or `WARNING`. Any `ERROR` will fail the build (`exit -1`). ++(`string`) URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is. + - ### refLinksNotFoundURL ++###### removePathAccents + - URL to be used as a placeholder when a page reference cannot be found in `ref` or `relref`. Is used as-is. - - ### removePathAccents - - **Default value:** false - - Removes [non-spacing marks](https://www.compart.com/en/unicode/category/Mn) from [composite characters](https://en.wikipedia.org/wiki/Precomposed_character) in content paths. ++(`bool`) Removes [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`. + +```text +content/post/hügó.md → https://example.org/post/hugo/ +``` + - ### sectionPagesMenu ++###### sectionPagesMenu + +See [Menus](/content-management/menus/#define-automatically). + - ### security ++###### security + - See [Security Policy](/about/security-model/#security-policy) ++See [Security Policy](/about/security-model/#security-policy). + - ### sitemap ++###### sitemap + +Default [sitemap configuration](/templates/sitemap-template/#configuration). + - ### summaryLength ++###### summaryLength + - **Default value:** 70 ++(`int`) The length of text in words to show in a [`.Summary`](/content-management/summaries/#automatic-summary-splitting). Default is `70`. + - The length of text in words to show in a [`.Summary`](/content-management/summaries/#automatic-summary-splitting). - - ### taxonomies ++###### taxonomies + +See [Configure Taxonomies](/content-management/taxonomies#configure-taxonomies). + - ### theme - - : See [module configuration](/hugo-modules/configuration/#module-configuration-imports) for how to import a theme. - - ### themesDir ++###### theme + - **Default value:** "themes" ++See [module configuration](/hugo-modules/configuration/#module-configuration-imports) for how to import a theme. + - The directory where Hugo reads the themes from. ++###### themesDir + - ### timeout ++(`string`) The directory where Hugo reads the themes from. Default is `themes`. + - **Default value:** "30s" ++###### timeout + - Timeout for generating page contents, specified as a [duration](https://pkg.go.dev/time#Duration) or in seconds. *Note:* this is used to bail out of recursive content generation. You might need to raise this limit if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents). ++(`string`) Timeout for generating page contents, specified as a [duration](https://pkg.go.dev/time#Duration) or in seconds. *Note:* this is used to bail out of recursive content generation. You might need to raise this limit if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents). Default is `30s`. + - ### timeZone ++###### timeZone + - The time zone (or location), e.g. `Europe/Oslo`, used to parse front matter dates without such information and in the [`time`] function. The list of valid values may be system dependent, but should include `UTC`, `Local`, and any location in the [IANA Time Zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). ++(`string`) The time zone (or location), e.g. `Europe/Oslo`, used to parse front matter dates without such information and in the [`time`] function. The list of valid values may be system dependent, but should include `UTC`, `Local`, and any location in the [IANA Time Zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + - ### title ++###### title + - Site title. ++(`string`) Site title. + - ### titleCaseStyle ++###### titleCaseStyle + - **Default value:** "ap" ++(`string`) Default is `ap`. See [Configure Title Case](#configure-title-case). + - See [Configure Title Case](#configure-title-case) ++###### uglyURLs + - ### uglyURLs ++(`bool`) When enabled, creates URL of the form `/filename.html` instead of `/filename/`. Default is `false`. + - **Default value:** false ++###### watch + - When enabled, creates URL of the form `/filename.html` instead of `/filename/`. - - ### watch - - **Default value:** false - - Watch filesystem for changes and recreate as needed. ++(`bool`) Watch filesystem for changes and recreate as needed. Default is `false`. + +{{% note %}} +If you are developing your site on a \*nix machine, here is a handy shortcut for finding a configuration option from the command line: +```txt +cd ~/sites/yourhugosite +hugo config | grep emoji +``` + +which shows output like + +```txt +enableemoji: true +``` +{{% /note %}} + +## Configure build + +The `build` configuration section contains global build-related configuration options. + +{{< code-toggle config=build />}} + +buildStats {{< new-in 0.115.1 >}} +: When enabled, creates a `hugo_stats.json` file in the root of your project. This file contains arrays of the `class` attributes, `id` attributes, and tags of every HTML element within your published site. Use this file as data source when [removing unused CSS] from your site. This process is also known as pruning, purging, or tree shaking. + +[removing unused CSS]: /hugo-pipes/postprocess/#css-purging-with-postcss + +Exclude `class` attributes, `id` attributes, or tags from `hugo_stats.json` with the `disableClasses`, `disableIDs`, and `disableTags` keys. + +{{% note %}} +With v0.115.0 and earlier this feature was enabled by setting `writeStats` to `true`. Although still functional, the `writeStats` key will be deprecated in a future release. + +Given that CSS purging is typically limited to production builds, place the `buildStats` object below [config/production]. + +[config/production]: /getting-started/configuration/#configuration-directory + +Built for speed, there may be "false positive" detections (e.g., HTML elements that are not HTML elements) while parsing the published site. These "false positives" are infrequent and inconsequential. +{{% /note %}} + +Due to the nature of partial server builds, new HTML entities are added while the server is running, but old values will not be removed until you restart the server or run a regular `hugo` build. + +cachebusters +: See [Configure Cache Busters](#configure-cache-busters) + +noJSConfigInAssets +: Turn off writing a `jsconfig.json` into your `/assets` folder with mapping of imports from running [js.Build](/hugo-pipes/js). This file is intended to help with intellisense/navigation inside code editors such as [VS Code](https://code.visualstudio.com/). Note that if you do not use `js.Build`, no file will be written. + +useResourceCacheWhen +: When to use the cached resources in `/resources/_gen` for PostCSS and ToCSS. Valid values are `never`, `always` and `fallback`. The last value means that the cache will be tried if PostCSS/extended version is not available. + +## Configure cache busters + +{{< new-in 0.112.0 >}} + +The `build.cachebusters` configuration option was added to support development using Tailwind 3.x's JIT compiler where a `build` configuration may look like this: + +{{< code-toggle file=hugo >}} +[build] + [build.buildStats] + enable = true + [[build.cachebusters]] + source = "assets/watching/hugo_stats\\.json" + target = "styles\\.css" + [[build.cachebusters]] + source = "(postcss|tailwind)\\.config\\.js" + target = "css" + [[build.cachebusters]] + source = "assets/.*\\.(js|ts|jsx|tsx)" + target = "js" + [[build.cachebusters]] + source = "assets/.*\\.(.*)$" + target = "$1" +{{< /code-toggle >}} + - Some key points in the above are `writeStats = true`, which writes a `hugo_stats.json` file on each build with HTML classes etc. that's used in the rendered output. Changes to this file will trigger a rebuild of the `styles.css` file. You also need to add `hugo_stats.json` to Hugo's server watcher. See [Hugo Starter Tailwind Basic](https://github.com/bep/hugo-starter-tailwind-basic) for a running example. ++When `buildStats` {{< new-in 0.115.1 >}} is enabled, Hugo writes a `hugo_stats.json` file on each build with HTML classes etc. that's used in the rendered output. Changes to this file will trigger a rebuild of the `styles.css` file. You also need to add `hugo_stats.json` to Hugo's server watcher. See [Hugo Starter Tailwind Basic](https://github.com/bep/hugo-starter-tailwind-basic) for a running example. + +source +: A regexp matching file(s) relative to one of the virtual component directories in Hugo, typically `assets/...`. + +target +: A regexp matching the keys in the resource cache that should be expired when `source` changes. You can use the matching regexp groups from `source` in the expression, e.g. `$1`. + +## Configure server + +This is only relevant when running `hugo server`, and it allows to set HTTP headers during development, which allows you to test out your Content Security Policy and similar. The configuration format matches [Netlify's](https://docs.netlify.com/routing/headers/#syntax-for-the-netlify-configuration-file) with slightly more powerful [Glob matching](https://github.com/gobwas/glob): + +{{< code-toggle file=hugo >}} +[server] +[[server.headers]] +for = "/**" + +[server.headers.values] +X-Frame-Options = "DENY" +X-XSS-Protection = "1; mode=block" +X-Content-Type-Options = "nosniff" +Referrer-Policy = "strict-origin-when-cross-origin" +Content-Security-Policy = "script-src localhost:1313" +{{< /code-toggle >}} + +Since this is "development only", it may make sense to put it below the `development` environment: + +{{< code-toggle file=config/development/server >}} +[[headers]] +for = "/**" + +[headers.values] +X-Frame-Options = "DENY" +X-XSS-Protection = "1; mode=block" +X-Content-Type-Options = "nosniff" +Referrer-Policy = "strict-origin-when-cross-origin" +Content-Security-Policy = "script-src localhost:1313" +{{< /code-toggle >}} + +You can also specify simple redirects rules for the server. The syntax is again similar to Netlify's. + +Note that a `status` code of 200 will trigger a [URL rewrite](https://docs.netlify.com/routing/redirects/rewrites-proxies/), which is what you want in SPA situations, e.g: + +{{< code-toggle file=config/development/server >}} +[[redirects]] +from = "/myspa/**" +to = "/myspa/" +status = 200 +force = false +{{< /code-toggle >}} + +Setting `force=true` will make a redirect even if there is existing content in the path. Note that before Hugo 0.76 `force` was the default behavior, but this is inline with how Netlify does it. + +## 404 server error page {#_404-server-error-page} + +{{< new-in 0.103.0 >}} + +Hugo will, by default, render all 404 errors when running `hugo server` with the `404.html` template. Note that if you have already added one or more redirects to your [server configuration](#configure-server), you need to add the 404 redirect explicitly, e.g: + +{{< code-toggle file=config/development/server >}} +[[redirects]] +from = "/**" +to = "/404.html" +status = 404 +{{< /code-toggle >}} + +## Configure title case + +By default, Hugo follows the capitalization rules published in the [Associated Press Stylebook] when creating automatic section titles, and when transforming strings with the [`strings.Title`] function. + +Change this behavior by setting `titleCaseStyle` in your site configuration to any of the values below: + +ap +: Use the capitalization rules published in the [Associated Press Stylebook]. + +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. + +[`strings.Title`]: /functions/strings/title +[Associated Press Stylebook]: https://www.apstylebook.com/ +[Chicago Manual of Style]: https://www.chicagomanualofstyle.org/home.html +[site configuration]: /getting-started/configuration/#configure-title-case + +## Configuration environment variables + +HUGO_NUMWORKERMULTIPLIER +: Can be set to increase or reduce the number of workers used in parallel processing in Hugo. If not set, the number of logical CPUs will be used. + - ## Configuration lookup order - - Similar to the template [lookup order], Hugo has a default set of rules for searching for a configuration file in the root of your website's source directory as a default behavior: - - 1. `./hugo.toml` - 2. `./hugo.yaml` - 3. `./hugo.json` - - In your configuration file, you can direct Hugo as to how you want your website rendered, control your website's menus, and arbitrarily define site-wide parameters specific to your project. - - ## Example configuration - - The following is a typical example of a configuration file. The values nested under `params:` will populate the [`.Site.Params`] variable for use in [templates]: - - {{< code-toggle file=hugo >}} - baseURL: "https://yoursite.example.com/" - title: "My Hugo Site" - permalinks: - posts: /:year/:month/:title/ - params: - Subtitle: "Hugo is Absurdly Fast!" - AuthorName: "Jon Doe" - GitHubUser: "spf13" - ListOfFoo: - - "foo1" - - "foo2" - SidebarRecentLimit: 5 - {{< /code-toggle >}} - +## Configure with environment variables + +In addition to the 3 configuration options already mentioned, configuration key-values can be defined through operating system environment variables. + +For example, the following command will effectively set a website's title on Unix-like systems: + +```txt +$ env HUGO_TITLE="Some Title" hugo +``` + +This is really useful if you use a service such as Netlify to deploy your site. Look at the Hugo docs [Netlify configuration file](https://github.com/gohugoio/hugoDocs/blob/master/netlify.toml) for an example. + +{{% note %}} +Names must be prefixed with `HUGO_` and the configuration key must be set in uppercase when setting operating system environment variables. + +To set configuration parameters, prefix the name with `HUGO_PARAMS_` +{{% /note %}} + +If you are using snake_cased variable names, the above will not work. Hugo determines the delimiter to use by the first character after `HUGO`. This allows you to define environment variables on the form `HUGOxPARAMSxAPI_KEY=abcdefgh`, using any [allowed](https://stackoverflow.com/questions/2821043/allowed-characters-in-linux-environment-variable-names#:~:text=So%20names%20may%20contain%20any,not%20begin%20with%20a%20digit.) delimiter. + +## Ignore content and data files when rendering + +{{% note %}} +This works, but we recommend you use the newer and more powerful [includeFiles and excludeFiles](/hugo-modules/configuration/#module-configuration-mounts) mount options. +{{% /note %}} + +To exclude specific files from the `content`, `data`, and `i18n` directories when rendering your site, set `ignoreFiles` to one or more regular expressions to match against the absolute file path. + +To ignore files ending with `.foo` or `.boo`: + +{{< code-toggle file=hugo >}} +ignoreFiles = ['\.foo$', '\.boo$'] +{{< /code-toggle >}} + +To ignore a file using the absolute file path: + +{{< code-toggle file=hugo >}} +ignoreFiles = ['^/home/user/project/content/test\.md$'] +{{< /code-toggle >}} + +## Configure front matter + +### Configure dates + +Dates are important in Hugo, and you can configure how Hugo assigns dates to your content pages. You do this by adding a `frontmatter` section to your `hugo.toml`. + +The default configuration is: + +{{< code-toggle config=frontmatter />}} + +If you, as an example, have a non-standard date parameter in some of your content, you can override the setting for `date`: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = ["myDate", ":default"] +{{< /code-toggle >}} + +The `:default` is a shortcut to the default settings. The above will set `.Date` to the date value in `myDate` if present, if not we will look in `date`,`publishDate`, `lastmod` and pick the first valid date. + +In the list to the right, values starting with ":" are date handlers with a special meaning (see below). The others are just names of date parameters (case insensitive) in your front matter configuration. Also note that Hugo have some built-in aliases to the above: `lastmod` => `modified`, `publishDate` => `pubdate`, `published` and `expiryDate` => `unpublishdate`. With that, as an example, using `pubDate` as a date in front matter, will, by default, be assigned to `.PublishDate`. + +The special date handlers are: + +`:fileModTime` +: Fetches the date from the content file's last modification timestamp. + +An example: + +{{< code-toggle file=hugo >}} +[frontmatter] +lastmod = ["lastmod", ":fileModTime", ":default"] +{{< /code-toggle >}} + +The above will try first to extract the value for `.Lastmod` starting with the `lastmod` front matter parameter, then the content file's modification timestamp. The last, `:default` should not be needed here, but Hugo will finally look for a valid date in `:git`, `date` and then `publishDate`. + +`:filename` +: Fetches the date from the content file's file name. For example, `2018-02-22-mypage.md` will extract the date `2018-02-22`. Also, if `slug` is not set, `mypage` will be used as the value for `.Slug`. + +An example: + +{{< code-toggle file=hugo >}} +[frontmatter] +date = [":filename", ":default"] +{{< /code-toggle >}} + +The above will try first to extract the value for `.Date` from the file name, then it will look in front matter parameters `date`, `publishDate` and lastly `lastmod`. + +`:git` +: This is the Git author date for the last revision of this content file. This will only be set if `--enableGitInfo` is set or `enableGitInfo = true` is set in site configuration. + +## Configure additional output formats + +Hugo v0.20 introduced the ability to render your content to multiple output formats (e.g., to JSON, AMP html, or CSV). See [Output Formats] for information on how to add these values to your Hugo project's configuration file. + +## Configure minify + ++See the [tdewolff/minify] project page for details. ++ ++[tdewolff/minify]: https://github.com/tdewolff/minify ++ +Default configuration: + +{{< code-toggle config=minify />}} + +## Configure file caches + +Since Hugo 0.52 you can configure more than just the `cacheDir`. This is the default configuration: + +{{< code-toggle config=caches />}} + +You can override any of these cache settings in your own `hugo.toml`. + +### The keywords explained + +cacheDir +: (`string`) See [Configure cacheDir](#configure-cachedir). + +project +: (`string`) The base directory name of the current Hugo project. This means that, in its default setting, every project will have separated file caches, which means that when you do `hugo --gc` you will not touch files related to other Hugo projects running on the same PC. + +resourceDir +: (`string`) This is the value of the `resourceDir` configuration option. + +maxAge +: (`string`) This is the duration before a cache entry will be evicted, -1 means forever and 0 effectively turns that particular cache off. Uses Go's `time.Duration`, so valid values are `"10s"` (10 seconds), `"10m"` (10 minutes) and `"10h"` (10 hours). + +dir +: (`string`) The absolute path to where the files for this cache will be stored. Allowed starting placeholders are `:cacheDir` and `:resourceDir` (see above). + - ## Configuration format specs - - - [TOML Spec][toml] - - [YAML Spec][yaml] - - [JSON Spec][json] - - [`.Site.Params`]: /variables/site/ - [directory structure]: /getting-started/directory-structure - [json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf - [lookup order]: /templates/lookup-order/ - [Output Formats]: /templates/output-formats/ - [templates]: /templates/ - [toml]: https://toml.io/en/latest - [yaml]: https://yaml.org/spec/ - [static-files]: /content-management/static-files/ - +## Configure cacheDir + +This is the directory where Hugo by default will store its file caches. See [Configure File Caches](#configure-file-caches). + +This can be set using the `cacheDir` config option or via the OS env variable `HUGO_CACHEDIR`. + +If this is not 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 vendors, please read their documentation. For an CircleCI example, see [this configuration](https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml). +1. In a `hugo_cache` directory below the OS user cache directory as defined by Go's [os.UserCacheDir](https://pkg.go.dev/os#UserCacheDir). On Unix systems, this is `$XDG_CACHE_HOME` as specified by [basedir-spec-latest](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) 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`. {{< new-in 0.116.0 >}} +1. In a `hugo_cache_$USER` directory below the OS temp dir. + +If you want to know the current value of `cacheDir`, you can run `hugo config`, e.g: `hugo config | grep cachedir`. + +[`time`]: /functions/time/astime ++[`.Site.Params`]: /variables/site/ ++[directory structure]: /getting-started/directory-structure ++[lookup order]: /templates/lookup-order/ ++[Output Formats]: /templates/output-formats/ ++[templates]: /templates/ ++[static-files]: /content-management/static-files/ diff --cc docs/content/en/getting-started/glossary.md index dce3d1527,000000000..929feb542 mode 100644,000000..100644 --- a/docs/content/en/getting-started/glossary.md +++ b/docs/content/en/getting-started/glossary.md @@@ -1,385 -1,0 +1,389 @@@ +--- +title: Glossary of terms +description: Terms commonly used throughout the documentation. +categories: [getting started] +keywords: [glossary] +menu: + docs: + parent: getting-started + weight: 60 +weight: 60 +# Use level 6 headings for each term in the glossary. +--- + +###### action + +See [template action](#template-action). + +###### archetype + +A template for new content. See [details](/content-management/archetypes/). + +###### argument + +A [scalar](#scalar), [array](#array), [slice](#slice), [map](#map), or [object](#object) passed to a [function](#function), [method](#method), or [shortcode](#shortcode). + +###### array + +A numbered sequence of elements. Unlike Go's [slice](#slice) data type, an array has a fixed length. [Elements](#element) within an array can be [scalars](#scalar), slices, [maps](#map), pages, or other arrays. See the [Go documentation](https://go.dev/ref/spec#Array_types) for details. + +###### bool + +See [boolean](#boolean). + +###### boolean + +A data type with two possible values, either `true` or `false`. + +###### branch bundle + +A [page bundle](#page-bundle) with an _index.md file and zero or more [resources](#resource). Analogous to a physical branch, a branch bundle may have descendants including regular pages, [leaf bundles](/getting-started/glossary/#leaf-bundle), and other branch bundles. See [details](/content-management/page-bundles/). + +###### build + +To generate a static site that includes HTML files and assets such as images, CSS, and JavaScript. The build process includes rendering and resource transformations. + +###### bundle + +See [page bundle](#page-bundle). + +###### cache + +A software component that stores data so that future requests for the same data are faster. + +###### chain + +Within a template, to connect one or more [identifiers](#identifier) with a dot. An identifier can represent a method, object, or field. For example, `.Site.Params.author.name` or `.Date.UTC.Hour`. + +###### collection + +An [array](#array), [slice](#slice), or [map](#map). + +###### content format + +A markup language for creating content. Typically markdown, but may also be HTML, AsciiDoc, Org, Pandoc, or reStructuredText. See [details](/content-management/formats/). + +###### content type + +A classification of content inferred from the top-level directory name or the `type` set in [front matter](#front-matter). Pages in the root of the content directory, including the home page, are of type "page". Accessed via `.Page.Type` in [templates](#template). See [details](/content-management/types/). + +###### content view + +A template called with the `.Page.Render` method. See [details](/templates/views/). + +###### context + +Represented by a dot "." within a [template action](#template-action), context is the current location in a data structure. For example, while iterating over a [collection](#collection) of pages, the context within each iteration is the page's data structure. The context received by each template depends on template type and/or how it was called. See [details](/templates/introduction/#the-dot). + +###### default sort order + +The default sort order for page collections. Hugo sorts by [weight](#weight), then by date (descending), then by link title, and then by file path. + +###### element + +A member of a slice or array. + +###### environment + +Typically one of `development`, `staging`, or `production`, each environment may exhibit different behavior depending on configuration and template logic. For example, in a production environment you might minify and fingerprint CSS, but that probably doesn't make sense in a development environment. + +When running the built-in development server with the `hugo server` command, the environment is set to `development`. When building your site with the `hugo` command, the environment is set to `production`. To override the environment value, use the `--environment` command line flag. + +To determine the current environment within a template, use the [`hugo.Environment`] function. + +[`hugo.Environment`]: /functions/hugo/environment + +###### field + +A predefined key/value pair in front matter such as `date` or `title`. See also [parameter](#parameter). + + +###### flag + +An option passed to a command-line program, beginning with one or two hyphens. See [details](/commands/hugo/). + +###### float + +See [floating point](#floating-point). + +###### floating point + +A numeric data type with a fractional component. For example, `3.14159`. + +###### fragment + +The final segment of a URL, beginning with a hash (`#`) mark, that references an `id` attribute of an HTML element on the page. + +###### front matter + +Metadata at the beginning of each content page, separated from the content by format-specific delimiters. See [details](/content-management/front-matter/). + +###### function + +Used within a [template action](#template-action), a function takes one or more [arguments](#argument) and returns a value. Unlike [methods](#method), functions are not associated with an [object](#object). See [details](/functions/). + +###### global resource + +A file within the assets directory, or within any directory [mounted](/hugo-modules/configuration/#module-configuration-mounts) to the assets directory. Capture one or more global resources using the [`resources.Get`], [`resources.GetMatch`], [`resources.Match`], or [`resources.ByType`] functions. + +[`resources.Get`]: /functions/resources/get +[`resources.GetMatch`]: /functions/resources/getmatch +[`resources.Match`]: /functions/resources/match +[`resources.ByType`]: /functions/resources/byType + +###### identifier + +A string that represents a variable, method, object, or field. It must conform to Go's [language specification](https://go.dev/ref/spec#Identifiers), beginning with a letter or underscore, followed by zero or more letters, digits, or underscores. + +###### int + +See [integer](#integer). + +###### integer + +A numeric data type without a fractional component. For example, `42`. + +###### internationalization + +Software design and development efforts that enable [localization](#localization). See the [W3C definition](https://www.w3.org/International/questions/qa-i18n). Abbreviated i18n. + +###### interval + +An [interval](https://en.wikipedia.org/wiki/Interval_(mathematics)) is a range of numbers between two endpoints: closed, open, or half-open. + +- A _closed_ interval, denoted by brackets, includes its endpoints. For example, [0, 1] is the interval where `0 <= x <= 1`. + - - An _open_ interval, denoted by parenthesis, excludes its endpoints. For example, (0, 1) is the interval where `0 < x < 1`. ++- An _open_ interval, denoted by parentheses, excludes its endpoints. For example, (0, 1) is the interval where `0 < x < 1`. + +- A _half-open_ interval includes only one of its endpoints. For example, (0, 1] is the _left-open_ interval where `0 < x <= 1`, while [0, 1) is the _right-open_ interval where `0 <= x < 1`. + +###### kind + +See [page kind](#page-kind). + +###### layout + +See [template](#template). + +###### leaf bundle + +A [page bundle](#page-bundle) with an index.md file and zero or more [resources](#resource). Analogous to a physical leaf, a leaf bundle is at the end of a branch. Hugo ignores content (but not resources) beneath the leaf bundle. See [details](/content-management/page-bundles/). + +###### list page + +Any [page kind](#page-kind) that receives a page [collection](#collection) in [context](#context). This includes the home page, [section pages](#section-page), [taxonomy pages](#taxonomy-page), and [term pages](#term-page). + +###### localization + +Adaptation of a site to meet language and regional requirements. This includes translations, language-specific media, date and currency formats, etc. See [details](/content-management/multilingual/) and the [W3C definition](https://www.w3.org/International/questions/qa-i18n). Abbreviated l10n. + +###### map + +An unordered group of elements, each indexed by a unique key. See the [Go documentation](https://go.dev/ref/spec#Map_types) for details. + +###### markdown attribute + +A list of attributes, containing one or more key/value pairs, separated by spaces or commas, and wrapped by braces. Apply markdown attributes to images and block-level elements including blockquotes, fenced code blocks, headings, horizontal rules, lists, paragraphs, and tables. See [details](/getting-started/configuration-markup/#goldmark). + +###### marshal + +To transform a data structure into a serialized object. For example, transforming a [map](#map) into a JSON string. See [unmarshal](#unmarshal). + +###### method + +Used within a [template action](#template-action) and associated with an [object](#object), a method takes zero or more [arguments](#argument) and either returns a value or performs an action. For example, `.IsHome` is a method on the `.Page` object which returns `true` if the current page is the home page. See also [function](#function). + +###### module + +Like a [theme](#theme), a module is a packaged combination of [archetypes](#archetype), assets, content, data, [templates](#template), translation tables, static files, or configuration settings. A module may serve as the basis for a new site, or to augment an existing site. See [details](/hugo-modules/). + +###### object + +A data structure with or without associated [methods](#method). + +###### ordered taxonomy + +Created by invoking the [`Alphabetical`] or [`ByCount`] method on a [taxonomy object](#taxonomy-object), which is a [map](#map), an ordered taxonomy is a [slice](#slice), where each element is an object that contains the [term](#term) and a slice of its [weighted pages](#weighted-page). + +[`Alphabetical`]: /methods/taxonomy/alphabetical +[`ByCount`]: /methods/taxonomy/bycount + +###### output format + +{{% include "methods/page/_common/output-format-definition.md" %}} + +###### page bundle + +A directory that encapsulates both content and associated [resources](#resource). There are two types of page bundles: [leaf bundles](#leaf-bundle) and [branch bundles](#branch-bundle). See [details](/content-management/page-bundles/). + ++###### page collection ++ ++A slice of page objects. ++ +###### page kind + +A classification of pages, one of `home`, `page`, `section`, `taxonomy`, or `term`. See [details](/templates/section-templates/#page-kinds). + +Note that there are also `RSS`, `sitemap`, `robotsTXT`, and `404` page kinds, but these are only available during the rendering of each of these respective page's kind and therefore *not* available in any of the `Pages` collections. + +###### page resource + +A file within a [page bundle](#page-bundle). Capture one or more page resources using any of the [`Resources`] methods on a `Page` object. + +[`Resources`]: /methods/page/resources/#methods + +###### pager + +Created during [pagination](#pagination), a pager contains a subset of a section list, and navigation links to other pagers. + +###### paginate + +To split a [section](#section) list into two or more [pagers](#pager) See [details](/templates/pagination/). + +###### pagination + +The process of [paginating](#paginate) a [section](#section) list. + +###### parameter + +Typically, a user-defined key/value pair at the site or page level, but may also refer to a configuration setting or an [argument](#argument). See also [field](#field). + +###### partial + +A [template](#template) called from any other template including [shortcodes](#shortcode), [render hooks](#render-hook), and other partials. A partial either renders something or returns something. A partial can also call itself, for example, to [walk](#walk) a data structure. + +###### permalink + +The absolute URL of a published resource or a rendered page, including scheme and host. + +###### pipe + +See [pipeline](#pipeline). + +###### pipeline + +Within a [template action](#template-action), a pipeline is a possibly chained sequence of values, [function](#function) calls, or [method](#method) calls. Functions and methods in the pipeline may take multiple [arguments](#argument). + +A pipeline may be *chained* by separating a sequence of commands with pipeline characters "|". In a chained pipeline, the result of each command is passed as the last argument to the following command. The output of the final command in the pipeline is the value of the pipeline. See the [Go documentation](https://pkg.go.dev/text/template#hdr-Pipelines) for details. + +###### publish + +See [build](#build). + +###### regular page + +Content with the "page" [page kind](#page-kind). See also [section page](#section-page). + +###### relative permalink + +The host-relative URL of a published resource or a rendered page. + +###### render hook + +A [template](#template) that overrides standard markdown rendering. See [details](/templates/render-hooks/). + +###### remote resource + +A file on a remote server, accessible via HTTP or HTTPS with the [`resources.GetRemote`](/functions/resources/getremote) function. + +###### resource + +Any file consumed by the build process to augment or generate content, structure, behavior, or presentation. For example: images, videos, content snippets, CSS, Sass, JavaScript, and data. + +Hugo supports three types of resources: [global](#global-resource), [page](#page-resource), and [remote](#remote-resource) + +###### scalar + +A single value, one of [string](#string), [integer](#integer), [floating point](#floating-point), or [boolean](#boolean). + +###### scratch pad + +Conceptually, a [map](#map) with [methods](#method) to set, get, update, and delete values. Attach the data structure to a `Page` object using the [`Scratch`] or [`Store`] methods, or created a locally scoped scratch pad using the [`newScratch`] function. + +[`Scratch`]: /methods/page/scratch +[`Store`]: /methods/page/store +[`newScratch`]: /functions/collections/newscratch + +###### section + +A top-level content directory, or any content directory with an _index.md file. A content directory with an _index.md file is also known as a [branch bundle](/getting-started/glossary/#branch-bundle). Section templates receive one or more page [collections](#collection) in [context](#context). See [details](/content-management/sections/). + +###### section page + +Content with the "section" [page kind](#page-kind). Typically a listing of [regular pages](#regular-page) and/or [section pages](#section-page) within the current [section](#section). See also [regular page](#regular-page). + +###### shortcode + +A [template](#template) called from within markdown, taking zero or more [arguments](#argument). See [details](/content-management/shortcodes/). + +###### slice + +A numbered sequence of elements. Unlike Go's [array](#array) data type, slices are dynamically sized. [Elements](#element) within a slice can be [scalars](#scalar), [arrays](#array), [maps](#map), pages, or other slices. See the [Go documentation](https://go.dev/ref/spec#Slice_types) for details. + +###### string + +A sequence of bytes. For example, `"What is 6 times 7?"` . + +###### taxonomic weight + +Defined in front matter and unique to each taxonomy, this [weight](#weight) determines the sort order of page collections contained within a [taxonomy object](#taxonomy-object). See [details](/templates/taxonomy-templates/#assign-weight). + +###### taxonomy + +A group of related [terms](#term) used to classify content. For example, a "colors" taxonomy might include the terms "red", "green", and "blue". See [details](/content-management/taxonomies/). + +###### taxonomy object + +A [map](#map) of [terms](#term) and the [weighted pages](#weighted-page) associated with each term. + +###### taxonomy page + +Content with the "taxonomy" [page kind](#page-kind). Typically a listing of [terms](#term) within a given [taxonomy](#taxonomy). + +###### template + +A file with [template actions](#template-action), located within the layouts directory of a project, theme, or module. See [details](/templates/). + +###### template action + +A data evaluation or control structure within a [template](#template), delimited by "{{" and "}}". See the [Go documentation](https://pkg.go.dev/text/template#hdr-Actions) for details. + +###### term + +A member of a [taxonomy](#taxonomy), used to classify content. See [details](/content-management/taxonomies/). + +###### term page + +Content with the "term" [page kind](#page-kind). Typically a listing of [regular pages](#regular-page) and [section pages](#section-page) with a given [term](#term). + +###### theme + +A packaged combination of [archetypes](#archetype), assets, content, data, [templates](#template), translation tables, static files, or configuration settings. A theme may serve as the basis for a new site, or to augment an existing site. See also [module](#module). + +###### token + +An identifier within a format string, beginning with a colon and replaced with a value when rendered. For example, use tokens in format strings for both [permalinks](/content-management/urls/#permalinks) and [dates](/functions/time/format/#localization). + +###### type + +See [content type](#content-type). + +###### unmarshal + +To transform a serialized object into a data structure. For example, transforming a JSON file into a [map](#map) that you can access within a template. See [marshal](#marshal). + +###### variable + +A user-defined [identifier](#identifier) prefaced with a `$` symbol, representing a value of any data type, initialized or assigned within a [template action](#template-action). For example, `$foo` and `$bar` are variables. + +###### walk + +To recursively traverse a nested data structure. For example, rendering a multilevel menu. + +###### weight + +Used to position an element within a collection sorted by weight. Assign weights using non-zero integers. Lighter items float to the top, while heavier items sink to the bottom. Unweighted or zero-weighted elements are placed at the end of the collection. Weights are typically assigned to pages, menu entries, languages, and output formats. + +###### weighted page + +Contained within a [taxonomy object](#taxonomy-object), a weighted page is a [map](#map) with two elements: a `Page` object, and its [taxonomic weight](#taxonomic-weight) as defined in front matter. Access the elements using the `Page` and `Weight` keys. diff --cc docs/content/en/getting-started/quick-start.md index ce4312455,000000000..a6c54b54c mode 100644,000000..100644 --- a/docs/content/en/getting-started/quick-start.md +++ b/docs/content/en/getting-started/quick-start.md @@@ -1,225 -1,0 +1,232 @@@ +--- +title: Quick start +description: Learn to create a Hugo site in minutes. +categories: [getting started] +keywords: [quick start,usage] +menu: + docs: + parent: getting-started + weight: 20 +weight: 20 +toc: true +aliases: [/quickstart/,/overview/quickstart/] ++minVersion: v0.112.0 +--- + +In this tutorial you will: + +1. Create a site +2. Add content +3. Configure the site +4. Publish the site + +## Prerequisites + +Before you begin this tutorial you must: + - 1. [Install Hugo] (extended edition, v0.112.0 or later) ++1. [Install Hugo] (extended 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]. + +[PowerShell]: https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows +[are different applications]: https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.3 +{{% /note %}} + ++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. + +```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 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: 2022-11-20T09:03:20-08:00 - draft: true - --- +++++ ++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. + +[markdown]: https://commonmark.org/help/ + +```text - --- - title: "My First Post" - date: 2022-11-20T09:03:20-08:00 - draft: true - --- +++++ ++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. + +{{% 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. + +[live testing tool]: https://spec.commonmark.org/dingus/ +[specification]: https://spec.commonmark.org/ +{{% /note %}} + +## 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. + +2. Set the `languageCode` to your language and region. + +3. 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]. + +[demonstration site]: https://gohugo-ananke-theme-demo.netlify.app/ +[documentation]: https://github.com/theNewDynamic/gohugo-theme-ananke#readme +[The New Dynamic]: https://www.thenewdynamic.com/ +{{% /note %}} + +## 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 [hosting and deployment] 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 +[directory structure]: /getting-started/directory-structure +[draft, future, and expired content]: /getting-started/usage/#draft-future-and-expired-content +[draft, future, or expired content]: /getting-started/usage/#draft-future-and-expired-content +[external learning resources]:/getting-started/external-learning-resources/ +[forum]: https://discourse.gohugo.io/ +[forum]: https://discourse.gohugo.io/ +[front matter]: /content-management/front-matter +[Git submodule]: https://git-scm.com/book/en/v2/Git-Tools-Submodules +[hosting and deployment]: /hosting-and-deployment/ +[Install Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[Install Hugo]: /installation/ +[Requesting Help]: https://discourse.gohugo.io/t/requesting-help/9132 +[Requesting Help]: https://discourse.gohugo.io/t/requesting-help/9132 +[site configuration]: /getting-started/configuration/ diff --cc docs/content/en/hosting-and-deployment/hosting-on-github/index.md index f41250279,000000000..24bd31a25 mode 100644,000000..100644 --- a/docs/content/en/hosting-and-deployment/hosting-on-github/index.md +++ b/docs/content/en/hosting-and-deployment/hosting-on-github/index.md @@@ -1,190 -1,0 +1,190 @@@ +--- +title: Host on GitHub Pages +description: Deploy Hugo as a GitHub Pages project or personal/organizational site and automate the whole process with GitHub Actions +categories: [hosting and deployment] +keywords: [hosting,github] +menu: + docs: + parent: hosting-and-deployment +toc: true +aliases: [/tutorials/github-pages-blog/] +--- + +GitHub provides free and fast static hosting over SSL for personal, organization, or project pages directly from a GitHub repository via its GitHub Pages service and automating development workflows and build with GitHub Actions. + +## Prerequisites + +1. [Create a GitHub account] +2. [Install Git] +3. [Create a Hugo site] and test it locally with `hugo server`. + +[Create a GitHub account]: https://github.com/signup +[Install Git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[Create a Hugo site]: /getting-started/quick-start/ + +## Types of sites + +There are three types of GitHub Pages sites: project, user, and organization. Project sites are connected to a specific project hosted on GitHub. User and organization sites are connected to a specific account on GitHub.com. + +{{% note %}} +See the [GitHub Pages documentation] to understand the requirements for repository ownership and naming. + +[GitHub Pages documentation]: https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages#types-of-github-pages-sites +{{% /note %}} + +[GitHub Pages documentation]: https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages#types-of-github-pages-sites + +## Procedure + +Step 1 +: Create a GitHub repository. + +Step 2 +: Push your local repository to GitHub. + +Step 3 +: 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-1.png) +{style="max-width: 280px"} + +Step 4 +: Change the **Source** to `GitHub Actions`. The change is immediate; you do not have to press a Save button. + +![screen capture](gh-pages-2.png) +{style="max-width: 280px"} + +Step 5 +: Create an empty file in your local repository. + +```text +.github/workflows/hugo.yaml +``` + +Step 6 +: Copy and paste the YAML below into the file you created. Change the branch name and Hugo version as needed. + +{{< code file=.github/workflows/hugo.yaml copy=true >}} +# Sample workflow for building and deploying a Hugo site to GitHub Pages +name: Deploy Hugo site to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: + - main + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +# Default to bash +defaults: + run: + shell: bash + +jobs: + # Build job + build: + runs-on: ubuntu-latest + env: - HUGO_VERSION: 0.120.2 ++ HUGO_VERSION: 0.121.0 + steps: + - name: Install Hugo CLI + run: | + wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \ + && sudo dpkg -i ${{ runner.temp }}/hugo.deb + - name: Install Dart Sass + run: sudo snap install dart-sass + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: recursive + fetch-depth: 0 + - name: Setup Pages + id: pages - uses: actions/configure-pages@v3 ++ uses: actions/configure-pages@v4 + - name: Install Node.js dependencies + run: "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true" + - name: Build with Hugo + env: + # For maximum backward compatibility with Hugo modules + HUGO_ENVIRONMENT: production + HUGO_ENV: production + run: | + hugo \ + --gc \ + --minify \ + --baseURL "${{ steps.pages.outputs.base_url }}/" + - name: Upload artifact + uses: actions/upload-pages-artifact@v2 + with: + path: ./public + + # Deployment job + 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@v2 ++ uses: actions/deploy-pages@v3 +{{< /code >}} + +Step 7 +: Commit the change to your local repository with a commit message of something like "Add workflow", and push to GitHub. + +Step 8 +: From GitHub's main menu, choose **Actions**. You will see something like this: + +![screen capture](gh-pages-3.png) +{style="max-width: 350px"} + +Step 9 +: When GitHub has finished building and deploying your site, the color of the status indicator will change to green. + +![screen capture](gh-pages-4.png) +{style="max-width: 350px"} + +Step 10 +: Click on the commit message as shown above. You will see this: + +![screen capture](gh-pages-5.png) +{style="max-width: 611px"} + +Under the deploy step, you will see a link to your live site. + +In the future, whenever you push a change from your local repository, GitHub will rebuild your site and deploy the changes. + +## 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. + +[Dart Sass]: /hugo-pipes/transpile-sass-to-css/#dart-sass + +## Additional 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) diff --cc docs/content/en/hosting-and-deployment/hosting-on-gitlab.md index dce306253,000000000..74b1fa154 mode 100644,000000..100644 --- a/docs/content/en/hosting-and-deployment/hosting-on-gitlab.md +++ b/docs/content/en/hosting-and-deployment/hosting-on-gitlab.md @@@ -1,101 -1,0 +1,101 @@@ +--- +title: Host on GitLab Pages +description: GitLab makes it easy to build, deploy, and host your Hugo website via their free GitLab Pages service, which provides native support for Hugo. +categories: [hosting and deployment] +keywords: [hosting,gitlab] +menu: + docs: + parent: hosting-and-deployment +toc: true +aliases: [/tutorials/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](/getting-started/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](https://docs.gitlab.com/ee/ci/quick_start/) jobs by creating a `.gitlab-ci.yml` file in the root of your project. + +{{< code file=.gitlab-ci.yml copy=true >}} +variables: - DART_SASS_VERSION: 1.64.1 - HUGO_VERSION: 0.115.4 ++ DART_SASS_VERSION: 1.69.5 ++ HUGO_VERSION: 0.121.0 + NODE_VERSION: 20.x + GIT_DEPTH: 0 + GIT_STRATEGY: clone + GIT_SUBMODULE_STRATEGY: recursive + TZ: America/Los_Angeles + +image: + name: golang:1.20.6-bookworm + +pages: + script: + # Install brotli + - apt-get update + - apt-get install -y brotli + # Install Dart Sass + - curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz + - tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz + - cp -r dart-sass/ /usr/local/bin + - rm -rf dart-sass* + - export PATH=/usr/local/bin/dart-sass:$PATH + # Install Hugo + - curl -LJO https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb + - apt-get install -y ./hugo_extended_${HUGO_VERSION}_linux-amd64.deb + - rm hugo_extended_${HUGO_VERSION}_linux-amd64.deb + # Install Node.js + - curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION} | bash - + - apt-get install -y nodejs + # Install Node.js dependencies + - "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true" + # Build + - hugo --gc --minify + # Compress + - find public -type f -regex '.*\.\(css\|html\|js\|txt\|xml\)$' -exec gzip -f -k {} \; + - find public -type f -regex '.*\.\(css\|html\|js\|txt\|xml\)$' -exec brotli -f -k {} \; + artifacts: + paths: + - public + rules: + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH +{{% /code %}} + +## 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/hosting-and-deployment/hosting-on-netlify.md index 9b01f4cd8,000000000..ac6202700 mode 100644,000000..100644 --- a/docs/content/en/hosting-and-deployment/hosting-on-netlify.md +++ b/docs/content/en/hosting-and-deployment/hosting-on-netlify.md @@@ -1,145 -1,0 +1,145 @@@ +--- +title: Host on Netlify +description: Netlify can host your Hugo site with CDN, continuous deployment, 1-click HTTPS, an admin GUI, and its own CLI. +categories: [hosting and deployment] +keywords: [hosting,netlify] +menu: + docs: + parent: hosting-and-deployment +toc: true +--- + +[Netlify][netlify] provides continuous deployment services, global CDN, ultra-fast DNS, atomic deploys, instant cache invalidation, one-click SSL, a browser-based interface, a CLI, and many other features for managing your Hugo website. + +## Assumptions + +* You have an account with GitHub, GitLab, or Bitbucket. +* You have completed the [Quick Start] or have a Hugo website you are ready to deploy and share with the world. +* You do not already have a Netlify account. + +## Create a Netlify account + +Go to [app.netlify.com] and select your preferred sign up method. This will likely be a hosted Git provider, although you also have the option to sign up with an email address. + +The following examples use GitHub, but other git providers will follow a similar process. + +![Screenshot of the homepage for app.netlify.com, containing links to the most popular hosted git solutions.](/images/hosting-and-deployment/hosting-on-netlify/netlify-signup.jpg) + +Selecting GitHub will bring up an authorization modal for authentication. Select "Authorize application." + +![Screenshot of the authorization popup for Netlify and GitHub.](/images/hosting-and-deployment/hosting-on-netlify/netlify-first-authorize.jpg) + +## Create a new site with continuous deployment + +You're now already a Netlify member and should be brought to your new dashboard. Select "New site from git." + +![Screenshot of the blank Netlify admin panel with no sites and highlighted 'add new site' button'](/images/hosting-and-deployment/hosting-on-netlify/netlify-add-new-site.jpg) + +Netlify will then start walking you through the steps necessary for continuous deployment. First, you'll need to select your git provider again, but this time you are giving Netlify added permissions to your repositories. + +![Screenshot of step 1 of create a new site for Netlify: selecting the git provider](/images/hosting-and-deployment/hosting-on-netlify/netlify-create-new-site-step-1.jpg) + +And then again with the GitHub authorization modal: + +![Screenshot of step 1 of create a new site for Netlify: selecting the git provider](/images/hosting-and-deployment/hosting-on-netlify/netlify-authorize-added-permissions.jpg) + +Select the repo you want to use for continuous deployment. If you have a large number of repositories, you can filter through them in real time using repo search: + +![Screenshot of step 1 of create a new site for Netlify: selecting the git provider](/images/hosting-and-deployment/hosting-on-netlify/netlify-create-new-site-step-2.jpg) + +Once selected, you'll be brought to a screen for basic setup. Here you can select the branch you want to publish, your [build command], and your publish (i.e. deploy) directory. The publish directory should mirror that of what you've set in your [site configuration], the default of which is `public`. The following steps assume you are publishing from the `master` branch. + +## Configure Hugo version in Netlify + +You can [set Hugo version](https://www.netlify.com/blog/2017/04/11/netlify-plus-hugo-0.20-and-beyond/) for your environments in `netlify.toml` file or set `HUGO_VERSION` as a build environment variable in the Netlify console. + +For production: + +{{< code file=netlify.toml >}} +[context.production.environment] - HUGO_VERSION = "0.115.4" ++ HUGO_VERSION = "0.121.0" +{{< /code >}} + +For testing: + +{{< code file=netlify.toml >}} +[context.deploy-preview.environment] - HUGO_VERSION = "0.115.4" ++ HUGO_VERSION = "0.121.0" +{{< /code >}} + +The Netlify configuration file can be a little hard to understand and get right for the different environment, and you may get some inspiration and tips from this site's `netlify.toml`: + +{{< readfile file=netlify.toml highlight=toml >}} + +## Build and deploy site + +In the Netlify console, selecting "Deploy site" will immediately take you to a terminal for your build:. + +![Animated gif of deploying a site to Netlify, including the terminal read out for the build.](/images/hosting-and-deployment/hosting-on-netlify/netlify-deploying-site.gif) + +Once the build is finished---this should only take a few seconds--you should now see a "Hero Card" at the top of your screen letting you know the deployment is successful. The Hero Card is the first element that you see in most pages. It allows you to see a quick summary of the page and gives access to the most common/pertinent actions and information. You'll see that the URL is automatically generated by Netlify. You can update the URL in "Settings." + +![Screenshot of successful deploy badge at the top of a deployments screen from within the Netlify admin.](/images/hosting-and-deployment/hosting-on-netlify/netlify-deploy-published.jpg) + +![Screenshot of homepage to https://hugo-netlify-example.netlify.com, which is mostly dummy text](/images/hosting-and-deployment/hosting-on-netlify/netlify-live-site.jpg) + +[Visit the live site][visit]. + +Now every time you push changes to your hosted git repository, Netlify will rebuild and redeploy your site. + +See [this blog post](https://www.netlify.com/blog/2017/04/11/netlify-plus-hugo-0.20-and-beyond/) for more details about how Netlify handles Hugo versions. + +## Use Hugo themes with Netlify + +The `git clone` method for installing themes is not supported by Netlify. If you were to use `git clone`, it would require you to recursively remove the `.git` subdirectory from the theme folder and would therefore prevent compatibility with future versions of the theme. + +A *better* approach is to install a theme as a proper git submodule. You can [read the GitHub documentation for submodules][ghsm] or those found on [Git's website][gitsm] for more information, but the command is similar to that of `git clone`: + +```txt +cd themes +git submodule add https://github.com// +``` + +It is recommended to only use stable versions of a theme (if it’s versioned) and always check the changelog. This can be done by checking out a specific release within the theme's directory. + +Switch to the theme's directory and list all available versions: + +```txt +cd themes/ +git tag +# exit with q +``` + +You can checkout a specific version as follows: + +```txt +git checkout tags/ +``` + +You can update a theme to the latest version by executing the following command in the *root* directory of your project: + +```txt +git submodule update --rebase --remote +``` + +## Next steps + +You now have a live website served over HTTPS, distributed through CDN, and configured for continuous deployment. Dig deeper into the Netlify documentation: + +1. [Using a Custom Domain] +2. [Setting up HTTPS on Custom Domains][httpscustom] +3. [Redirects and Rewrite Rules] + +[app.netlify.com]: https://app.netlify.com +[build command]: /getting-started/usage/#build-your-site +[site configuration]: /getting-started/configuration/ +[ghsm]: https://github.com/blog/2104-working-with-submodules +[gitsm]: https://git-scm.com/book/en/v2/Git-Tools-Submodules +[httpscustom]: https://www.netlify.com/docs/ssl/ +[hugoversions]: https://github.com/netlify/build-image/blob/master/Dockerfile#L216 +[netlify]: https://www.netlify.com/ +[netlifysignup]: https://app.netlify.com/signup +[Quick Start]: /getting-started/quick-start/ +[Redirects and Rewrite Rules]: https://www.netlify.com/docs/redirects/ +[Using a Custom Domain]: https://www.netlify.com/docs/custom-domains/ +[visit]: https://hugo-netlify-example.netlify.com diff --cc docs/content/en/hugo-modules/configuration.md index d707e7498,000000000..ce9e97d81 mode 100644,000000..100644 --- a/docs/content/en/hugo-modules/configuration.md +++ b/docs/content/en/hugo-modules/configuration.md @@@ -1,180 -1,0 +1,181 @@@ +--- +title: Configure Hugo modules +description: This page describes the configuration options for a module. +categories: [hugo modules] +keywords: [modules,themes] +menu: + docs: + parent: modules + weight: 20 +weight: 20 +toc: true +--- + +## Module configuration: top level + +{{< code-toggle file=hugo >}} +[module] - noVendor = "" - proxy = "direct" - noProxy = "none" - private = "*.*" - replacements = "" - workspace = "off" ++noProxy = 'none' ++noVendor = '' ++private = '*.*' ++proxy = 'direct' ++replacements = '' ++vendorClosest = false ++workspace = 'off' +{{< /code-toggle >}} + ++noProxy ++: Comma separated glob list matching paths that should not use the proxy configured above. ++ +noVendor +: A optional Glob pattern matching module paths to skip when vendoring, e.g. "github.com/**" + - vendorClosest - : When enabled, we will 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. ++private ++: Comma separated glob list matching paths that should be treated as private. + +proxy +: Defines the proxy server to use to download remote modules. Default is `direct`, which means "git clone" and similar. + - noProxy - : Comma separated glob list matching paths that should not use the proxy configured above. - - private - : Comma separated glob list matching paths that should be treated as private. ++vendorClosest ++: When enabled, we will 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. + +workspace +: The workspace file to use. This enables Go workspace mode. Note that this can also be set via OS env, e.g. `export HUGO_MODULE_WORKSPACE=/my/hugo.work` This only works with Go 1.18+. In Hugo `v0.109.0` we changed the default to `off` and we now resolve any relative work file names relative to the working directory. + +replacements +: A comma-separated list of mappings from module paths to directories, e.g. `github.com/bep/my-theme -> ../..,github.com/bep/shortcodes -> /some/path`. This is mostly useful for temporary local development of a module, in which case you might want to save it as an environment variable, e.g: `env HUGO_MODULE_REPLACEMENTS="github.com/bep/my-theme -> ../.."`. Relative paths are relative to [themesDir](/getting-started/configuration/#all-configuration-settings). Absolute paths are allowed. + +Note that the above terms maps directly to their counterparts in Go Modules. Some of these setting may be natural to set as OS environment variables. To set the proxy server to use, as an example: + +```txt +env HUGO_MODULE_PROXY=https://proxy.example.org hugo +``` + +{{< gomodules-info >}} + +## Module configuration: hugoVersion + +If your module requires a particular version of Hugo to work, you can indicate that in the `module` section and the user will be warned if using a too old/new version. + +{{< code-toggle file=hugo >}} +[module] +[module.hugoVersion] + min = "" + max = "" + extended = false + +{{< /code-toggle >}} + +Any of the above can be omitted. + +min +: The minimum Hugo version supported, e.g. `0.55.0` + +max +: The maximum Hugo version supported, e.g. `0.55.0` + +extended +: Whether the extended version of Hugo is required. + +## Module configuration: imports + +{{< code-toggle file=hugo >}} +[module] +[[module.imports]] + path = "github.com/gohugoio/hugoTestModules1_linux/modh1_2_1v" + ignoreConfig = false + ignoreImports = false + disable = false +[[module.imports]] + path = "my-shortcodes" +{{< /code-toggle >}} + +path +: Can be either a valid Go Module module path, e.g. `github.com/gohugoio/myShortcodes`, or the directory name for the module as stored in your themes folder. + +ignoreConfig +: If enabled, any module configuration file, e.g. `hugo.toml`, will not be loaded. Note that this will also stop the loading of any transitive module dependencies. + +ignoreImports +: If enabled, module imports will not be followed. + +disable +: Set to `true` to disable the module while keeping any version info in the `go.*` files. + +noMounts +: Do not mount any folder in this import. + +noVendor +: Never vendor this import (only allowed in main project). + +{{< gomodules-info >}} + +## Module configuration: mounts + +{{% note %}} +When the `mounts` configuration was introduced in Hugo 0.56.0, we were careful to preserve the existing `contentDir`, `staticDir`, and similar configuration to make sure all existing sites just continued to work. But you should not have both: if you add a `mounts` section you should remove the old `contentDir`, `staticDir`, etc. settings. +{{% /note %}} + +{{% note %}} +When you add a mount, the default mount for the concerned target root is ignored: be sure to explicitly add it. +{{% /note %}} + +**Default mounts** +{{< code-toggle file=hugo >}} +[module] +[[module.mounts]] + source="content" + target="content" +[[module.mounts]] + source="static" + target="static" +[[module.mounts]] + source="layouts" + target="layouts" +[[module.mounts]] + source="data" + target="data" +[[module.mounts]] + source="assets" + target="assets" +[[module.mounts]] + source="i18n" + target="i18n" +[[module.mounts]] + source="archetypes" + target="archetypes" +{{< /code-toggle >}} + +source +: The source directory of the mount. For the main project, this can be either project-relative or absolute and even a symbolic link. For other modules it must be project-relative. + +target +: Where it should be mounted into Hugo's virtual filesystem. It must start with one of Hugo's component folders: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, or `archetypes`. E.g. `content/blog`. + +lang +: The language code, e.g. "en". Only relevant for `content` mounts, and `static` mounts when in multihost mode. + +includeFiles (string or slice) +: One or more [glob](https://github.com/gobwas/glob) 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 to the file names starting from the `source` root, they should have Unix styled slashes even on Windows, `/` matches the mount root and `**` can be used as a super-asterisk to match recursively down all directories, e.g `/posts/**.jpg`. + +The search is case-insensitive. + +excludeFiles (string or slice) +: One or more glob 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 >}} diff --cc docs/content/en/hugo-modules/use-modules.md index 9e8f1d4d0,000000000..295ff2061 mode 100644,000000..100644 --- a/docs/content/en/hugo-modules/use-modules.md +++ b/docs/content/en/hugo-modules/use-modules.md @@@ -1,161 -1,0 +1,161 @@@ +--- +title: Use Hugo Modules +description: How to use Hugo Modules to build and manage your site. +categories: [hugo modules] +keywords: [modules,themes] +menu: + docs: + parent: modules + weight: 30 +weight: 30 +aliases: [/themes/usage/,/themes/installing/,/installing-and-using-themes/] +toc: true +--- + +## Prerequisite + +{{< gomodules-info >}} + +## Initialize a new module + +Use `hugo mod init` to initialize a new Hugo Module. If it fails to guess the module path, you must provide it as an argument, e.g.: + +```sh +hugo mod init github.com/gohugoio/myShortcodes +``` + +Also see the [CLI Doc](/commands/hugo_mod_init/). + +## Use a module for a theme + +The easiest way to use a Module for a theme is to import it in the configuration. + +1. Initialize the hugo module system: `hugo mod init github.com//` +2. Import the theme: + +{{< code-toggle file=hugo >}} +[module] + [[module.imports]] + path = "github.com/spf13/hyde" +{{< /code-toggle >}} + +## Update modules + +Modules will be downloaded and added when you add them as imports to your configuration, see [Module Imports](/hugo-modules/configuration/#module-configuration-imports). + +To update or manage versions, you can use `hugo mod get`. + +Some examples: + +### Update all modules + +```sh +hugo mod get -u +``` + +### Update all modules recursively + +```sh +hugo mod get -u ./... +``` + +### Update one module + +```sh +hugo mod get -u github.com/gohugoio/myShortcodes +``` + +### Get a specific version + +```sh +hugo mod get github.com/gohugoio/myShortcodes@v1.0.7 +``` + +Also see the [CLI Doc](/commands/hugo_mod_get/). + +## Make and test changes in a module + +One way to do local development of a module imported in a project is to add a replace directive to a local directory with the source in `go.mod`: + +```sh +replace github.com/bep/hugotestmods/mypartials => /Users/bep/hugotestmods/mypartials +``` + +If you have the `hugo server` running, the configuration will be reloaded and `/Users/bep/hugotestmods/mypartials` put on the watch list. + +Instead of modifying the `go.mod` files, you can also use the modules configuration [`replacements`](/hugo-modules/configuration/#module-configuration-top-level) option. + +## Print dependency graph + +Use `hugo mod graph` from the relevant module directory and it will print the dependency graph, including vendoring, module replacement or disabled status. + +E.g.: + +```txt +hugo mod graph + +github.com/bep/my-modular-site github.com/bep/hugotestmods/mymounts@v1.2.0 +github.com/bep/my-modular-site github.com/bep/hugotestmods/mypartials@v1.0.7 +github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myassets@v1.0.4 +github.com/bep/hugotestmods/mypartials@v1.0.7 github.com/bep/hugotestmods/myv2@v1.0.0 +DISABLED github.com/bep/my-modular-site github.com/spf13/hyde@v0.0.0-20190427180251-e36f5799b396 +github.com/bep/my-modular-site github.com/bep/hugo-fresh@v1.0.1 +github.com/bep/my-modular-site in-themesdir +``` + +Also see the [CLI Doc](/commands/hugo_mod_graph/). + +## Vendor your modules + +`hugo mod vendor` will write all the module dependencies to a `_vendor` folder, which will then be used for all subsequent builds. + +Note that: + +* You can run `hugo mod vendor` on any level in the module tree. +* Vendoring will not store modules stored in your `themes` folder. +* Most commands accept a `--ignoreVendorPaths` flag, which will then not use the vendored modules in `_vendor` for the module paths matching the [Glob](https://github.com/gobwas/glob) pattern given. + +Also see the [CLI Doc](/commands/hugo_mod_vendor/). + +## Tidy go.mod, go.sum + +Run `hugo mod tidy` to remove unused entries in `go.mod` and `go.sum`. + +Also see the [CLI Doc](/commands/hugo_mod_clean/). + +## Clean module cache + +Run `hugo mod clean` to delete the entire modules cache. + +Note that you can also configure the `modules` cache with a `maxAge`, see [File Caches](/getting-started/configuration/#configure-file-caches). + +Also see the [CLI Doc](/commands/hugo_mod_clean/). + +## Module workspaces + +{{< new-in 0.109.0 >}} + +Workspace support was added in [Go 1.18](https://go.dev/blog/get-familiar-with-workspaces) and Hugo got solid support for it in the `v0.109.0` version. + +A common use case for a workspace is to simplify local development of a site with its theme modules. + +A workspace can be configured in a `*.work` file and activated with the [module.workspace](/hugo-modules/configuration/) setting, which for this use is commonly controlled via the `HUGO_MODULE_WORKSPACE` OS environment variable. + +See the [hugo.work](https://github.com/gohugoio/hugo/blob/master/docs/hugo.work) file in the Hugo Docs repo for an example: + +```text - go 1.19 ++go 1.20 + +use . +use ../gohugoioTheme +``` + +Using the `use` directive, list all the modules you want to work on, pointing to its relative location. As in the example above, it's recommended to always include the main project (the ".") in the list. + +With that you can start the Hugo server with that workspace enabled: + +```sh +HUGO_MODULE_WORKSPACE=hugo.work hugo server --ignoreVendorPaths "**" +``` + +The `--ignoreVendorPaths` flag is added above to ignore any of the vendored dependencies inside `_vendor`. If you don't use vendoring, you don't need that flag. But now the server is set up watching the files and directories in the workspace and you can see your local edits reloaded. diff --cc docs/content/en/hugo-pipes/babel.md index 73ccf01d4,000000000..c447983a9 mode 100755,000000..100755 --- a/docs/content/en/hugo-pipes/babel.md +++ b/docs/content/en/hugo-pipes/babel.md @@@ -1,76 -1,0 +1,76 @@@ +--- +title: Babel +description: Hugo Pipes can process JS files with Babel. +categories: [asset management] +keywords: [] +menu: + docs: + parent: hugo-pipes + weight: 70 +weight: 70 +function: + aliases: [babel] + returnType: resource.Resource + signatures: ['resources.Babel [OPTIONS] RESOURCE'] +--- + +## Usage + +Any JavaScript resource file can be transpiled to another JavaScript version using `resources.Babel` which takes for argument the resource object and an optional dict of options listed below. Babel uses the [babel cli](https://babeljs.io/docs/en/babel-cli). + +{{% note %}} +Hugo Pipe's Babel requires the `@babel/cli` and `@babel/core` JavaScript packages to be installed in the project or globally (`npm install -g @babel/cli @babel/core`) along with any Babel plugin(s) or preset(s) used (e.g., `npm install @babel/preset-env --save-dev`). + +If you are using the Hugo Snap package, Babel and plugin(s) need to be installed locally within your Hugo site directory, e.g., `npm install @babel/cli @babel/core --save-dev` without the `-g` flag. +{{% /note %}} + - ### configuration ++## Configuration + +We add the main project's `node_modules` to `NODE_PATH` when running Babel and similar tools. There are some known [issues](https://github.com/babel/babel/issues/5618) with Babel in this area, so if you have a `babel.config.js` living in a Hugo Module (and not in the project itself), we recommend using `require` to load the presets/plugins, e.g.: + +```js +module.exports = { + presets: [ + [ + require("@babel/preset-env"), + { + useBuiltIns: "entry", + corejs: 3, + }, + ], + ], +}; +``` + - ### Options ++## Options + +config +: (`string`) Path to the Babel configuration file. Hugo will, by default, look for a `babel.config.js` in your project. More information on these configuration files can be found here: [babel configuration](https://babeljs.io/docs/en/configuration). + +minified +: (`bool`) Save as many bytes as possible when printing + +noComments +: (`bool`) Write comments to generated output (true by default) + +compact +: (`bool`) Do not include superfluous whitespace characters and line terminators. Defaults to `auto` if not set. + +verbose +: (`bool`) Log everything + +sourceMap +: (`string`) Output `inline` or `external` sourcemap from the babel compile. External sourcemaps will be written to the target with the output file name + ".map". Input sourcemaps can be read from js.Build and node modules and combined into the output sourcemaps. + - ### Examples ++## Examples + +```go-html-template +{{- $transpiled := resources.Get "scripts/main.js" | babel -}} +``` + +Or with options: + +```go-html-template +{{ $opts := dict "noComments" true }} +{{- $transpiled := resources.Get "scripts/main.js" | babel $opts -}} +``` diff --cc docs/content/en/hugo-pipes/js.md index c9366ce8a,000000000..9d2bbbd82 mode 100644,000000..100644 --- a/docs/content/en/hugo-pipes/js.md +++ b/docs/content/en/hugo-pipes/js.md @@@ -1,166 -1,0 +1,166 @@@ +--- +title: js.Build +linkTitle: JavaScript building +description: Bundle, transpile, tree shake, and minify JavaScript resources. +categories: [asset management] +keywords: [] +menu: + docs: + parent: hugo-pipes + weight: 60 +weight: 60 +action: + aliases: [] + returnType: resource.Resource + signatures: ['js.Build [OPTIONS] RESOURCE'] +--- + +## Usage + +Any JavaScript resource file can be transpiled and "tree shaken" using `js.Build` which takes for argument either a string for the filepath or a dict of options listed below. + +### Options + +targetPath +: (`string`) If not set, the source path will be used as the base target path. +Note that the target path's extension may change if the target MIME type is different, e.g. when the source is TypeScript. + - params ++params {{< new-in "0.96.0" >}} +: (`map` or `slice`) Params that can be imported as JSON in your JS files, e.g.: + +```go-html-template +{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }} +``` +And then in your JS file: + +```js +import * as params from '@params'; +``` + +Note that this is meant for small data sets, e.g. configuration settings. For larger data, please put/mount the files into `/assets` and import them directly. + +minify +: (`bool`) Let `js.Build` handle the minification. + +inject +: (`slice`) This option allows you to automatically replace a global variable with an import from another file. The path names must be relative to `assets`. See https://esbuild.github.io/api/#inject + +shims +: (`map`) This option allows swapping out a component with another. A common use case is to load dependencies like React from a CDN (with _shims_) when in production, but running with the full bundled `node_modules` dependency during development: + +```go-html-template +{{ $shims := dict "react" "js/shims/react.js" "react-dom" "js/shims/react-dom.js" }} +{{ $js = $js | js.Build dict "shims" $shims }} +``` + +The _shim_ files may look like these: + +```js +// js/shims/react.js +module.exports = window.React; +``` + +```js +// js/shims/react-dom.js +module.exports = window.ReactDOM; +``` + +With the above, these imports should work in both scenarios: + +```js +import * as React from 'react' +import * as ReactDOM from 'react-dom'; +``` + +target +: (`string`) The language target. + One of: `es5`, `es2015`, `es2016`, `es2017`, `es2018`, `es2019`, `es2020` or `esnext`. + Default is `esnext`. + +externals +: (`slice`) External dependencies. Use this to trim dependencies you know will never be executed. See https://esbuild.github.io/api/#external + +defines +: (`map`) Allow to define a set of string replacement to be performed when building. Should be a map where each key is to be replaced by its value. + +```go-html-template +{{ $defines := dict "process.env.NODE_ENV" `"development"` }} +``` + +format +: (`string`) The output format. + One of: `iife`, `cjs`, `esm`. + Default is `iife`, a self-executing function, suitable for inclusion as a ` +``` diff --cc docs/content/en/hugo-pipes/minification.md index f8cedcde5,000000000..a5d4724f9 mode 100755,000000..100755 --- a/docs/content/en/hugo-pipes/minification.md +++ b/docs/content/en/hugo-pipes/minification.md @@@ -1,27 -1,0 +1,27 @@@ +--- +title: Minify +linkTitle: Asset minification +description: Minifies a given resource. +categories: [asset management] +keywords: [] +menu: + docs: + parent: hugo-pipes + weight: 80 +weight: 80 +action: + aliases: [minify] + returnType: resource.Resource + signatures: [resources.Minify RESOURCE] +--- + +## Usage + - Any CSS, JS, JSON, HTML, SVG or XML resource can be minified using `resources.Minify` which takes for argument the resource object. ++Any CSS, JS, JSON, HTML, SVG, or XML resource can be minified using `resources.Minify` which takes for argument the resource object. + +```go-html-template +{{ $css := resources.Get "css/main.css" }} +{{ $style := $css | resources.Minify }} +``` + +Note that you can also minify the final HTML output to `/public` by running `hugo --minify`. diff --cc docs/content/en/installation/_common/04-build-from-source.md index f670a5752,000000000..63be3e456 mode 100644,000000..100644 --- a/docs/content/en/installation/_common/04-build-from-source.md +++ b/docs/content/en/installation/_common/04-build-from-source.md @@@ -1,27 -1,0 +1,27 @@@ +--- +# Do not remove front matter. +--- + +## Build from source + +To build the extended edition of Hugo from source you must: + +1. Install [Git] - 1. Install [Go] version 1.19 or later ++1. Install [Go] version 1.20 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`). + +Then build and test: + +```sh +CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@latest +hugo version +``` + +[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/installation/_common/homebrew.md index 8d6ff90fc,000000000..6cd7a524f mode 100644,000000..100644 --- a/docs/content/en/installation/_common/homebrew.md +++ b/docs/content/en/installation/_common/homebrew.md @@@ -1,13 -1,0 +1,13 @@@ +--- +# Do not remove front matter. +--- + +### Homebrew + - [Homebrew] is a free and open-source package manager for macOS and Linux. This will install the extended edition of Hugo: ++[Homebrew] is a free and open-source package manager for macOS and Linux. To install the extended edition of Hugo: + +```sh +brew install hugo +``` + +[Homebrew]: https://brew.sh/ diff --cc docs/content/en/installation/bsd.md index a3b179d25,000000000..6d00b8b98 mode 100644,000000..100644 --- a/docs/content/en/installation/bsd.md +++ b/docs/content/en/installation/bsd.md @@@ -1,75 -1,0 +1,75 @@@ +--- +title: BSD +description: Install Hugo on BSD derivatives. +categories: [installation] +keywords: [] +menu: + docs: + parent: installation + weight: 50 +weight: 50 +toc: true +--- +{{% include "installation/_common/01-editions.md" %}} + +{{% include "installation/_common/02-prerequisites.md" %}} + +{{% include "installation/_common/03-prebuilt-binaries.md" %}} + +## Repository packages + +Most BSD derivatives maintain a repository for commonly installed applications. Please note that these repositories may not contain the [latest release]. + +[latest release]: https://github.com/gohugoio/hugo/releases/latest + +### DragonFly BSD + - [DragonFly BSD] includes Hugo in its package repository. This will install the extended edition of Hugo: ++[DragonFly BSD] includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +sudo pkg install gohugo +``` + +[DragonFly BSD]: https://www.dragonflybsd.org/ + +### FreeBSD + - [FreeBSD] includes Hugo in its package repository. This will install the extended edition of Hugo: ++[FreeBSD] includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +sudo pkg install gohugo +``` + +[FreeBSD]: https://www.freebsd.org/ + +### NetBSD + - [NetBSD] includes Hugo in its package repository. This will install the extended edition of Hugo: ++[NetBSD] includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +sudo pkgin install go-hugo +``` + +[NetBSD]: https://www.netbsd.org/ + +### OpenBSD + +[OpenBSD] includes Hugo in its package repository. This will prompt you to select which edition of Hugo to install: + +```sh +doas pkg_add hugo +``` + +[OpenBSD]: https://www.openbsd.org/ + +{{% include "installation/_common/04-build-from-source.md" %}} + +## Comparison + +||Prebuilt binaries|Repository packages|Build from source +:--|:--:|:--:|:--: +Easy to install?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: +Easy to upgrade?|:heavy_check_mark:|varies|:heavy_check_mark: +Easy to downgrade?|:heavy_check_mark:|varies|:heavy_check_mark: +Automatic updates?|:x:|varies|:x: +Latest version available?|:heavy_check_mark:|varies|:heavy_check_mark: diff --cc docs/content/en/installation/linux.md index bb8f4b555,000000000..7b75f149b mode 100644,000000..100644 --- a/docs/content/en/installation/linux.md +++ b/docs/content/en/installation/linux.md @@@ -1,143 -1,0 +1,176 @@@ +--- +title: Linux +description: Install Hugo on Linux. +categories: [installation] +keywords: [] +menu: + docs: + parent: installation + weight: 30 +weight: 30 +toc: true +--- +{{% include "installation/_common/01-editions.md" %}} + +{{% include "installation/_common/02-prerequisites.md" %}} + +{{% include "installation/_common/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. + - This will install the extended edition of Hugo: ++To install the extended edition of Hugo: + +```sh +sudo snap install hugo +``` + +To enable or revoke access to removable media: + +```sh +sudo snap connect hugo:removable-media +sudo snap disconnect hugo:removable-media +``` + +To enable or revoke access to SSH keys: + +```sh +sudo snap connect hugo:ssh-keys +sudo snap disconnect hugo:ssh-keys +``` + +[most distributions]: https://snapcraft.io/docs/installing-snapd +[strictly confined]: https://snapcraft.io/docs/snap-confinement +[Snap]: https://snapcraft.io/ + +{{% include "installation/_common/homebrew.md" %}} + +## Repository packages + +Most Linux distributions maintain a repository for commonly installed applications. + +{{% note %}} - Due to Long Term Release (LTR) guidelines, most Linux package repositories will not contain the [latest release]. ++The Hugo version available in package repositories varies based on Linux distribution and release, and in some cases will not be the [latest version]. + - [latest release]: https://github.com/gohugoio/hugo/releases/latest ++Use one of the other installation methods if your package repository does not provide the desired version. ++ ++[latest version]: https://github.com/gohugoio/hugo/releases/latest +{{% /note %}} + ++### 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 ++``` ++ ++[Alpine Linux]: https://alpinelinux.org/ ++ +### Arch Linux + - Derivatives of the [Arch Linux] distribution of Linux include [EndeavourOS], [Garuda Linux], [Manjaro], and others. This will install the extended edition of Hugo: ++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 +``` + +[Arch Linux]: https://archlinux.org/ +[EndeavourOS]: https://endeavouros.com/ +[Manjaro]: https://manjaro.org/ +[Garuda Linux]: https://garudalinux.org/ + +### 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. This will install the extended edition of Hugo: ++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. + +[Debian]: https://www.debian.org/ +[elementary OS]: https://elementary.io/ +[KDE neon]: https://neon.kde.org/ +[Linux Lite]: https://www.linuxliteos.com/ +[Linux Mint]: https://linuxmint.com/ +[MX Linux]: https://mxlinux.org/ +[Pop!_OS]: https://pop.system76.com/ +[Ubuntu]: https://ubuntu.com/ +[Zorin OS]: https://zorin.com/os/ + +### Fedora + - Derivatives of the [Fedora] distribution of Linux include [CentOS], [Red Hat Enterprise Linux], and others. This will install the extended edition of Hugo: ++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 +``` + +[CentOS]: https://www.centos.org/ +[Fedora]: https://getfedora.org/ +[Red Hat Enterprise Linux]: https://www.redhat.com/ + ++### Gentoo ++ ++Derivatives of the [Gentoo] distribution of Linux include [Calculate Linux], [Funtoo], and others. Follow the instructions below to install the extended edition of Hugo: ++ ++1. Specify the `extended` [USE] flag in /etc/portage/package.use/hugo: ++ ++ ```text ++ www-apps/hugo extended ++ ``` ++ ++2. Build using the Portage package manager: ++ ++ ```sh ++ sudo emerge www-apps/hugo ++ ``` ++ ++[Calculate Linux]: https://www.calculate-linux.org/ ++[Funtoo]: https://www.funtoo.org/ ++[Gentoo]: https://www.gentoo.org/ ++[USE]: https://packages.gentoo.org/packages/www-apps/hugo ++ +### openSUSE + - Derivatives of the [openSUSE] distribution of Linux include [GeckoLinux], [Linux Karmada], and others. This will install the extended edition of Hugo: ++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 +``` + +[GeckoLinux]: https://geckolinux.github.io/ +[Linux Karmada]: https://linuxkamarada.com/ +[openSUSE]: https://www.opensuse.org/ + +### Solus + - The [Solus] distribution of Linux includes Hugo in its package repository. This will install the _standard_ edition of Hugo: ++The [Solus] distribution of Linux includes Hugo in its package repository. To install the extended edition of Hugo: + +```sh +sudo eopkg install hugo +``` + +[Solus]: https://getsol.us/ + +{{% include "installation/_common/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. diff --cc docs/content/en/installation/macos.md index eba977481,000000000..fa6029679 mode 100644,000000..100644 --- a/docs/content/en/installation/macos.md +++ b/docs/content/en/installation/macos.md @@@ -1,46 -1,0 +1,46 @@@ +--- +title: macOS +description: Install Hugo on macOS. +categories: [installation] +keywords: [] +menu: + docs: + parent: installation + weight: 20 +weight: 20 +toc: true +--- +{{% include "installation/_common/01-editions.md" %}} + +{{% include "installation/_common/02-prerequisites.md" %}} + +{{% include "installation/_common/03-prebuilt-binaries.md" %}} + +## Package managers + +{{% include "installation/_common/homebrew.md" %}} + +### MacPorts + - [MacPorts] is a free and open-source package manager for macOS. This will install the extended edition of Hugo: ++[MacPorts] is a free and open-source package manager for macOS. To install the extended edition of Hugo: + +```sh +sudo port install hugo +``` + +[MacPorts]: https://www.macports.org/ + +{{% include "installation/_common/04-build-from-source.md" %}} + +## Comparison + +||Prebuilt binaries|Package managers|Build from source +:--|:--:|:--:|:--: +Easy to install?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:| +Easy to upgrade?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: +Easy to downgrade?|:heavy_check_mark:|:heavy_check_mark: [^1]|:heavy_check_mark: +Automatic updates?|:x:|:x: [^2]|:x: +Latest version available?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: + +[^1]: Easy if a previous version is still installed. +[^2]: Possible but requires advanced configuration. diff --cc docs/content/en/installation/windows.md index 97e767af8,000000000..719264550 mode 100644,000000..100644 --- a/docs/content/en/installation/windows.md +++ b/docs/content/en/installation/windows.md @@@ -1,68 -1,0 +1,73 @@@ +--- +title: Windows +description: Install Hugo on Windows. +categories: [installation] +keywords: [] +menu: + docs: + parent: installation + weight: 40 +weight: 40 +toc: true +--- ++ ++{{% note %}} ++Hugo v0.121.1 and later require at least Windows 10 or Windows Server 2016. ++{{% /note %}} ++ +{{% include "installation/_common/01-editions.md" %}} + +{{% include "installation/_common/02-prerequisites.md" %}} + +{{% include "installation/_common/03-prebuilt-binaries.md" %}} + +## Package managers + +### Chocolatey + - [Chocolatey] is a free and open-source package manager for Windows. This will install the extended edition of Hugo: ++[Chocolatey] is a free and open-source package manager for Windows. To install the extended edition of Hugo: + +```sh +choco install hugo-extended +``` + +[Chocolatey]: https://chocolatey.org/ + +### Scoop + - [Scoop] is a free and open-source package manager for Windows. This will install the extended edition of Hugo: ++[Scoop] is a free and open-source package manager for Windows. To install the extended edition of Hugo: + +```sh +scoop install hugo-extended +``` + +[Scoop]: https://scoop.sh/ + +### Winget + - [Winget] is Microsoft's official free and open-source package manager for Windows. This will install the extended edition of Hugo: ++[Winget] is Microsoft's official free and open-source package manager for Windows. To install the extended edition of Hugo: + +```sh +winget install Hugo.Hugo.Extended +``` + +[Winget]: https://learn.microsoft.com/en-us/windows/package-manager/ + +{{% include "installation/_common/04-build-from-source.md" %}} + +{{% note %}} +See these [detailed instructions](https://discourse.gohugo.io/t/41370) to install GCC on Windows. +{{% /note %}} + +## Comparison + +||Prebuilt binaries|Package managers|Build from source +:--|:--:|:--:|:--: +Easy to install?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:| +Easy to upgrade?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: +Easy to downgrade?|:heavy_check_mark:|:heavy_check_mark: [^2]|:heavy_check_mark: +Automatic updates?|:x:|:x: [^1]|:x: +Latest version available?|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark: + +[^1]: Possible but requires advanced configuration. +[^2]: Easy if a previous version is still installed. diff --cc docs/content/en/methods/menu-entry/Children.md index af2af6dce,000000000..ad671b2d0 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Children.md +++ b/docs/content/en/methods/menu-entry/Children.md @@@ -1,67 -1,0 +1,67 @@@ +--- +title: Children +description: Returns a collection of child menu entries, if any, under the given menu entry. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/HasChildren + returnType: navigation.Menu + signatures: [MENUENTRY.Children] +--- + +Use the `Children` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + - [[menu.main]] ++[[menus.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +And this template: + +```go-html-template +
    + {{ range .Site.Menus.main }} +
  • + {{ .Name }} + {{ if .HasChildren }} + + {{ end }} +
  • + {{ end }} +
+``` + +Hugo renders this HTML: + +```html + +``` diff --cc docs/content/en/methods/menu-entry/HasChildren.md index d906987e8,000000000..fac03b7ae mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/HasChildren.md +++ b/docs/content/en/methods/menu-entry/HasChildren.md @@@ -1,67 -1,0 +1,67 @@@ +--- +title: HasChildren +description: Reports whether the given menu entry has child menu entries. +categories: [] +keywords: [] +action: + related: + - methods/menu-entry/Children + returnType: bool + signatures: [MENUENTRY.HasChildren] +--- + +Use the `HasChildren` method when rendering a nested menu. + +With this site configuration: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + - [[menu.main]] ++[[menus.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +And this template: + +```go-html-template +
    + {{ range .Site.Menus.main }} +
  • + {{ .Name }} + {{ if .HasChildren }} + + {{ end }} +
  • + {{ end }} +
+``` + +Hugo renders this HTML: + +```html + +``` diff --cc docs/content/en/methods/menu-entry/Identifier.md index a4d7e129e,000000000..ba8b77ece mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Identifier.md +++ b/docs/content/en/methods/menu-entry/Identifier.md @@@ -1,44 -1,0 +1,44 @@@ +--- +title: Identifier +description: Returns the `identifier` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Identifier] +--- + +The `Identifier` method returns the `identifier` property of the menu entry. If you define the menu entry [automatically], it returns the page's section. + +[automatically]: /content-management/menus/#define-automatically + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + - [[menu.main]] ++[[menus.main]] +identifier = 'contact' +name = 'Contact' +pageRef = '/contact' +weight = 20 +{{< /code-toggle >}} + +This example uses the `Identifier` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist: + +```go-html-template + +``` + +{{% note %}} +In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables. + +[details]: /content-management/menus/#properties-front-matter +{{% /note %}} diff --cc docs/content/en/methods/menu-entry/KeyName.md index 8031441b9,000000000..4b43596b0 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/KeyName.md +++ b/docs/content/en/methods/menu-entry/KeyName.md @@@ -1,39 -1,0 +1,39 @@@ +--- +title: KeyName +description: Returns the `identifier` property of the given menu entry, falling back to its `name` property. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.KeyName] +--- + +In this menu definition, the second entry does not contain an `identifier`, so the `Identifier` method returns its `name` property instead: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 20 +{{< /code-toggle >}} + +This example uses the `KeyName` method when querying the translation table on a multilingual site, falling back the `name` property if a matching key in the translation table does not exist: + +```go-html-template + +``` + +In the example above, we need to pass the value returned by `.KeyName` through the [`lower`] function because the keys in the translation table are lowercase. + +[`lower`]: functions/strings/tolower diff --cc docs/content/en/methods/menu-entry/Page.md index 9b23f7b73,000000000..b75e4af55 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Page.md +++ b/docs/content/en/methods/menu-entry/Page.md @@@ -1,53 -1,0 +1,53 @@@ +--- +title: Page +description: Returns the Page object associated with the given menu entry. +categories: [] +keywords: [] +action: + related: [] - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [MENUENTRY.Page] +--- + +Regardless of how you [define menu entries], an entry associated with a page has access to its [methods]. + +In this menu definition, the first two entries are associated with a page, the last entry is not: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +pageRef = '/about' +weight = 10 + - [[menu.main]] ++[[menus.main]] +pageRef = '/contact' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Hugo' +url = 'https://gohugo.io' +weight = 30 +{{< /code-toggle >}} + +In this example, if the menu entry is associated with a page, we use page's [`RelPermalink`] and [`LinkTitle`] when rendering the anchor element. + +If the entry is not associated with a page, we use its `url` and `name` properties. + +```go-html-template +
    + {{ range .Site.Menus.main }} + {{ with .Page }} +
  • {{ .Title }}
  • + {{ else }} +
  • {{ .Name }}
  • + {{ end }} + {{ end }} +
+``` + +See the [menu templates] section for more information. + +[`LinkTitle`]: /methods/page/linktitle +[`RelPermalink`]: /methods/page/relpermalink +[define menu entries]: /content-management/menus/ +[menu templates]: /templates/menu-templates/#page-references +[methods]: /methods/page diff --cc docs/content/en/methods/menu-entry/Params.md index 1486c12cb,000000000..8af3f0637 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Params.md +++ b/docs/content/en/methods/menu-entry/Params.md @@@ -1,62 -1,0 +1,62 @@@ +--- +title: Params +description: Returns the `params` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: maps.Params + signatures: [MENUENTRY.Params] +--- + +When you define menu entries [in site configuration] or [in front matter], you can include a `params` key to attach additional information to the entry. For example: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Hugo' +url = 'https://gohugo.io' +weight = 30 - [menu.main.params] ++[menus.main.params] + rel = 'external' +{{< /code-toggle >}} + +With this template: + + +```go-html-template + +``` + +Hugo renders: + +```html + +``` + +See the [menu templates] section for more information. + +[menu templates]: /templates/menu-templates/#menu-entry-parameters +[in front matter]: /content-management/menus/#define-in-front-matter +[in site configuration]: /content-management/menus/ diff --cc docs/content/en/methods/menu-entry/Parent.md index 897712831,000000000..af1b4afe6 mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/Parent.md +++ b/docs/content/en/methods/menu-entry/Parent.md @@@ -1,51 -1,0 +1,50 @@@ +--- +title: Parent +description: Returns the `parent` property of the given menu entry. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [MENUENTRY.Parent] +--- + +With this menu definition: + +{{< code-toggle file=hugo >}} - [menu] - [[menu.main]] ++[[menus.main]] +name = 'Products' +pageRef = '/product' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Product 1' +pageRef = '/products/product-1' +parent = 'Products' +weight = 1 + - [[menu.main]] ++[[menus.main]] +name = 'Product 2' +pageRef = '/products/product-2' +parent = 'Products' +weight = 2 +{{< /code-toggle >}} + +This template renders the nested menu, listing the `parent` property next each of the child entries: + +```go-html-template +
    + {{ range .Site.Menus.main }} +
  • + {{ .Name }} + {{ if .HasChildren }} +
      + {{ range .Children }} +
    • {{ .Name }} ({{ .Parent }})
    • + {{ end }} +
    + {{ end }} +
  • + {{ end }} +
+``` diff --cc docs/content/en/methods/menu-entry/_common/pre-post.md index 8cc787ea9,000000000..fbfce062a mode 100644,000000..100644 --- a/docs/content/en/methods/menu-entry/_common/pre-post.md +++ b/docs/content/en/methods/menu-entry/_common/pre-post.md @@@ -1,39 -1,0 +1,39 @@@ +--- +# Do not remove front matter. +--- + +In this site configuration we enable rendering of [emoji shortcodes], and add emoji shortcodes before (pre) and after (post) each menu entry: + +{{< code-toggle file=hugo >}} +enableEmoji = true + - [[menu.main]] ++[[menus.main]] +name = 'About' +pageRef = '/about' +post = ':point_left:' +pre = ':point_right:' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +post = ':arrow_left:' +pre = ':arrow_right:' +weight = 20 +{{< /code-toggle >}} + +To render the menu: + +```go-html-template +
    + {{ range .Site.Menus.main }} +
  • + {{ .Pre | markdownify }} + {{ .Name }} + {{ .Post | markdownify }} +
  • + {{ end }} +
+``` + +[emoji shortcodes]: /quick-reference/emojis/ diff --cc docs/content/en/methods/menu/ByName.md index 3f1c52b2e,000000000..04f25c22d mode 100644,000000..100644 --- a/docs/content/en/methods/menu/ByName.md +++ b/docs/content/en/methods/menu/ByName.md @@@ -1,65 -1,0 +1,65 @@@ +--- +title: ByName +description: Returns the given menu with its entries sorted by name. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.ByName] +--- + +The `Sort` method returns the given menu with its entries sorted by `name`. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by `name`: + +```go-html-template +
    + {{ range .Site.Menus.main.ByName }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +Hugo renders this to: + +```html + +``` + +You can also sort menu entries using the [`sort`] function. For example, to sort by `name` in descending order: + +```go-html-template +
    + {{ range sort .Site.Menus.main "Name" "desc" }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. + +[`sort`]: /functions/collections/sort diff --cc docs/content/en/methods/menu/ByWeight.md index c915914db,000000000..d5cb0444b mode 100644,000000..100644 --- a/docs/content/en/methods/menu/ByWeight.md +++ b/docs/content/en/methods/menu/ByWeight.md @@@ -1,76 -1,0 +1,76 @@@ +--- +title: ByWeight +description: Returns the given menu with its entries sorted by weight, then by name, then by identifier. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.ByWeight] +--- + +The `ByWeight` method returns the given menu with its entries sorted by [`weight`], then by `name`, then by `identifier`. This is the default sort order. + +[`weight`]: /getting-started/glossary/#weight + +Consider this menu definition: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +identifier = 'about' +name = 'About' +pageRef = '/about' +weight = 20 + - [[menu.main]] ++[[menus.main]] +identifier = 'services' +name = 'Services' +pageRef = '/services' +weight = 10 + - [[menu.main]] ++[[menus.main]] +identifier = 'contact' +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by `weight`, then by `name`, then by `identifier`: + +```go-html-template +
    + {{ range .Site.Menus.main.ByWeight }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +Hugo renders this to: + +```html + +``` + +{{% note %}} +In the menu definition above, note that the `identifier` property is only required when two or more menu entries have the same name, or when localizing the name using translation tables. + +[details]: /content-management/menus/#properties-front-matter +{{% /note %}} + +You can also sort menu entries using the [`sort`] function. For example, to sort by `weight` in descending order: + +```go-html-template +
    + {{ range sort .Site.Menus.main "Weight" "desc" }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. + +[`sort`]: /functions/collections/sort diff --cc docs/content/en/methods/menu/Limit.md index 12263e811,000000000..23a523dbd mode 100644,000000..100644 --- a/docs/content/en/methods/menu/Limit.md +++ b/docs/content/en/methods/menu/Limit.md @@@ -1,50 -1,0 +1,50 @@@ +--- +title: Limit +description: Returns the given menu, limited to the first N entries. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.Limit N] +--- + +The `Limit` method returns the given menu, limited to the first N entries. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by name, and limit to the first 2 entries: + +```go-html-template +
    + {{ range .Site.Menus.main.ByName.Limit 2 }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +Hugo renders this to: + +```html + +``` diff --cc docs/content/en/methods/menu/Reverse.md index 989132d60,000000000..a3fe09dce mode 100644,000000..100644 --- a/docs/content/en/methods/menu/Reverse.md +++ b/docs/content/en/methods/menu/Reverse.md @@@ -1,51 -1,0 +1,51 @@@ +--- +title: Reverse +description: Returns the given menu, reversing the sort order of its entries. +categories: [] +keywords: [] +action: + related: [] + returnType: navigation.Menu + signatures: [MENU.Reverse] +--- + +The `Reverse` method returns the given menu, reversing the sort order of its entries. + +Consider this menu definition: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Services' +pageRef = '/services' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'About' +pageRef = '/about' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Contact' +pageRef = '/contact' +weight = 30 +{{< /code-toggle >}} + +To sort the entries by name in descending order: + +```go-html-template +
    + {{ range .Site.Menus.main.ByName.Reverse }} +
  • {{ .Name }}
  • + {{ end }} +
+``` + +Hugo renders this to: + +```html + +``` diff --cc docs/content/en/methods/page/AllTranslations.md index b9c156127,000000000..b8cc65179 mode 100644,000000..100644 --- a/docs/content/en/methods/page/AllTranslations.md +++ b/docs/content/en/methods/page/AllTranslations.md @@@ -1,90 -1,0 +1,91 @@@ +--- +title: AllTranslations +description: Returns all translation of the given page, including the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Translations + - methods/page/IsTranslated + - methods/page/TranslationKey + returnType: page.Pages + signatures: [PAGE.AllTranslations] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 + +[languages.fr] +contentDir = 'content/fr' +languageCode = 'fr-FR' +languageName = 'Français' +weight = 3 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── fr/ +│ ├── books/ +│ │ └── book-1.md +│ └── _index.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ with .AllTranslations }} + +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of each site: + +```html + +``` + +On the "Book 2" page of the English and German sites, Hugo will render this: + +```html + +``` diff --cc docs/content/en/methods/page/CodeOwners.md index ec7e5c8bf,000000000..068c4591f mode 100644,000000..100644 --- a/docs/content/en/methods/page/CodeOwners.md +++ b/docs/content/en/methods/page/CodeOwners.md @@@ -1,66 -1,0 +1,66 @@@ +--- +title: CodeOwners +description: Returns of slice of code owners for the given page, derived from the CODEOWNERS file in the root of the project directory. +categories: [] +keywords: [] +action: + related: + - methods/page/GitInfo + returnType: '[]string' + signatures: [PAGE.CodeOwners] +--- + +GitHub and GitLab support CODEOWNERS files. This file specifies the users responsible for developing and maintaining software and documentation. This definition can apply to the entire repository, specific directories, or to individual files. To learn more: + +- [GitHub CODEOWNERS documentation] +- [GitLab CODEOWNERS documentation] + +Use the `CodeOwners` method on a `Page` object to determine the code owners for the given page. + +[GitHub CODEOWNERS documentation]: https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners +[GitLab CODEOWNERS documentation]: https://docs.gitlab.com/ee/user/project/code_owners.html + +To use the `CodeOwners` method you must enable access to your local Git repository: + +{{< code-toggle file=hugo >}} +enableGitInfo = true +{{< /code-toggle >}} + +Consider this project structure: + +```text - hugo-testing/ ++my-project/ +├── content/ +│ ├── books/ +│ │ └── les-miserables.md +│ └── films/ +│ └── the-hunchback-of-notre-dame.md +└── CODEOWNERS +``` + +And this CODEOWNERS file: + +```text +* @jdoe +/content/books/ @tjones +/content/films/ @mrichards @rsmith +``` + +The table below shows the slice of code owners returned for each file: + +Path|Code owners +:--|:-- +`books/les-miserables.md`|`[@tjones]` +`films/the-hunchback-of-notre-dame.md`|`[@mrichards @rsmith]` + +Render the code owners for each content page: + +```go-html-template +{{ range .CodeOwners }} + {{ . }} +{{ end }} +``` + +Combine this method with [`resources.GetRemote`] to retrieve names and avatars from your Git provider by querying their API. + +[`resources.GetRemote`]: functions/resources/getremote diff --cc docs/content/en/methods/page/CurrentSection.md index 03cb9eb3d,000000000..7049feb47 mode 100644,000000..100644 --- a/docs/content/en/methods/page/CurrentSection.md +++ b/docs/content/en/methods/page/CurrentSection.md @@@ -1,60 -1,0 +1,60 @@@ +--- +title: CurrentSection +description: Returns the Page object of the section in which the given page resides. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.CurrentSection] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +The current section of a [section] page, [taxonomy] page, [term] page, or the home page, is itself. + +[section]: /getting-started/glossary/#section +[taxonomy]: /getting-started/glossary/#taxonomy +[term]: /getting-started/glossary/#term +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- current section: 2023-11 +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- current section: 2023-11 +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- current section: auctions +│ ├── bidding.md +│ └── payment.md <-- current section: auctions +├── books/ +│ ├── _index.md <-- current section: books +│ ├── book-1.md +│ └── book-2.md <-- current section: books +├── films/ +│ ├── _index.md <-- current section: films +│ ├── film-1.md +│ └── film-2.md <-- current section: films +└── _index.md <-- current section: home +``` + +To create a link to the current section page: + +```go-html-template +{{ .CurrentSection.LinkTitle }} +``` diff --cc docs/content/en/methods/page/File.md index c39d1a64d,000000000..44b752215 mode 100644,000000..100644 --- a/docs/content/en/methods/page/File.md +++ b/docs/content/en/methods/page/File.md @@@ -1,180 -1,0 +1,190 @@@ +--- +title: File +description: For pages backed by a file, returns file information for the given page. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.fileInfo + signatures: [PAGE.File] +toc: true +--- + +By default, not all pages are backed by a file, including top level [section] pages, [taxonomy] pages, and [term] pages. By definition, you cannot retrieve file information when the file does not exist. + +To back one of the pages above with a file, create an _index.md file in the corresponding directory. For example: + +```text +content/ +└── books/ + ├── _index.md <-- the top level section page + ├── book-1.md + └── book-2.md +``` + +Code defensively by verifying file existence as shown in each of the examples below. + +## Methods + +{{% note %}} +The path separators (slash or backslash) in `Path`, `Dir`, and `Filename` depend on the operating system. +{{% /note %}} + - BaseFileName - : (`string`) The file name, excluding the extension. ++###### BaseFileName ++ ++(`string`) The file name, excluding the extension. + +```go-html-template +{{ with .File }} + {{ .BaseFileName }} +{{ end }} +``` + - ContentBaseName - : (`string`) If the page is a branch or leaf bundle, the name of the containing directory, else the `TranslationBaseName`. ++###### ContentBaseName ++ ++(`string`) If the page is a branch or leaf bundle, the name of the containing directory, else the `TranslationBaseName`. + +```go-html-template +{{ with .File }} + {{ .ContentBaseName }} +{{ end }} +``` + - Dir - : (`string`) The file path, excluding the file name, relative to the `content` directory. ++###### Dir ++ ++(`string`) The file path, excluding the file name, relative to the `content` directory. + +```go-html-template +{{ with .File }} + {{ .Dir }} +{{ end }} +``` + - Ext - : (`string`) The file extension. ++###### Ext ++ ++(`string`) The file extension. + +```go-html-template +{{ with .File }} + {{ .Ext }} +{{ end }} +``` + - Filename - : (`string`) The absolute file path. ++###### Filename ++ ++(`string`) The absolute file path. + +```go-html-template +{{ with .File }} + {{ .Filename }} +{{ end }} +``` + - Lang - : (`string`) The language associated with the given file. ++###### Lang ++ ++(`string`) The language associated with the given file. + +```go-html-template +{{ with .File }} + {{ .Lang }} +{{ end }} +``` + - LogicalName - : (`string`) The file name. ++###### LogicalName ++ ++(`string`) The file name. + +```go-html-template +{{ with .File }} + {{ .LogicalName }} +{{ end }} +``` + - Path - : (`string`) The file path, relative to the `content` directory. ++###### Path ++ ++(`string`) The file path, relative to the `content` directory. + +```go-html-template +{{ with .File }} + {{ .Path }} +{{ end }} +``` + - TranslationBaseName - : (`string`) The file name, excluding the extension and language identifier. ++###### TranslationBaseName ++ ++(`string`) The file name, excluding the extension and language identifier. + +```go-html-template +{{ with .File }} + {{ .TranslationBaseName }} +{{ end }} +``` + - UniqueID - : (`string`) The MD5 hash of `.File.Path`. ++###### UniqueID ++ ++(`string`) The MD5 hash of `.File.Path`. + +```go-html-template +{{ with .File }} + {{ .UniqueID }} +{{ end }} +``` + +## Examples + +Consider this content structure in a multilingual project: + +```text +content/ +├── news/ +│ ├── b/ +│ │ ├── index.de.md <-- leaf bundle +│ │ └── index.en.md <-- leaf bundle +│ ├── a.de.md <-- regular content +│ ├── a.en.md <-- regular content +│ ├── _index.de.md <-- branch bundle +│ └── _index.en.md <-- branch bundle +├── _index.de.md +└── _index.en.md +``` + +With the English language site: + + |regular content|leaf bundle|branch bundle +:--|:--|:--|:-- +BaseFileName|a.en|index.en|_index.en +ContentBaseName|a|b|news +Dir|news/|news/b/|news/ +Ext|md|md|md +Filename|/home/user/...|/home/user/...|/home/user/... +Lang|en|en|en +LogicalName|a.en.md|index.en.md|_index.en.md +Path|news/a.en.md|news/b/index.en.md|news/_index.en.md +TranslationBaseName|a|index|_index +UniqueID|15be14b...|186868f...|7d9159d... + +## Defensive coding + +Some of the pages on a site may not be backed by a file. For example: + +- Top level section pages +- Taxonomy pages +- Term pages + +Without a backing file, Hugo will throw a warning if you attempt to access a `.File` property. For example: + +```text +WARN .File.ContentBaseName on zero object. Wrap it in if or with... +``` + +To code defensively, first check for file existence: + +```go-html-template +{{ with .File }} + {{ .ContentBaseName }} +{{ end }} +``` + +[section]: /getting-started/glossary/#section +[taxonomy]: /getting-started/glossary/#taxonomy +[term]: /getting-started/glossary/#term diff --cc docs/content/en/methods/page/FirstSection.md index f757aa2d2,000000000..b3ae4c04a mode 100644,000000..100644 --- a/docs/content/en/methods/page/FirstSection.md +++ b/docs/content/en/methods/page/FirstSection.md @@@ -1,56 -1,0 +1,56 @@@ +--- +title: FirstSection +description: Returns the Page object of the top level section of which the given page is a descendant. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Parent + - methods/page/Sections - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.FirstSection] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +When called on the home page, the `FirstSection` method returns the `Page` object of the home page itself. +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- first section: auctions +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- first section: auctions +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- first section: auctions +│ ├── bidding.md +│ └── payment.md <-- first section: auctions +├── books/ +│ ├── _index.md <-- first section: books +│ ├── book-1.md +│ └── book-2.md <-- first section: books +├── films/ +│ ├── _index.md <-- first section: films +│ ├── film-1.md +│ └── film-2.md <-- first section: films +└── _index.md <-- first section: home +``` + +To link to the top level section of which the current page is a descendant: + +```go-html-template +{{ .FirstSection.LinkTitle }} +``` diff --cc docs/content/en/methods/page/Fragments.md index bae1c7d03,000000000..89f82d2ce mode 100644,000000..100644 --- a/docs/content/en/methods/page/Fragments.md +++ b/docs/content/en/methods/page/Fragments.md @@@ -1,106 -1,0 +1,106 @@@ +--- +title: Fragments +description: Returns a data structure of the fragments in the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/TableOfContents + returnType: tableofcontents.Fragments + signatures: [PAGE.Fragments] +toc: true +--- + +{{< new-in 0.111.0 >}} + +In a URL, whether absolute or relative, the [fragment] links to an `id` attribute of an HTML element on the page. + +```text +/articles/article-1#section-2 +------------------- --------- + path fragment +``` + +Hugo assigns an `id` attribute to each markdown [ATX] and [setext] heading within the page content. You can override the `id` with a [markdown attribute] as needed. This creates the relationship between an entry in the [table of contents] (TOC) and a heading on the page. + +Use the `Fragments` method on a `Page` object to create a table of contents with the `Fragments.ToHTML` method, or by [walking] the `Fragments.Map` data structure. + +## Methods + +Headings - : (`map`) A nested map of all headings on the page. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure: ++: (`map`) A nested map of all headings on the page. Each map contains the following keys: `ID`, `Level`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +
{{ .Fragments.Headings | jsonify (dict "indent" "  ") }}
+``` + +HeadingsMap - : (`slice`) A slice of maps of all headings on the page, with first-level keys for each heading. Each map contains the following keys: `ID`, `Title` and `Headings`. To inspect the data structure: ++: (`slice`) A slice of maps of all headings on the page, with first-level keys for each heading. Each map contains the following keys: `ID`, `Level`, `Title` and `Headings`. To inspect the data structure: + +```go-html-template +
{{ .Fragments.HeadingsMap | jsonify (dict "indent" "  ") }}
+``` + +Identifiers +: (`slice`) A slice containing the `id` of each heading on the page. To inspect the data structure: + +```go-html-template +
{{ .Fragments.Identifiers | jsonify (dict "indent" "  ") }}
+``` + +Identifiers.Contains ID +: (`bool`) Reports whether one or more headings on the page has the given `id` attribute, useful for validating fragments within a link [render hook]. + +```go-html-template +{{ .Fragments.Identifiers.Contains "section-2" }} → true +``` + +Identifiers.Count ID +: (`int`) The number of headings on a page with the given `id` attribute, useful for detecting duplicates. + +```go-html-template +{{ .Fragments.Identifiers.Count "section-2" }} → 1 +``` + +ToHTML +: (`template.HTML`) Returns a TOC as a nested list, either ordered or unordered, identical to the HTML returned by the [`TableOfContents`] method. This method take three arguments: the start level (`int`), the end level (`int`), and a boolean (`true` to return an ordered list, `false` to return an unordered list). + +Use this method when you want to control the start level, end level, or list type independently from the table of contents settings in your site configuration. + +```go-html-template +{{ $startLevel := 2 }} +{{ $endLevel := 3 }} +{{ $ordered := true }} +{{ .Fragments.ToHTML $startLevel $endLevel $ordered }} +``` + +Hugo renders this to: + +```html + +``` + +{{% note %}} +It is safe to use the `Fragments` methods within a render hook, even for the current page. + +When using the `Fragments` methods within a shortcode, call the shortcode using the `{{}}` notation. If you use the `{{%/* */%}}` notation, the rendered shortcode is included in the creation of the fragments map, resulting in a circular loop. +{{% /note %}} + +[atx]: https://spec.commonmark.org/0.30/#atx-headings +[fragment]: /getting-started/glossary/#fragment +[markdown attribute]: /getting-started/glossary/#markdown-attribute +[setext]: https://spec.commonmark.org/0.30/#setext-headings +[table of contents]: /methods/page/tableofcontents +[walking]: /getting-started/glossary/#walk +[`tableofcontents`]: /methods/page/tableofcontents +[render hook]: /getting-started/glossary/#render-hook diff --cc docs/content/en/methods/page/GetPage.md index ed072932a,000000000..b1f192d58 mode 100644,000000..100644 --- a/docs/content/en/methods/page/GetPage.md +++ b/docs/content/en/methods/page/GetPage.md @@@ -1,65 -1,0 +1,65 @@@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +action: + related: + - methods/site/GetPage - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.GetPage PATH] +aliases: [/functions/getpage] +--- + +The `GetPage` method is also available on a `Site` object. See [details]. + +[details]: /methods/site/getpage + +When using the `GetPage` method on the `Page` object, specify a path relative to the current directory or relative to the content directory. + +If Hugo cannot resolve the path to a page, the method returns nil. If the path is ambiguous, Hugo throws an error and fails the build. + +Consider this content structure: + +```text +content/ +├── works/ +│ ├── paintings/ +│ │ ├── _index.md +│ │ ├── starry-night.md +│ │ └── the-mona-lisa.md +│ ├── sculptures/ +│ │ ├── _index.md +│ │ ├── david.md +│ │ └── the-thinker.md +│ └── _index.md +└── _index.md +``` + +The examples below depict the result of rendering works/paintings/the-mona-list.md with a single page template: + +```go-html-template +{{ with .GetPage "starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "./starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "../paintings/starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Starry Night +{{ end }} + +{{ with .GetPage "../sculptures/david" }} + {{ .Title }} → David +{{ end }} + +{{ with .GetPage "/works/sculptures/david" }} + {{ .Title }} → David +{{ end }} +``` diff --cc docs/content/en/methods/page/GitInfo.md index 88137614c,000000000..9dba2a2b2 mode 100644,000000..100644 --- a/docs/content/en/methods/page/GitInfo.md +++ b/docs/content/en/methods/page/GitInfo.md @@@ -1,130 -1,0 +1,146 @@@ +--- +title: GitInfo +description: Returns Git information related to the last commit of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/CodeOwners + returnType: source.GitInfo + signatures: [PAGE.GitInfo] +toc: true +--- + +The `GitInfo` method on a `Page` object returns an object with additional methods. + +{{% note %}} +Hugo's Git integration is performant, but may increase build times on large sites. +{{% /note %}} + +## Prerequisites + +Install [Git], create a repository, and commit your project files. + +You must also allow Hugo to access your repository. In your site configuration: + +{{< code-toggle file=hugo >}} +enableGitInfo = true +{{< /code-toggle >}} + +Alternatively, use the command line flag when building your site: + +```sh +hugo --enableGitInfo +``` + +{{% note %}} - When you set `enableGitInto` to `true`, or enable the feature with the command line flag, the last modification date for each content page will be the Author Date of the last commit for that file. ++When you set `enableGitInfo` to `true`, or enable the feature with the command line flag, the last modification date for each content page will be the Author Date of the last commit for that file. + +This is configurable. See [details]. + +[details]: /getting-started/configuration/#configure-dates +{{% /note %}} + +## Methods + - AbbreviatedHash - : (`string`) The abbreviated commit hash. ++###### AbbreviatedHash ++ ++(`string`) The abbreviated commit hash. + +```go-html-template +{{ with .GitInfo }} + {{ .AbbreviatedHash }} → aab9ec0b3 +{{ end }} +``` + - AuthorDate - : (`time.Time`) The author date. ++###### AuthorDate ++ ++(`time.Time`) The author date. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorDate.Format "2006-01-02" }} → 2023-10-09 +{{ end }} +``` + - AuthorEmail - : (`string`) The author's email address, respecting [gitmailmap]. ++###### AuthorEmail ++ ++(`string`) The author's email address, respecting [gitmailmap]. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorEmail }} → jsmith@example.org +{{ end }} +``` + - AuthorName - : (`string`) The author's name, respecting [gitmailmap]. ++###### AuthorName ++ ++(`string`) The author's name, respecting [gitmailmap]. + +```go-html-template +{{ with .GitInfo }} + {{ .AuthorName }} → John Smith +{{ end }} +``` + - Hash - : (`string`) The commit hash. ++###### CommitDate ++ ++(`time.Time`) The commit date. ++ ++```go-html-template ++{{ with .GitInfo }} ++ {{ .CommitDate.Format "2006-01-02" }} → 2023-10-09 ++{{ end }} ++``` ++ ++###### Hash ++ ++(`string`) The commit hash. + +```go-html-template +{{ with .GitInfo }} + {{ .Hash }} → aab9ec0b31ebac916a1468c4c9c305f2bebf78d4 +{{ end }} +``` + - Subject - : (`string`) The commit message subject. ++###### Subject ++ ++(`string`) The commit message subject. + +```go-html-template +{{ with .GitInfo }} + {{ .Subject }} → Add tutorials +{{ end }} +``` + +## Last modified date + +By default, when `enableGitInfo` is `true`, the `Lastmod` method on a `Page` object returns the Git AuthorDate of the last commit that included the file. + +You can change this behavior in your [site configuration]. + +[git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git +[gitmailmap]: https://git-scm.com/docs/gitmailmap +[site configuration]: /getting-started/configuration/#configure-front-matter + +## Hosting considerations + +When hosting your site in a CI/CD environment, the step that clones your project repository must perform a deep clone. If the clone is shallow, the Git information for a given file may not be accurate---it may reflect the most recent repository commit, not the commit that last modified the file. + +Some providers perform deep clones by default, others allow you to configure the clone depth, and some providers only perform shallow clones. + +Hosting service | Default clone depth | Configurable +:-- | :-- | :-- +Cloudflare Pages | Shallow | Yes [^CFP] +DigitalOcean App Platform | Deep | N/A +GitHub Pages | Shallow | Yes [^GHP] +GitLab Pages | Shallow | Yes [^GLP] +Netlify | Deep | N/A +Render | Shallow | No +Vercel | Shallow | No + +[^CFP]: To configure a Cloudflare Pages site for deep cloning, preface the site's normal Hugo build command with `git fetch --unshallow &&` (*e.g.*, `git fetch --unshallow && hugo`). + +[^GHP]: You can configure the GitHub Action to do a deep clone by specifying `fetch-depth: 0` in the applicable "checkout" step of your workflow file, as shown in the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-github/#procedure). + +[^GLP]: You can configure the GitLab Runner's clone depth [as explained in the GitLab documentation](https://docs.gitlab.com/ee/ci/large_repositories/#shallow-cloning); see also the Hugo documentation's [example workflow file](/hosting-and-deployment/hosting-on-gitlab/#configure-gitlab-cicd). diff --cc docs/content/en/methods/page/Next.md index 3c9e3495a,000000000..57fc1f2f8 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Next.md +++ b/docs/content/en/methods/page/Next.md @@@ -1,53 -1,0 +1,53 @@@ +--- +title: Next +description: Returns the next page in a global page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Prev + - methods/page/NextInSection + - methods/page/PrevInSection + - methods/pages/Next + - methods/pages/Prev - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.Next] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .Next }} + Prev +{{ end }} + +{{ with .Prev }} + Next +{{ end }} +``` + +## Compare to Pages methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --cc docs/content/en/methods/page/NextInSection.md index b48ddcc62,000000000..73f82d754 mode 100644,000000..100644 --- a/docs/content/en/methods/page/NextInSection.md +++ b/docs/content/en/methods/page/NextInSection.md @@@ -1,71 -1,0 +1,71 @@@ +--- +title: NextInSection +description: Returns the next page within a section, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/PrevInSection + - methods/page/Next + - methods/page/Prev + - methods/pages/Next + - methods/pages/Prev - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.NextInSection] +--- + +The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── books/ +│ ├── _index.md +│ ├── book-1.md +│ ├── book-2.md +│ └── book-3.md +├── films/ +│ ├── _index.md +│ ├── film-1.md +│ ├── film-2.md +│ └── film-3.md +└── _index.md +``` + +When you visit book-2: + +- The `PrevInSection` method points to book-3 +- The `NextInSection` method points to book-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .NextInSection }} + Previous in section +{{ end }} + +{{ with .PrevInSection }} + Next in section +{{ end }} +``` + +{{% note %}} +The navigation sort order may be different than the page collection sort order. +{{% /note %}} + +With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence: + +1. Page [weight] +2. Page [date] (descending) +3. Page [linkTitle], falling back to page [title] +4. Page file path if the page is backed by a file + +For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice. + +[date]: /methods/page/date +[weight]: /methods/page/weight +[linkTitle]: /methods/page/linktitle +[title]: /methods/page/title diff --cc docs/content/en/methods/page/Page.md index 2c0536bee,000000000..4d81c04ef mode 100644,000000..100644 --- a/docs/content/en/methods/page/Page.md +++ b/docs/content/en/methods/page/Page.md @@@ -1,40 -1,0 +1,40 @@@ +--- +title: Page +description: Returns the Page object of the given page. +categories: [] +keywords: [] +action: + related: [] - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.Page] +--- + +This is a convenience method, useful within partial templates that are called from both [shortcodes] and page templates. + +{{< code file=layouts/shortcodes/foo.html >}} +{{ partial "my-partial.html" . }} +{{< /code >}} + +When the shortcode calls the partial, it passes the current [context] (the dot). The context includes identifiers such as `Page`, `Params`, `Inner`, and `Name`. + +{{< code file=layouts/_default/single.html >}} +{{ partial "my-partial.html" . }} +{{< /code >}} + +When the page template calls the partial, it also passes the current context (the dot). But in this case, the dot _is_ the `Page` object. + +{{< code file=layouts/partials/my-partial.html >}} +The page title is: {{ .Page.Title }} +{{< /code >}} + +To handle both scenarios, the partial template must be able to access the `Page` object with `Page.Page`. + +{{% note %}} +And yes, that means you can do `.Page.Page.Page.Page.Title` too. + +But don't. +{{% /note %}} + + +[context]: getting-started/glossary/#context +[shortcodes]: /getting-started/glossary/#shortcode diff --cc docs/content/en/methods/page/Params.md index ce624c394,000000000..3d79d15c5 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Params.md +++ b/docs/content/en/methods/page/Params.md @@@ -1,43 -1,0 +1,43 @@@ +--- +title: Params +description: Returns a map of custom parameters as defined in the front matter of the given page. +categories: [] +keywords: [] +action: + related: + - functions/collections/IndexFunction + - methods/site/Params + - methods/page/Param + returnType: maps.Params + signatures: [PAGE.Params] +--- + +With this front matter: + +{{< code-toggle file=content/news/annual-conference.md >}} +title = 'Annual conference' +date = 2023-10-17T15:11:37-07:00 +display_related = true - event-date = '2023' +[params.author] + email = 'jsmith@example.org' + name = 'John Smith' +{{< /code-toggle >}} + +The `title` and `date` fields are standard parameters---the other fields are user-defined. + +Access the custom parameters by [chaining] the [identifiers]: + +```go-html-template +{{ .Params.display_related }} → true +{{ .Params.author.name }} → John Smith +``` + +In the template example above, each of the keys is a valid identifier. For example, none of the keys contains a hyphen. To access a key that is not a valid identifier, use the [`index`] function: + +```go-html-template - {{ index .Params "event-date" }} → 2023 ++{{ index .Params "key-with-hyphens" }} → 2023 +``` ++ +[`index`]: /functions/collections/indexfunction +[chaining]: /getting-started/glossary/#chain +[identifiers]: /getting-started/glossary/#identifier diff --cc docs/content/en/methods/page/Parent.md index dbd2cb9b3,000000000..9d9ed7ea3 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Parent.md +++ b/docs/content/en/methods/page/Parent.md @@@ -1,60 -1,0 +1,60 @@@ +--- +title: Parent +description: Returns the Page object of the parent section of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Ancestors + - methods/page/CurrentSection + - methods/page/FirstSection + - methods/page/InSection + - methods/page/IsAncestor + - methods/page/IsDescendant + - methods/page/Sections - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.Parent] +--- + +{{% include "methods/page/_common/definition-of-section.md" %}} + +{{% note %}} +The parent section of a regular page is the [current section]. + +[current section]: /methods/page/currentsection +{{% /note %}} + +Consider this content structure: + +```text +content/ +├── auctions/ +│ ├── 2023-11/ +│ │ ├── _index.md <-- parent: auctions +│ │ ├── auction-1.md +│ │ └── auction-2.md <-- parent: 2023-11 +│ ├── 2023-12/ +│ │ ├── _index.md +│ │ ├── auction-3.md +│ │ └── auction-4.md +│ ├── _index.md <-- parent: home +│ ├── bidding.md +│ └── payment.md <-- parent: auctions +├── books/ +│ ├── _index.md <-- parent: home +│ ├── book-1.md +│ └── book-2.md <-- parent: books +├── films/ +│ ├── _index.md <-- parent: home +│ ├── film-1.md +│ └── film-2.md <-- parent: films +└── _index.md <-- parent: nil +``` + +In the example above, note the parent section of the home page is nil. Code defensively by verifying existence of the parent section before calling methods on its `Page` object. To create a link to the parent section page of the current page: + +```go-html-template +{{ with .Parent }} + {{ .LinkTitle }} +{{ end }} +``` diff --cc docs/content/en/methods/page/Permalink.md index be6df5aad,000000000..d8416df86 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Permalink.md +++ b/docs/content/en/methods/page/Permalink.md @@@ -1,25 -1,0 +1,25 @@@ +--- +title: Permalink +description: Returns the permalink of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/RelPermalink + returnType: string + signatures: [PAGE.Permalink] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +title = 'Documentation' +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ $page := .Site.GetPage "/about" }} - {{ $page.RelPermalink }} → https://example.org/docs/about/ ++{{ $page.Permalink }} → https://example.org/docs/about/ +``` diff --cc docs/content/en/methods/page/Prev.md index cde83b0f2,000000000..b1a503af5 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Prev.md +++ b/docs/content/en/methods/page/Prev.md @@@ -1,53 -1,0 +1,53 @@@ +--- +title: Prev +description: Returns the previous page in a global page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Next + - methods/page/PrevInSection + - methods/page/NextInSection + - methods/pages/Prev + - methods/pages/Next - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.Prev] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .Next }} + Prev +{{ end }} + +{{ with .Prev }} + Next +{{ end }} +``` + +## Compare to Pages methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --cc docs/content/en/methods/page/PrevInSection.md index 30b813350,000000000..c09e4580f mode 100644,000000..100644 --- a/docs/content/en/methods/page/PrevInSection.md +++ b/docs/content/en/methods/page/PrevInSection.md @@@ -1,72 -1,0 +1,72 @@@ +--- +title: PrevInSection +description: Returns the previous page within a section, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/NextInSection + - methods/page/Next + - methods/pages/Next + - methods/page/Prev + - methods/pages/Prev - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGE.PrevInSection] +--- + + +The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect. + +With this content structure: + +```text +content/ +├── books/ +│ ├── _index.md +│ ├── book-1.md +│ ├── book-2.md +│ └── book-3.md +├── films/ +│ ├── _index.md +│ ├── film-1.md +│ ├── film-2.md +│ └── film-3.md +└── _index.md +``` + +When you visit book-2: + +- The `PrevInSection` method points to book-3 +- The `NextInSection` method points to book-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ with .NextInSection }} + Previous in section +{{ end }} + +{{ with .PrevInSection }} + Next in section +{{ end }} +``` + +{{% note %}} +The navigation sort order may be different than the page collection sort order. +{{% /note %}} + +With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugo’s default sort order. In order of precedence: + +1. Page [weight] +2. Page [date] (descending) +3. Page [linkTitle], falling back to page [title] +4. Page file path if the page is backed by a file + +For example, with a page collection sorted by title, the navigation sort order will use Hugo’s default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice. + +[date]: /methods/page/date +[weight]: /methods/page/weight +[linkTitle]: /methods/page/linktitle +[title]: /methods/page/title diff --cc docs/content/en/methods/page/RelPermalink.md index 8a5972ccc,000000000..817e3c862 mode 100644,000000..100644 --- a/docs/content/en/methods/page/RelPermalink.md +++ b/docs/content/en/methods/page/RelPermalink.md @@@ -1,25 -1,0 +1,25 @@@ +--- +title: RelPermalink +description: Returns the relative permalink of the given page. +categories: [] +keywords: [] +action: + related: + - methods/page/Permalink + returnType: string + signatures: [PAGE.RelPermalink] +--- + +Site configuration: + +{{< code-toggle file=hugo >}} +title = 'Documentation' +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ $page := .Site.GetPage "/about" }} - {{ $page.Permalink }} → /docs/about/ ++{{ $page.RelPermalink }} → /docs/about/ +``` diff --cc docs/content/en/methods/page/Resources.md index a9fa3dab2,000000000..140b50020 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Resources.md +++ b/docs/content/en/methods/page/Resources.md @@@ -1,81 -1,0 +1,85 @@@ +--- +title: Resources +description: Returns a collection of page resources. +categories: [] +keywords: [] +action: + related: + - functions/resources/ByType + - functions/resources/Get + - functions/resources/GetMatch + - functions/resources/GetRemote + - functions/resources/Match + returnType: resource.Resources + signatures: [PAGE.Resources] +toc: true +--- + +The `Resources` method on a `Page` object returns a collection of page resources. A page resource is a file within a [page bundle]. + +To work with global or remote resources, see the [`resources`] functions. + +## Methods + - ByType - : (`resource.Resources`) Returns a collection of page resources of the given [media type], or nil if none found. The media type is typically one of `image`, `text`, `audio`, `video`, or `application`. ++###### ByType ++ ++(`resource.Resources`) Returns a collection of page resources of the given [media type], or nil if none found. The media type is typically one of `image`, `text`, `audio`, `video`, or `application`. + +```go-html-template +{{ range .Resources.ByType "image" }} + +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.ByType`] function. + - Get - : (`resource.Resource`) Returns a page resource from the given path, or nil if none found. ++###### Get ++ ++(`resource.Resource`) Returns a page resource from the given path, or nil if none found. + +```go-html-template +{{ with .Resources.Get "images/a.jpg" }} + +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.Get`] function. + - GetMatch - : (`resource.Resource`) Returns the first page resource from paths matching the given [glob pattern], or nil if none found. ++###### GetMatch ++ ++(`resource.Resource`) Returns the first page resource from paths matching the given [glob pattern], or nil if none found. + +```go-html-template +{{ with .Resources.GetMatch "images/*.jpg" }} + +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.GetMatch`] function. + - Match - : (`resource.Resources`) Returns a collection of page resources from paths matching the given [glob pattern], or nil if none found. ++###### Match ++ ++(`resource.Resources`) Returns a collection of page resources from paths matching the given [glob pattern], or nil if none found. + +```go-html-template +{{ range .Resources.Match "images/*.jpg" }} + +{{ end }} +``` + +When working with global resources instead of page resources, use the [`resources.Match`] function. + +## Pattern matching + +With the `GetMatch` and `Match` methods, Hugo determines a match using a case-insensitive [glob pattern]. + +{{% include "functions/_common/glob-patterns.md" %}} + +[`resources.ByType`]: /functions/resources/ByType +[`resources.GetMatch`]: /functions/resources/ByType +[`resources.Get`]: /functions/resources/ByType +[`resources.Match`]: /functions/resources/ByType +[`resources`]: /functions/resources +[glob pattern]: https://github.com/gobwas/glob#example +[media type]: https://en.wikipedia.org/wiki/Media_type +[page bundle]: /getting-started/glossary/#page-bundle diff --cc docs/content/en/methods/page/Store.md index 04e1d5256,000000000..8bc16034b mode 100644,000000..100644 --- a/docs/content/en/methods/page/Store.md +++ b/docs/content/en/methods/page/Store.md @@@ -1,97 -1,0 +1,104 @@@ +--- +title: Store +description: Creates a persistent "scratch pad" on the given page to store and manipulate data. +categories: [] +keywords: [] +action: + related: + - methods/page/scratch + - functions/collections/NewScratch + returnType: maps.Scratch + signatures: [PAGE.Store] +aliases: [/functions/store] +--- + +The `Store` method on a `Page` object creates a persistent [scratch pad] to store and manipulate data. In contrast with the [`Scratch`] method, the scratch pad created by the `Store` method is not reset on server rebuilds. + +To create a locally scoped scratch pad that is not attached to a `Page` object, use the [`newScratch`] function. + +[`Scratch`]: /methods/page/scratch +[`newScratch`]: functions/collections/newscratch +[scratch pad]: /getting-started/glossary/#scratch-pad + +## Methods + - Set - : Sets the value of a given key. ++###### Set ++ ++Sets the value of a given key. + +```go-html-template +{{ .Store.Set "greeting" "Hello" }} +``` + - Get - : Gets the value of a given key. ++###### Get ++ ++Gets the value of a given key. + +```go-html-template +{{ .Store.Set "greeting" "Hello" }} +{{ .Store.Get "greeting" }} → Hello +``` + - Add - : Adds a given value to existing value(s) of the given key. ++###### Add + - : For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. ++Adds a given value to existing value(s) of the given key. ++ ++For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. + +```go-html-template +{{ .Store.Set "greeting" "Hello" }} +{{ .Store.Add "greeting" "Welcome" }} +{{ .Store.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ .Store.Set "total" 3 }} +{{ .Store.Add "total" 7 }} +{{ .Store.Get "total" }} → 10 +``` + +```go-html-template +{{ .Store.Set "greetings" (slice "Hello") }} +{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }} +{{ .Store.Get "greetings" }} → [Hello Welcome Cheers] +``` + - SetInMap - : Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. ++###### SetInMap ++ ++Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. + +```go-html-template +{{ .Store.SetInMap "greetings" "english" "Hello" }} +{{ .Store.SetInMap "greetings" "french" "Bonjour" }} +{{ .Store.Get "greetings" }} → map[english:Hello french:Bonjour] +``` + - DeleteInMap - : Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. ++###### DeleteInMap ++ ++Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. + +```go-html-template +{{ .Store.SetInMap "greetings" "english" "Hello" }} +{{ .Store.SetInMap "greetings" "french" "Bonjour" }} +{{ .Store.DeleteInMap "greetings" "english" }} +{{ .Store.Get "greetings" }} → map[french:Bonjour] +``` + - GetSortedMapValues - : Returns an array of values from `key` sorted by `mapKey`. ++###### GetSortedMapValues ++ ++Returns an array of values from `key` sorted by `mapKey`. + +```go-html-template +{{ .Store.SetInMap "greetings" "english" "Hello" }} +{{ .Store.SetInMap "greetings" "french" "Bonjour" }} +{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour] +``` + - Delete - : Removes the given key. ++###### Delete ++ ++Removes the given key. + +```go-html-template +{{ .Store.Set "greeting" "Hello" }} +{{ .Store.Delete "greeting" }} +``` diff --cc docs/content/en/methods/page/Translations.md index 7aaee75ab,000000000..1ed256630 mode 100644,000000..100644 --- a/docs/content/en/methods/page/Translations.md +++ b/docs/content/en/methods/page/Translations.md @@@ -1,88 -1,0 +1,89 @@@ +--- +title: Translations +description: Returns all translation of the given page, excluding the current language. +categories: [] +keywords: [] +action: + related: + - methods/page/AllTranslations + - methods/page/IsTranslated + - methods/page/TranslationKey + returnType: page.Pages + signatures: [PAGE.Translations] +--- + +With this site configuration: + +{{< code-toggle file=hugo >}} +defaultContentLanguage = 'en' + +[languages.en] +contentDir = 'content/en' +languageCode = 'en-US' +languageName = 'English' +weight = 1 + +[languages.de] +contentDir = 'content/de' +languageCode = 'de-DE' +languageName = 'Deutsch' +weight = 2 + +[languages.fr] +contentDir = 'content/fr' +languageCode = 'fr-FR' +languageName = 'Français' +weight = 3 +{{< /code-toggle >}} + +And this content: + +```text +content/ +├── de/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── en/ +│ ├── books/ +│ │ ├── book-1.md +│ │ └── book-2.md +│ └── _index.md +├── fr/ +│ ├── books/ +│ │ └── book-1.md +│ └── _index.md +└── _index.md +``` + +And this template: + +```go-html-template +{{ with .Translations }} + +{{ end }} +``` + +Hugo will render this list on the "Book 1" page of the English site: + +```html + +``` + +Hugo will render this list on the "Book 2" page of the English site: + +```html + +``` diff --cc docs/content/en/methods/page/_common/scratch-methods.md index c09b4aadc,000000000..b2650cdde mode 100644,000000..100644 --- a/docs/content/en/methods/page/_common/scratch-methods.md +++ b/docs/content/en/methods/page/_common/scratch-methods.md @@@ -1,79 -1,0 +1,86 @@@ +--- +# Do not remove front matter. +--- + +## Methods + - Set - : Sets the value of a given key. ++###### Set ++ ++Sets the value of a given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +``` + - Get - : Gets the value of a given key. ++###### Get ++ ++Gets the value of a given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.Get "greeting" }} → Hello +``` + - Add - : Adds a given value to existing value(s) of the given key. ++###### Add + - : For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. ++Adds a given value to existing value(s) of the given key. ++ ++For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.Add "greeting" "Welcome" }} +{{ .Scratch.Get "greeting" }} → HelloWelcome +``` + +```go-html-template +{{ .Scratch.Set "total" 3 }} +{{ .Scratch.Add "total" 7 }} +{{ .Scratch.Get "total" }} → 10 +``` + +```go-html-template +{{ .Scratch.Set "greetings" (slice "Hello") }} +{{ .Scratch.Add "greetings" (slice "Welcome" "Cheers") }} +{{ .Scratch.Get "greetings" }} → [Hello Welcome Cheers] +``` + - SetInMap - : Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. ++###### SetInMap ++ ++Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`. + +```go-html-template +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +{{ .Scratch.Get "greetings" }} → map[english:Hello french:Bonjour] +``` + - DeleteInMap - : Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. ++###### DeleteInMap ++ ++Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. + +```go-html-template +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +{{ .Scratch.DeleteInMap "greetings" "english" }} +{{ .Scratch.Get "greetings" }} → map[french:Bonjour] +``` + - GetSortedMapValues - : Returns an array of values from `key` sorted by `mapKey`. ++###### GetSortedMapValues ++ ++Returns an array of values from `key` sorted by `mapKey`. + +```go-html-template +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +{{ .Scratch.GetSortedMapValues "greetings" }} → [Hello Bonjour] +``` + - Delete - : Removes the given key. ++###### Delete ++ ++Removes the given key. + +```go-html-template +{{ .Scratch.Set "greeting" "Hello" }} +{{ .Scratch.Delete "greeting" }} +``` diff --cc docs/content/en/methods/pages/Next.md index 638822e5d,000000000..b7284609f mode 100644,000000..100644 --- a/docs/content/en/methods/pages/Next.md +++ b/docs/content/en/methods/pages/Next.md @@@ -1,55 -1,0 +1,55 @@@ +--- +title: Next +description: Returns the next page in a local page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/pages/Prev + - methods/page/Next + - methods/page/NextInSection + - methods/page/Prev + - methods/page/PrevInSection - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [PAGES.Next PAGE] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect. + +With this content structure and the page collection sorted by weight in ascending order: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }} + +{{ with $pages.Next . }} + Previous +{{ end }} + +{{ with $pages.Prev . }} + Next +{{ end }} +``` + +## Compare to Page methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --cc docs/content/en/methods/pages/Prev.md index 3a4dcfd1d,000000000..b9ef27a45 mode 100644,000000..100644 --- a/docs/content/en/methods/pages/Prev.md +++ b/docs/content/en/methods/pages/Prev.md @@@ -1,55 -1,0 +1,55 @@@ +--- +title: Prev +description: Returns the previous page in a local page collection, relative to the given page. +categories: [] +keywords: [] +action: + related: + - methods/pages/Next + - methods/page/Next + - methods/page/NextInSection + - methods/page/Prev + - methods/page/PrevInSection - returnType: hugolib.pageStates ++ returnType: page.Pages + signatures: [PAGES.Prev PAGE] +toc: true +--- + +The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect. + +With this content structure and the page collection sorted by weight in ascending order: + +```text +content/ +├── pages/ +│ ├── _index.md +│ ├── page-1.md <-- front matter: weight = 10 +│ ├── page-2.md <-- front matter: weight = 20 +│ └── page-3.md <-- front matter: weight = 30 +└── _index.md +``` + +When you visit page-2: + +- The `Prev` method points to page-3 +- The `Next` method points to page-1 + +{{% note %}} +Use the opposite label in your navigation links as shown in the example below. +{{% /note %}} + +```go-html-template +{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }} + +{{ with $pages.Next . }} + Previous +{{ end }} + +{{ with $pages.Prev . }} + Next +{{ end }} +``` + +## Compare to Page methods + +{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}} diff --cc docs/content/en/methods/resource/Exif.md index 75071153a,000000000..765b4c92f mode 100644,000000..100644 --- a/docs/content/en/methods/resource/Exif.md +++ b/docs/content/en/methods/resource/Exif.md @@@ -1,78 -1,0 +1,78 @@@ +--- +title: Exif - description: Applicable to images, returns an EXIF object containing image metadata. ++description: Applicable to JPEG and TIFF images, returns an EXIF object containing image metadata. +categories: [] +keywords: [] +action: + related: [] + returnType: exif.ExifInfo + signatures: [RESOURCE.Exif] +toc: true +--- + - Applicable to images, the `Exif` method on an image `Resource` object returns an [EXIF] object containing image metadata. ++Applicable to JPEG and TIFF images, the `Exif` method on an image `Resource` object returns an [EXIF] object containing image metadata. + +## Methods + +Date +: (`time.Time`) Returns the image creation date/time. Format with the [`time.Format`]function. + +Lat +: (`float64`) Returns the GPS latitude in degrees. + +Long +: (`float64`) Returns the GPS longitude in degrees. + +Tags +: (`exif.Tags`) Returns a collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration]. + +## Examples + +To list the creation date, location, and EXIF tags: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .Exif }} +

Date: {{ .Date }}

+

Lat/Long: {{ .Lat }}/{{ .Long }}

+ {{ with .Tags }} +

Tags

+ + + + + + {{ range $k, $v := . }} + + {{ end }} + +
TagValue
{{ $k }}{{ $v }}
+ {{ end }} + {{ end }} +{{ end }} +``` + +To list specific values: + +```go-html-template +{{ with resources.Get "images/a.jpg" }} + {{ with .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 }} +{{ end }} +``` + +{{% include "methods/resource/_common/global-page-remote-resources.md" %}} + +[exif]: https://en.wikipedia.org/wiki/Exif +[site configuration]: /content-management/image-processing/#exif-data +[`time.Format`]: /functions/time/format diff --cc docs/content/en/methods/shortcode/Page.md index c9262ab48,000000000..8bb58fa18 mode 100644,000000..100644 --- a/docs/content/en/methods/shortcode/Page.md +++ b/docs/content/en/methods/shortcode/Page.md @@@ -1,36 -1,0 +1,36 @@@ +--- +title: Page +description: Returns the Page object from which the shortcode was called. +categories: [] +keywords: [] +action: + related: [] + returnType: hugolib.pageForShortcode + signatures: [SHORTCODE.Page] +--- + +With this content: + +{{< code-toggle file=content/books/les-miserables.md fm=true >}} +title = 'Les Misérables' +author = 'Victor Hugo' - published = 1862 ++publication_year = 1862 +isbn = '978-0451419439' +{{< /code-toggle >}} + +Calling this shortcode: + +```text +{{}} +``` + +We can access the front matter values using the `Page` method: + +{{< code file=layouts/shortcodes/book-details.html >}} +
    +
  • Title: {{ .Page.Title }}
  • +
  • Author: {{ .Page.Params.author }}
  • +
  • Published: {{ .Page.Params.publication_year }}
  • +
  • ISBN: {{ .Page.Params.isbn }}
  • +
+{{< /code >}} diff --cc docs/content/en/methods/site/DisqusShortname.md index 359b836af,000000000..2d4447485 mode 100644,000000..100644 --- a/docs/content/en/methods/site/DisqusShortname.md +++ b/docs/content/en/methods/site/DisqusShortname.md @@@ -1,20 -1,0 +1,17 @@@ +--- +title: DisqusShortname +description: Returns the Disqus shortname as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.DisqusShortname] - # deprecated 2023-10-30 - expiryDate: 2024-10-30 - _build: - list: never ++expiryDate: 2024-10-30 # deprecated 2023-10-30 +--- + +{{% deprecated-in 0.120.0 %}} +Use [`Site.Config.Services.Disqus.Shortname`] instead. + +[`Site.Config.Services.Disqus.Shortname`]: /methods/site/config +{{% /deprecated-in %}} diff --cc docs/content/en/methods/site/GetPage.md index 1e949f37c,000000000..b7d4b8f32 mode 100644,000000..100644 --- a/docs/content/en/methods/site/GetPage.md +++ b/docs/content/en/methods/site/GetPage.md @@@ -1,109 -1,0 +1,109 @@@ +--- +title: GetPage +description: Returns a Page object from the given path. +categories: [] +keywords: [] +action: + related: + - methods/page/GetPage - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [SITE.GetPage PATH] +toc: true +--- + +The `GetPage` method is also available on `Page` objects, allowing you to specify a path relative to the current page. See [details]. + +[details]: /methods/page/getpage + +When using the `GetPage` method on a `Site` object, specify a path relative to the content directory. + +If Hugo cannot resolve the path to a page, the method returns nil. + +Consider this content structure: + +```text +content/ +├── works/ +│ ├── paintings/ +│ │ ├── _index.md +│ │ ├── starry-night.md +│ │ └── the-mona-lisa.md +│ ├── sculptures/ +│ │ ├── _index.md +│ │ ├── david.md +│ │ └── the-thinker.md +│ └── _index.md +└── _index.md +``` + +This home page template: + +```go-html-template +{{ with .Site.GetPage "/works/paintings" }} +
    + {{ range .Pages }} +
  • {{ .Title }} by {{ .Params.artist }}
  • + {{ end }} +
+{{ end }} +``` + +Is rendered to: + +```html +
    +
  • Starry Night by Vincent van Gogh
  • +
  • The Mona Lisa by Leonardo da Vinci
  • +
+``` + +To get a regular page instead of a section page: + +```go-html-template +{{ with .Site.GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Starry Night + {{ .Params.artist }} → Vincent van Gogh +{{ end }} +``` + +## Multilingual projects + +With multilingual projects, the `GetPage` method on a `Site` object resolves the given path to a page in the current language. + +To get a page from a different language, query the `Sites` object: + +```go-html-template +{{ with where .Site.Sites "Language.Lang" "eq" "de" }} + {{ with index . 0 }} + {{ with .GetPage "/works/paintings/starry-night" }} + {{ .Title }} → Sternenklare Nacht + {{ end }} + {{ end }} +{{ end }} +``` + +## Page bundles + +Consider this content structure: + +```text +content/ +├── headless/ +│ ├── a.jpg +│ ├── b.jpg +│ ├── c.jpg +│ └── index.md <-- front matter: headless = true +└── _index.md +``` + +In the home page template, use the `GetPage` method on a `Site` object to render all the images in the headless [page bundle]: + +```go-html-template +{{ with .Site.GetPage "/headless" }} + {{ range .Resources.ByType "image" }} + + {{ end }} +{{ end }} +``` + +[page bundle]: /getting-started/glossary/#page-bundle diff --cc docs/content/en/methods/site/GoogleAnalytics.md index 405cf0de5,000000000..50f479b49 mode 100644,000000..100644 --- a/docs/content/en/methods/site/GoogleAnalytics.md +++ b/docs/content/en/methods/site/GoogleAnalytics.md @@@ -1,20 -1,0 +1,17 @@@ +--- +title: GoogleAnalytics +description: Returns the Google Analytics tracking ID as defined in the site configuration. +categories: [] +keywords: [] +action: + related: [] + returnType: string + signatures: [SITE.GoogleAnalytics] - # deprecated 2023-10-30 - expiryDate: 2024-10-30 - _build: - list: never ++expiryDate: 2024-10-30 # deprecated 2023-10-30 +--- + +{{% deprecated-in 0.120.0 %}} +Use [`Site.Config.Services.GoogleAnalytics.ID`] instead. + +[`Site.Config.Services.GoogleAnalytics.ID`]: /methods/site/config +{{% /deprecated-in %}} diff --cc docs/content/en/methods/site/Home.md index 52612dd12,000000000..a25491a8e 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,25 @@@ +--- +title: Home +description: Returns the home Page object for the given site. +categories: [] +keywords: [] +action: + related: [] - returnType: hugolib.pageState ++ returnType: page.Page + signatures: [SITE.Home] +--- + +This method is useful for obtaining a link to the home page. + +Site configuration: + +{{< code-toggle file=hugo >}} +baseURL = 'https://example.org/docs/' +{{< /code-toggle >}} + +Template: + +```go-html-template +{{ .Site.Home.Permalink }} → https://example.org/docs/ +{{ .Site.Home.RelPermalink }} → /docs/ +``` diff --cc docs/content/en/methods/site/IsDevelopment.md index fdeae15fa,000000000..c009ba0de mode 100644,000000..100644 --- a/docs/content/en/methods/site/IsDevelopment.md +++ b/docs/content/en/methods/site/IsDevelopment.md @@@ -1,20 -1,0 +1,21 @@@ +--- +title: IsDevelopment +description: Reports whether the current running environment is “development”. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.IsDevelopment] - # deprecated 2023-10-30 - expiryDate: 2024-10-30 - _build: - list: never ++expiryDate: 2024-10-30 # deprecated 2023-10-30 +--- + +{{% deprecated-in 0.120.0 %}} +Use [`hugo.IsDevelopment`] instead. + +[`hugo.IsDevelopment`]: /functions/hugo/isdevelopment +{{% /deprecated-in %}} ++ ++```go-html-template ++{{ .Site.IsDevelopment }} → true/false ++``` diff --cc docs/content/en/methods/site/IsServer.md index c19a84bc9,000000000..3d5ce41b5 mode 100644,000000..100644 --- a/docs/content/en/methods/site/IsServer.md +++ b/docs/content/en/methods/site/IsServer.md @@@ -1,20 -1,0 +1,21 @@@ +--- +title: IsServer +description: Reports whether the built-in development server is running. +categories: [] +keywords: [] +action: + related: [] + returnType: bool + signatures: [SITE.IsServer] - # deprecated 2023-10-30 - expiryDate: 2024-10-30 - _build: - list: never ++expiryDate: 2024-10-30 # deprecated 2023-10-30 +--- + +{{% deprecated-in 0.120.0 %}} +Use [`hugo.IsServer`] instead. + +[`hugo.IsServer`]: /functions/hugo/isserver +{{% /deprecated-in %}} ++ ++```go-html-template ++{{ .Site.IsServer }} → true/false ++``` diff --cc docs/content/en/methods/site/Menus.md index 1967a9211,000000000..c204fe97b mode 100644,000000..100644 --- a/docs/content/en/methods/site/Menus.md +++ b/docs/content/en/methods/site/Menus.md @@@ -1,94 -1,0 +1,94 @@@ +--- +title: Menus +description: Returns a collection of menu objects for the given site. +categories: [] +keywords: [] +action: + related: + - methods/page/IsMenuCurrent + - methods/page/HasMenuCurrent + returnType: navigation.Menus + signatures: [SITE.Menus] +--- + +The `Menus` method on a `Site` object returns a collection of menus, where each menu contains one or more entries, either flat or nested. Each entry points to a page within the site, or to an external resource. + +{{% note %}} +Menus can be defined and localized in several ways. Please see the [menus] section for a complete explanation and examples. + +[menus]: /content-management/menus/ +{{% /note %}} + +A site can have multiple menus. For example, a main menu and a footer menu: + +{{< code-toggle file=hugo >}} - [[menu.main]] ++[[menus.main]] +name = 'Home' +pageRef = '/' +weight = 10 + - [[menu.main]] ++[[menus.main]] +name = 'Books' +pageRef = '/books' +weight = 20 + - [[menu.main]] ++[[menus.main]] +name = 'Films' +pageRef = '/films' +weight = 30 + - [[menu.footer]] ++[[menus.footer]] +name = 'Legal' +pageRef = '/legal' +weight = 10 + - [[menu.footer]] ++[[menus.footer]] +name = 'Privacy' +pageRef = '/privacy' +weight = 20 +{{< /code-toggle >}} + +This template renders the main menu: + +```go-html-template +{{ with site.Menus.main }} + +{{ end }} +``` + +When viewing the home page, the result is: + +```html + +``` + +When viewing the "books" page, the result is: + +```html + +``` + +You will typically render a menu using a partial template. As the active menu entry will be different on each page, use the [`partial`] function to call the template. Do not use the [`partialCached`] function. + +The example above is simplistic. Please see the [menu templates] section for more information. + +[menu templates]: /templates/menu-templates + +[`partial`]: /functions/partials/include +[`partialCached`]: /functions/partials/includecached diff --cc docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md index 57c9e8e29,000000000..9c94729ba mode 100644,000000..100644 --- a/docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md +++ b/docs/content/en/methods/taxonomy/_common/ordered-taxonomy-element-methods.md @@@ -1,25 -1,0 +1,25 @@@ +--- +# Do not remove front matter. +--- + +An ordered taxonomy is a slice, where each element is an object that contains the term and a slice of its weighted pages. + +Each element of the slice provides these methods: + +Count +: (`int`) Returns the number of pages to which the term is assigned. + +Page - : (`hugolib.pageState`) Returns the term's `Page` object, useful for linking to the term page. ++: (`page.Page`) Returns the term's `Page` object, useful for linking to the term page. + +Pages +: (`page.Pages`) Returns a `Pages` object containing the `Page` objects to which the term is assigned, sorted by [taxonomic weight]. To sort or group, use any of the [methods] available to the `Pages` object. For example, sort by the last modification date. + +Term +: (`string`) Returns the term name. + +WeightedPages +: (`page.WeightedPages`) Returns a slice of weighted pages to which the term is assigned, sorted by [taxonomic weight]. The `Pages` method above is more flexible, allowing you to sort and group. + +[methods]: /methods/pages +[taxonomic weight]: /getting-started/glossary/#taxonomic-weight diff --cc docs/content/en/showcase/digitalgov/index.md index 4376bbf03,000000000..3db2c608f mode 100644,000000..100644 --- a/docs/content/en/showcase/digitalgov/index.md +++ b/docs/content/en/showcase/digitalgov/index.md @@@ -1,64 -1,0 +1,64 @@@ +--- +title: Digital.gov +date: 2020-05-01 +description: "Showcase: \"Guidance on building better digital services in government.\"" +siteURL: https://digital.gov/ +siteSource: https://github.com/gsa/digitalgov.gov +--- + +For over a decade, Digital.gov has provided guidance, training, and community support to the people who are responsible for delivering digital services in the U.S. government. Essentially, it is a place where people can find examples of problems being solved in government, and get links to the tools and resources they need. + +Through collaboration in our communities of practice, Digital.gov is a window into the people who work in technology in government and the challenges they face making digital services stronger and more effective. [Read more about our site »](https://digital.gov/2019/12/19/a-new-digitalgov/) + +Digital.gov is built using the [U.S. Web Design System](https://designsystem.digital.gov/) (USWDS) and have followed the [design principles](https://designsystem.digital.gov/maturity-model/) in building out our new site: + +- **Start with real user needs** — We used human-centered design methods to inform our product decisions (like qualitative user research), and gathered feedback from real users. We also continually test our assumptions with small experiments. +- **Earn trust** —We recognize that trust has to be earned every time. We are including all [required links and content](https://digital.gov/resources/required-web-content-and-links/) on our site, clearly identifying as a government site, building with modern best practices, and using HTTPS. +- **Embrace accessibility** — [Accessibility](https://digital.gov/resources/intro-accessibility/) affects everybody, and we built it into every decision. We’re continually working to conform to Section 508 requirements, use user experience best practices, and support a wide range of devices. +- **Promote continuity** — We started from shared solutions like USWDS and [Federalist](https://federalist.18f.gov/). We designed our site to clearly identify as a government site by including USWDS’s .gov banner, common colors and patterns, and built with modern best practices. +- **Listen** — We actively collect user feedback and web metrics. We use the [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) and analyze the data to discover actionable insights. We make small, incremental changes to continuously improve our website by listening to readers and learning from what we hear. + +_More on the [USWDS maturity model »](https://designsystem.digital.gov/maturity-model/)_ + +## Open tools + +We didn’t start from scratch. We built and designed the Digital.gov using many of the open-source tools and services that we develop for government here in the [Technology Transformation Services](https://www.gsa.gov/tts/) (TTS). + +Using services that make it possible to design, build, and iterate quickly are essential to modern web design and development, which is why [Federalist](https://federalist.18f.gov/) and the [U.S. Web Design System](https://designsystem.digital.gov/) are such a great combination. + +**Why Hugo?** Well, with around `~3,000` files _(and growing)_ and `~9,000` built pages, we needed a site generator that could handle that volume with lightning fast speed. + +Hugo was the clear option. The [Federalist](https://federalist.18f.gov/) team quickly added it to their available site generators, and we were off. + +At the moment, it takes around `32 seconds` to build close to `~10,000` pages! + +Take a look: + +```text + + | EN +-------------------+------- + Pages | 7973 + Paginator pages | 600 + Non-page files | 108 + Static files | 851 + Processed images | 0 + Aliases | 1381 + Sitemaps | 1 + Cleaned | 0 + +Built in 32.427 seconds +``` + +In addition to Hugo, we are proudly using a number of other tools and services, all built by government are free to use: + +- [Federalist](https://federalist.18f.gov/) +- [Search.gov](https://www.search.gov/) — A free, hosted search platform for federal websites. +- [Cloud.gov](https://www.cloud.gov/) — helps teams build, run, and authorize cloud-ready or legacy government systems quickly and cheaply. - - [Federal CrowdSource Mobile Testing Program](https://digital.gov/services/mobile-application-testing-program/) — Free mobile compatibility testing by feds, for feds. ++- [Federal CrowdSource Mobile Testing Program](https://digital.gov/services/service_mobile-testing-program/) — Free mobile compatibility testing by feds, for feds. +- [Digital Analytics Program](https://digital.gov/services/dap/) (DAP) — A free analytics tool for measuring digital services in the federal government +- [Section508.gov](https://www.section508.gov/) and [PlainLanguage.gov](https://www.plainlanguage.gov/) resources +- [API.data.gov](https://api.data.gov/) — a free API management service for federal agencies +- [U.S. Digital Registry](https://digital.gov/services/u-s-digital-registry/) — A resource for confirming the official status of government social media accounts, mobile apps, and mobile websites. + +**Questions or feedback?** [Submit an issue](https://github.com/GSA/digitalgov.gov/issues) or send us an email to [digitalgov@gsa.gov](mailto:digitalgov@gsa.gov) :heart: diff --cc docs/content/en/templates/internal.md index 0785318ab,000000000..9438bfa6f mode 100644,000000..100644 --- a/docs/content/en/templates/internal.md +++ b/docs/content/en/templates/internal.md @@@ -1,221 -1,0 +1,221 @@@ +--- +title: Internal templates +description: Hugo ships with a group of boilerplate templates that cover the most common use cases for static websites. +categories: [templates] +keywords: [internal, analytics,] +menu: + docs: + parent: templates + weight: 190 +weight: 190 +toc: true +--- + +{{% note %}} +While the following internal templates are called similar to partials, they do *not* observe the partial template lookup order. +{{% /note %}} + +## Google Analytics + +Hugo ships with an internal template supporting [Google Analytics 4]. + +[Google Analytics 4]: https://support.google.com/analytics/answer/10089681 + +### Configure Google Analytics + +Provide your tracking ID in your configuration file: + +**Google Analytics 4 (gtag.js)** - {{< code-toggle file="hugo" >}} ++{{< code-toggle file=hugo >}} +[services.googleAnalytics] +ID = "G-MEASUREMENT_ID" +{{}} + +### Use the Google Analytics template + +Include the Google Analytics internal template in your templates where you want the code to appear: + +```go-html-template +{{ template "_internal/google_analytics.html" . }} +``` + +To create your own template, access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`. + +## Disqus + +Hugo also ships with an internal template for [Disqus comments][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][disqussignup]. + +### Configure 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` + +### Use the Disqus template + +To add Disqus, include the following line in the templates where you want your comments to appear: + +```go-html-template +{{ template "_internal/disqus.html" . }} +``` + +### Conditional loading of Disqus comments + +Users have noticed that enabling Disqus comments when running the Hugo web server on `localhost` (i.e. via `hugo server`) causes the creation of unwanted discussions on the associated Disqus account. + +You can create the following `layouts/partials/disqus.html`: + +{{< code file=layouts/partials/disqus.html >}} +
+ + +comments powered by Disqus +{{< /code >}} + +The `if` statement skips the initialization of the Disqus comment injection when you are running on `localhost`. + +You can then render your custom Disqus partial template as follows: + +```go-html-template +{{ partial "disqus.html" . }} +``` + +## Open Graph + +An internal 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. + +### Configure Open Graph + +Hugo's Open Graph template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages. + +{{< code-toggle file=hugo >}} +[params] + title = "My cool site" + images = ["site-feature-image.jpg"] + description = "Text about my cool site" +[taxonomies] + series = "series" +{{}} + +{{< code-toggle file=content/blog/my-post.md >}} +title = "Post title" +description = "Text about this post" +date = "2006-01-02" +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*` or `*cover*,*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`). + +### Use the Open Graph template + +To add Open Graph metadata, include the following line between the `` tags in your templates: + +```go-html-template +{{ template "_internal/opengraph.html" . }} +``` + +## Twitter Cards + +An internal template for [Twitter Cards](https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/abouts-cards), +metadata used to attach rich media to Tweets linking to your site. + +### Configure Twitter Cards + +Hugo's Twitter Card template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) 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 >}} +title = "Post title" +description = "Text about this post" +images = ["post-cover.png"] +{{}} + +If `images` aren't specified in the page front-matter, then hugo searches for [image page resources](/content-management/image-processing/) with `feature`, `cover`, or `thumbnail` in their name. +If no image resources with those names are found, the images defined in the [site config](/getting-started/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" copy=false >}} +[params.social] +twitter = "GoHugoIO" +{{}} + +NOTE: The `@` will be added for you + +```html + +``` + +### Use the Twitter Cards template + +To add Twitter card metadata, include the following line immediately after the `` element in your templates: + +```go-html-template +{{ template "_internal/twitter_cards.html" . }} +``` + +## The internal templates + +The code for these templates is located [here](https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates). + +* `_internal/disqus.html` +* `_internal/google_analytics.html` +* `_internal/opengraph.html` +* `_internal/pagination.html` +* `_internal/schema.html` +* `_internal/twitter_cards.html` + +[disqus]: https://disqus.com +[disqussignup]: https://disqus.com/profile/signup/ diff --cc docs/content/en/templates/lookup-order.md index 2a24c03ac,000000000..406a17c38 mode 100644,000000..100644 --- a/docs/content/en/templates/lookup-order.md +++ b/docs/content/en/templates/lookup-order.md @@@ -1,136 -1,0 +1,136 @@@ +--- +title: Template lookup order +description: Hugo uses the rules below to select a template for a given page, starting from the most specific. +categories: [templates,fundamentals] +keywords: [templates] +menu: + docs: + parent: templates + weight: 30 +weight: 30 +toc: true +--- + +## Lookup rules + +Hugo takes the parameters listed below into consideration when choosing a template for a given page. The templates are ordered by specificity. This should feel natural, but look at the table below for concrete examples of the different parameter variations. + +Kind +: The page `Kind` (the home page is one). See the example tables below per kind. This also determines if it is a **single page** (i.e. a regular content page. We then look for a template in `_default/single.html` for HTML) or a **list page** (section listings, home page, taxonomy lists, taxonomy terms. We then look for a template in `_default/list.html` for HTML). + +Layout +: Can be set in front matter. + +Output Format - : See [Custom Output Formats](/templates/output-formats). An output format has both a `name` (e.g. `rss`, `amp`, `html`) and a `suffix` (e.g. `xml`, `html`). We prefer matches with both (e.g. `index.amp.html`, but look for less specific templates. ++: See [Custom Output Formats](/templates/output-formats). An output format has both a `name` (e.g. `rss`, `amp`, `html`) and a `suffix` (e.g. `xml`, `html`). We prefer matches with both (e.g. `index.amp.html`), but look for less specific templates. + +Note that if the output format's Media Type has more than one suffix defined, only the first is considered. + +Language +: We will consider a language tag in the template name. If the site language is `fr`, `index.fr.amp.html` will win over `index.amp.html`, but `index.amp.html` will be chosen before `index.fr.html`. + +Type +: Is value of `type` if set in front matter, else it is the name of the root section (e.g. "blog"). It will always have a value, so if not set, the value is "page". + +Section +: Is relevant for `section`, `taxonomy` and `term` types. + +{{% note %}} +Templates can live in either the project's or the themes' layout folders, and the most specific templates will be chosen. Hugo will interleave the lookups listed below, finding the most specific one either in the project or themes. +{{% /note %}} + +## Target a template + +You cannot change the lookup order to target a content page, but you can change a content page to target a template. Specify `type`, `layout`, or both in front matter. + +Consider this content structure: + +```text +content/ +├── about.md +└── contact.md +``` + +Files in the root of the content directory have a [content type] of `page`. To render these pages with a unique template, create a matching subdirectory: + +[content type]: /getting-started/glossary/#content-type + +```text +layouts/ +└── page/ + └── single.html +``` + +But the contact page probably has a form and requires a different template. In the front matter specify `layout`: + +{{< code-toggle file=content/contact.md >}} +title = 'Contact' +layout = 'contact' +{{< /code-toggle >}} + +Then create the template for the contact page: + +```text +layouts/ +└── page/ + └── contact.html <-- renders contact.md + └── single.html <-- renders about.md +``` + +As a content type, the word `page` is vague. Perhaps `miscellaneous` would be better. Add `type` to the front matter of each page: + +{{< code-toggle file=content/about.md >}} +title = 'About' +type = 'miscellaneous' +{{< /code-toggle >}} + +{{< code-toggle file=content/contact.md >}} +title = 'Contact' +type = 'miscellaneous' +layout = 'contact' +{{< /code-toggle >}} + +Now place the layouts in the corresponding directory: + +```text +layouts/ +└── miscellaneous/ + └── contact.html <-- renders contact.md + └── single.html <-- renders about.md +``` + +## Home page + +{{< datatable-filtered "output" "layouts" "Kind == home" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}} + +## Single pages + +{{< datatable-filtered "output" "layouts" "Kind == page" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}} + +## Section pages + +A section page is a list of pages within a given section. + +{{< datatable-filtered "output" "layouts" "Kind == section" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}} + +## Taxonomy pages + +A taxonomy page is a list of terms within a given taxonomy. The examples below assume the following site configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +category = 'categories' +{{< /code-toggle >}} + +{{< datatable-filtered "output" "layouts" "Kind == taxonomy" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}} + +## Term pages + +A term page is a list of pages associated with a given term. The examples below assume the following site configuration: + +{{< code-toggle file=hugo >}} +[taxonomies] +category = 'categories' +{{< /code-toggle >}} + +{{< datatable-filtered "output" "layouts" "Kind == term" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}} diff --cc docs/content/en/templates/shortcode-templates.md index 4606369b6,000000000..6e3d968cf mode 100644,000000..100644 --- a/docs/content/en/templates/shortcode-templates.md +++ b/docs/content/en/templates/shortcode-templates.md @@@ -1,412 -1,0 +1,413 @@@ +--- +title: Create your own shortcodes +linkTitle: Shortcode templates +description: You can extend Hugo's built-in shortcodes by creating your own using the same templating syntax as that for single and list pages. +categories: [templates] +keywords: [shortcodes,templates] +menu: + docs: + parent: templates + weight: 130 +weight: 130 +aliases: [/functions/get] +toc: true +--- + +Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside your content. + +{{% note %}} +Hugo also ships with built-in shortcodes for common use cases. (See [Content Management: Shortcodes](/content-management/shortcodes/).) +{{% /note %}} + +## Create custom shortcodes + +Hugo's built-in shortcodes cover many common, but not all, use cases. Luckily, Hugo provides the ability to easily create custom shortcodes to meet your website's needs. + +{{< youtube Eu4zSaKOY4A >}} + +### File location + +To create a shortcode, place an HTML template in the `layouts/shortcodes` directory of your [source organization]. Consider the file name carefully since the shortcode name will mirror that of the file but without the `.html` extension. For example, `layouts/shortcodes/myshortcode.html` will be called with either `{{}}` or `{{%/* myshortcode /*/%}}`. + +You can organize your shortcodes in subdirectories, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g: + +```go-html-template +{{}} +``` + +Note the forward slash. + +### Shortcode template lookup order + +Shortcode templates have a simple [lookup order]: + +1. `/layouts/shortcodes/.html` +2. `/themes//layouts/shortcodes/.html` + +### Positional vs. named parameters + +You can create shortcodes using the following types of parameters: + +* Positional parameters +* Named parameters +* Positional *or* named parameters (i.e, "flexible") + +In shortcodes with positional parameters, the order of the parameters is important. If a shortcode has a single required value (e.g., the `youtube` shortcode below), positional parameters work very well and require less typing from content authors. + +For more complex layouts with multiple or optional parameters, named parameters work best. While less terse, named parameters require less memorization from a content author and can be added in a shortcode declaration in any order. + +Allowing both types of parameters (i.e., a "flexible" shortcode) is useful for complex layouts where you want to set default values that can be easily overridden by users. + +### Access parameters + +All shortcode parameters can be accessed via the `.Get` method. Whether you pass a key (i.e., string) or a number to the `.Get` method depends on whether you are accessing a named or positional parameter, respectively. + +To access a parameter by name, use the `.Get` method followed by the named parameter as a quoted string: + +```go-html-template +{{ .Get "class" }} +``` + +To access a parameter by position, use the `.Get` followed by a numeric position, keeping in mind that positional parameters are zero-indexed: + +```go-html-template +{{ .Get 0 }} +``` + +For the second position, you would just use: + +```go-html-template +{{ .Get 1 }} +``` + +`with` is great when the output depends on a parameter being set: + +```go-html-template +{{ with .Get "class" }} class="{{ . }}"{{ end }} +``` + +`.Get` can also be used to check if a parameter has been provided. This is +most helpful when the condition depends on either of the values, or both: + +```go-html-template +{{ if or (.Get "title") (.Get "alt") }} alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "title" }}{{ end }}"{{ end }} +``` + +#### `.Inner` + +If a closing shortcode is used, the `.Inner` variable will be populated with the content between the opening and closing shortcodes. To check if `.Inner` contains anything other than white space: + +```go-html-template +{{ if strings.ContainsNonSpace .Inner }} + Inner is not empty +{{ end }} +``` + +A shortcode with content declared via the `.Inner` variable can also be declared without the content and without the closing tag by using the self-closing syntax: + +```go-html-template +{{}} +``` + +{{% note %}} +Any shortcode that refers to `.Inner` must be closed or self-closed. + +{{% /note %}} + +#### `.Params` + +The `.Params` variable in shortcodes contains the list parameters passed to shortcode for more complicated use cases. You can also access higher-scoped parameters with the following logic: + +$.Params +: these are the parameters passed directly into the shortcode declaration (e.g., a YouTube video ID) + +$.Page.Params +: refers to the page's parameters; the "page" in this case refers to the content file in which the shortcode is declared (e.g., a `shortcode_color` field in a content's front matter could be accessed via `$.Page.Params.shortcode_color`). + +$.Page.Site.Params +: refers to global variables as defined in your [site's configuration file][config]. + +#### `.IsNamedParams` + +The `.IsNamedParams` variable checks whether the shortcode declaration uses named parameters and returns a boolean value. + +For example, you could create an `image` shortcode that can take either a `src` named parameter or the first positional parameter, depending on the preference of the content's author. Let's assume the `image` shortcode is called as follows: + +```go-html-template +{{}} +``` + +You could then include the following as part of your shortcode templating: + +```go-html-template +{{ if .IsNamedParams }} + +{{ else }} + +{{ end }} +``` + +See the [example Vimeo shortcode][vimeoexample] below for `.IsNamedParams` in action. + +{{% note %}} +While you can create shortcode templates that accept both positional and named parameters, you *cannot* declare shortcodes in content with a mix of parameter types. Therefore, a shortcode declared like `{{}}` will return an error. +{{% /note %}} + +You can also use the variable `.Page` to access all the normal [page variables][pagevars]. + - A shortcodes can also be nested. In a nested shortcode, you can access the parent shortcode context with [`.Parent` variable][shortcodesvars]. This can be very useful for inheritance of common shortcode parameters from the root. ++Shortcodes can also be nested. In a nested shortcode, you can access the parent shortcode context with the [`.Parent`] shortcode method. This can be very useful for inheritance of common shortcode parameters from the root. + +### Checking for existence + +You can check if a specific shortcode is used on a page by calling `.HasShortcode` in that page template, providing the name of the shortcode. This is sometimes useful when you want to include specific scripts or styles in the header that are only used by that shortcode. + +## Custom shortcode examples + +The following are examples of the different types of shortcodes you can create via shortcode template files in `/layouts/shortcodes`. + +### Single-word example: `year` + +Let's assume you would like to keep mentions of your copyright year current in your content files without having to continually review your Markdown. Your goal is to be able to call the shortcode as follows: + +```go-html-template +{{}} +``` + +{{< code file=layouts/shortcodes/year.html >}} +{{ now.Format "2006" }} +{{< /code >}} + +### Single positional example: `youtube` + +Embedded videos are a common addition to Markdown content that can quickly become unsightly. The following is the code used by [Hugo's built-in YouTube shortcode][youtubeshortcode]: + +```go-html-template +{{}} +``` + +Would load the template at `/layouts/shortcodes/youtube.html`: + +{{< code file=layouts/shortcodes/youtube.html >}} +
+ +
+{{< /code >}} + +{{< code file=youtube-embed.html >}} +
+ +
+{{< /code >}} + +### Single named example: `image` + +Let's say you want to create your own `img` shortcode rather than use Hugo's built-in [`figure` shortcode][figure]. Your goal is to be able to call the shortcode as follows in your content files: + +{{< code file=content-image.md >}} +{{}} +{{< /code >}} + +You have created the shortcode at `/layouts/shortcodes/img.html`, which loads the following shortcode template: + +{{< code file=layouts/shortcodes/img.html >}} + +
+ {{ with .Get "link" }}{{ end }} + + {{ if .Get "link" }}{{ end }} + {{ if or (or (.Get "title") (.Get "caption")) (.Get "attr") }} +
{{ if isset .Params "title" }} +

{{ .Get "title" }}

{{ end }} + {{ if or (.Get "caption") (.Get "attr") }}

+ {{ .Get "caption" }} + {{ with .Get "attrlink" }} {{ end }} + {{ .Get "attr" }} + {{ if .Get "attrlink" }} {{ end }} +

{{ end }} +
+ {{ end }} +
+ +{{< /code >}} + +Would be rendered as: + +{{< code file=img-output.html >}} +
+ +
+

Steve Francia

+
+
+{{< /code >}} + +### Single flexible example: `vimeo` + +```go-html-template +{{}} +{{}} +``` + +Would load the template found at `/layouts/shortcodes/vimeo.html`: + +{{< code file=layouts/shortcodes/vimeo.html >}} +{{ if .IsNamedParams }} +
+ +
+{{ else }} +
+ +
+{{ end }} +{{< /code >}} + +Would be rendered as: + +{{< code file=vimeo-iframes.html >}} +
+ +
+
+ +
+{{< /code >}} + +### Paired example: `highlight` + +The following is taken from `highlight`, which is a [built-in shortcode] that ships with Hugo. + +{{< code file=highlight-example.md >}} +{{}} + + This HTML + +{{}} +{{< /code >}} + +The template for the `highlight` shortcode uses the following code, which is already included in Hugo: + +```go-html-template +{{ .Get 0 | highlight .Inner }} +``` + +The rendered output of the HTML example code block will be as follows: + +{{< code file=syntax-highlighted.html >}} +
<html>
 +    <body> This HTML </body>
 +</html>
 +
+{{< /code >}} + +### Nested shortcode: image gallery + - Hugo's [`.Parent` shortcode variable][parent] 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 for common shortcode parameters. ++Hugo's [`.Parent`] shortcode 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 for common shortcode parameters. + +The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` parameter: + +{{< code file=layouts/shortcodes/gallery.html >}} +
+ {{ .Inner }} +
+{{< /code >}} + +You also have an `img` shortcode with a single named `src` parameter that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`: + +{{< code file=layouts/shortcodes/img.html >}} +{{- $src := .Get "src" -}} +{{- with .Parent -}} + +{{- else -}} + +{{- end -}} +{{< /code >}} + +You can then call your shortcode in your content as follows: + +```go-html-template +{{}} + {{}} + {{}} +{{}} +{{}} +``` + +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 + + +``` + +## Error handling in shortcodes + - Use the [errorf](/functions/fmt/errorf) template func and [.Position](/variables/shortcode/) variable to get useful error messages in shortcodes: ++Use the [errorf](/functions/fmt/errorf) template function and [`.Position`] shortcode method to get useful error messages in shortcodes: + +```sh +{{ with .Get "name" }} +{{ else }} +{{ errorf "missing value for parameter 'name': %s" .Position }} +{{ end }} +``` + +When the above fails, you will see an `ERROR` log similar to the below: + +```sh +ERROR 2018/11/07 10:05:55 missing value for parameter name: "/Users/bep/dev/go/gohugoio/hugo/docs/content/en/variables/shortcodes.md:32:1" +``` + +## Inline shortcodes + +You can also implement your shortcodes inline -- e.g. where you use them in the content file. This can be useful for scripting that you only need in one place. + +This feature is disabled by default, but can be enabled in your site configuration: + +{{< code-toggle file=hugo >}} ++[security] +enableInlineShortcodes = true +{{< /code-toggle >}} + +It is disabled by default for security reasons. The security model used by Hugo's template handling assumes that template authors are trusted, but that the content files are not, so the templates are injection-safe from malformed input data. But in most situations you have full control over the content, too, and then `enableInlineShortcodes = true` would be considered safe. But it's something to be aware of: It allows ad-hoc [Go Text templates](https://golang.org/pkg/text/template/) to be executed from the content files. + +And once enabled, you can do this in your content files: + + ```go-html-template + {{}}{{ now }}{{}} + ``` + +The above will print the current date and time. + + Note that an inline shortcode's inner content is parsed and executed as a Go text template with the same context as a regular shortcode template. + +This means that the current page can be accessed via `.Page.Title` etc. This also means that there are no concept of "nested inline shortcodes". + +The same inline shortcode can be reused later in the same content file, with different parameters if needed, using the self-closing syntax: + + ```go-html-template +{{}} +``` + +[basic content files]: /content-management/formats/ +[built-in shortcode]: /content-management/shortcodes/ +[config]: /getting-started/configuration/ +[Content Management: Shortcodes]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes +[source organization]: /getting-started/directory-structure/ +[docsshortcodes]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes +[figure]: /content-management/shortcodes/#figure +[hugosc]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes +[lookup order]: /templates/lookup-order/ +[pagevars]: /variables/page/ - [parent]: /variables/shortcode/ - [shortcodesvars]: /variables/shortcode/ ++[`.Parent`]: /methods/shortcode/parent/ ++[`.Position`]: /methods/shortcode/position/ +[spfscs]: https://github.com/spf13/spf13.com/tree/master/layouts/shortcodes +[vimeoexample]: #single-flexible-example-vimeo +[youtubeshortcode]: /content-management/shortcodes/#youtube diff --cc docs/content/en/tools/search.md index 041174118,000000000..c3db0dc98 mode 100644,000000..100644 --- a/docs/content/en/tools/search.md +++ b/docs/content/en/tools/search.md @@@ -1,55 -1,0 +1,55 @@@ +--- +title: Search tools +linkTitle: Search +description: See some of the open-source and commercial search options for your newly created Hugo website. +categories: [developer tools] +keywords: [search] +menu: + docs: + parent: developer-tools + weight: 40 +weight: 40 +toc: true +--- + +A static website with a dynamic search function? Yes, Hugo provides an alternative to embeddable scripts from Google or other search engines for static websites. Hugo allows you to provide your visitors with a custom search function by indexing your content files directly. + +## Open source + +[Pagefind](https://github.com/cloudcannon/pagefind) +: A fully static search library that aims to perform well on large sites, while using as little of your users' bandwidth as possible. + +[GitHub Gist for Hugo Workflow](https://gist.github.com/sebz/efddfc8fdcb6b480f567) +: This gist contains a simple workflow to create a search index for your static website. It uses a simple Grunt script to index all your content files and [lunr.js](https://lunrjs.com/) to serve the search results. + +[hugo-lunr](https://www.npmjs.com/package/hugo-lunr) +: A simple way to add site search to your static Hugo site using [lunr.js](https://lunrjs.com/). Hugo-lunr will create an index file of any HTML and Markdown documents in your Hugo project. + +[hugo-lunr-zh](https://www.npmjs.com/package/hugo-lunr-zh) +: A bit like Hugo-lunr, but Hugo-lunr-zh can help you separate the Chinese keywords. + +[GitHub Gist for Fuse.js integration](https://gist.github.com/eddiewebb/735feb48f50f0ddd65ae5606a1cb41ae) - : This gist demonstrates how to leverage Hugo's existing build time processing to generate a searchable JSON index used by [Fuse.js](https://fusejs.io/) on the client-side. Although this gist uses Fuse.js for fuzzy matching, any client-side search tool capable of reading JSON indexes will work. Does not require npm, grunt or other build-time tools except Hugo! ++: This gist demonstrates how to leverage Hugo's existing build time processing to generate a searchable JSON index used by [Fuse.js](https://fusejs.io/) on the client-side. Although this gist uses Fuse.js for fuzzy matching, any client-side search tool capable of reading JSON indexes will work. Does not require npm, grunt, or other build-time tools except Hugo! + +[hugo-search-index](https://www.npmjs.com/package/hugo-search-index) +: A library containing Gulp tasks and a prebuilt browser script that implements search. Gulp generates a search index from project markdown files. + +[hugofastsearch](https://gist.github.com/cmod/5410eae147e4318164258742dd053993) +: A usability and speed update to "GitHub Gist for Fuse.js integration" — global, keyboard-optimized search. + +[JS & Fuse.js tutorial](https://makewithhugo.com/add-search-to-a-hugo-site/) +: A simple client-side search solution, using FuseJS (does not require jQuery). + +[Hugo Lyra](https://github.com/paolomainardi/hugo-lyra) +: Hugo-Lyra is a JavaScript module to integrate [Lyra](https://github.com/LyraSearch/lyra) into a Hugo website. It contains the server-side part to generate the index and the client-side library (optional) to bootstrap the search engine easily. + +## Commercial + +[Algolia](https://www.algolia.com/) +: Algolia's Search API makes it easy to deliver a great search experience in your apps and websites. Algolia Search provides hosted full-text, numerical, faceted, and geolocalized search. + +[Bonsai](https://www.bonsai.io) - : Bonsai is a fully-managed hosted Elasticsearch service that is fast, reliable, and simple to set up. Easily ingest your docs from Hugo into Elasticsearch following [this guide from the docs](https://docs.bonsai.io/hc/en-us/articles/13929190788756-Hugo). ++: Bonsai is a fully-managed hosted Elasticsearch service that is fast, reliable, and simple to set up. Easily ingest your docs from Hugo into Elasticsearch following [this guide from the docs](https://bonsai.io/docs/hugo). + +[ExpertRec](https://www.expertrec.com/) +: ExpertRec is a hosted search-as-a-service solution that is fast and scalable. Set-up and integration is extremely easy and takes only a few minutes. The search settings can be modified without coding using a dashboard. diff --cc docs/content/en/troubleshooting/deprecation.md index 9aef54e8a,000000000..aa4bb71a2 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/deprecation.md +++ b/docs/content/en/troubleshooting/deprecation.md @@@ -1,50 -1,0 +1,50 @@@ +--- +title: Deprecation +description: The Hugo project follows a formal and consistent process to deprecate functions, methods, and configuration settings. +categories: [troubleshooting] +keywords: [] +menu: + docs: + parent: troubleshooting + weight: 50 +weight: 50 +--- + +When a project _deprecates_ something, they are telling its users: + +1. Don't use Thing One anymore. +2. Use Thing Two instead. +3. We're going to remove Thing One at some point in the future. + - [article]: https://en.wikipedia.org/wiki/Deprecation ++[reasons for deprecation]: https://en.wikipedia.org/wiki/Deprecation + - Think of deprecation as a statement of intent. This Wikipedia [article] describes common reasons for deprecation: ++Common [reasons for deprecation]: + - - The feature has been replaced by a more powerful alternative. - - The feature contains a design flaw. - - The feature is considered extraneous, and will be removed in the future in order to simplify the system as a whole. ++- A feature has been replaced by a more powerful alternative. ++- A feature contains a design flaw. ++- A feature is considered extraneous, and will be removed in the future in order to simplify the system as a whole. +- A future version of the software will make major structural changes, making it impossible or impractical to support older features. +- Standardization or increased consistency in naming. +- A feature that once was available only independently is now combined with its co-feature. + +After the project team deprecates something in code, Hugo will: + +1. Log an INFO message for 6 minor releases[^1] +2. Log a WARN message for another 6 minor releases +3. Log an ERROR message and fail the build thereafter + +To see the INFO messages, you must use the `--logLevel` command line flag: + +```text +hugo --logLevel info +``` + +To limit the output to deprecation notices: + +```text +hugo --logLevel info | grep deprecate +``` + +Run the above command every time you upgrade Hugo. + +[^1]: For example, v0.1.1 => v0.2.0 is a minor release. diff --cc docs/content/en/troubleshooting/faq.md index dc6204777,000000000..0425ca277 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/faq.md +++ b/docs/content/en/troubleshooting/faq.md @@@ -1,124 -1,0 +1,124 @@@ +--- +title: Frequently asked questions +linkTitle: FAQs +description: These questions are frequently asked by new users. +categories: [troubleshooting] +keywords: [faq] +menu: + docs: + parent: troubleshooting + weight: 70 +weight: 70 +# Use level 6 headings for each question. +--- + +Hugo’s [forum] is an active community of users and developers who answer questions, share knowledge, and provide examples. A quick search of over 20,000 topics will often answer your question. Please be sure to read about [requesting help] before asking your first question. + +These are just a few of the questions most frequently asked by new users. + +###### An error message indicates that a feature is not available. Why? + +Hugo is available in two editions: standard and extended. With the extended edition you can (a) encode to the WebP format when processing images, and (b) transpile Sass to CSS using the embedded LibSass transpiler. The extended edition is not required to use the Dart Sass transpiler. + +When you attempt to perform either of the operations above with the standard edition, Hugo throws this error: + +```go-html-template +Error: this feature is not available in your current Hugo version +``` + +To resolve, uninstall the standard edition, then install the extended edition. See the [installation] section for details. + +###### Why do I see "Page Not Found" when visiting the home page? + +In the content/_index.md file: + + - Is `draft` set to `true`? + - Is the `date` in the future? + - Is the `publishDate` in the future? + - Is the `expiryDate` in the past? + +If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`. + +###### Why is a given section not published? + +In the content/section/_index.md file: + + - Is `draft` set to `true`? + - Is the `date` in the future? + - Is the `publishDate` in the future? + - Is the `expiryDate` in the past? + +If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`. + +###### Why is a given page not published? + +In the content/section/page.md file, or in the content/section/page/index.md file: + + - Is `draft` set to `true`? + - Is the `date` in the future? + - Is the `publishDate` in the future? + - Is the `expiryDate` in the past? + +If the answer to any of these questions is yes, either change the field values, or use one of these command line flags: `--buildDrafts`, `--buildFuture`, or `--buildExpired`. + +###### Why can't I see any of a page's descendants? + +You may have an index.md file instead of an _index.md file. See [details](/content-management/page-bundles/). + +###### What is the difference between an index.md file and an _index.md file? + +A directory with an index.md file is a [leaf bundle]. A directory with an _index.md file is a [branch bundle]. See [details](/content-management/page-bundles/). + +[branch bundle]: /getting-started/glossary/#branch-bundle +[leaf bundle]: /getting-started/glossary/#leaf-bundle + +###### Why is my partial template not rendered as expected? {#foo} + +You may have neglected to pass the required [context] when calling the partial. For example: + +```go-html-template +{{/* incorrect */}} +{{ partial "_internal/pagination.html" }} + +{{/* correct */}} +{{ partial "_internal/pagination.html" . }} +``` + +###### In a template, what's the difference between `:=` and `=` when assigning values to variables? + +Use `:=` to initialize a variable, and use `=` to assign a value to a variable that has been previously initialized. See [details](https://pkg.go.dev/text/template#hdr-Variables). + +###### When I paginate a list page, why is the page collection not filtered as specified? + +You are probably invoking the [`Paginate`] or [`Paginator`] method more than once on the same page. See [details](/templates/pagination/#list-paginator-pages). + +###### Why are there two ways to call a shortcode? + +Use the `{{%/* shortcode */%}}` notation if the shortcode template, or the content between the opening and closing shortcode tags, contains markdown. Otherwise use the\ +`{{}}` notation. See [details](/content-management/shortcodes/). + +###### Can I use environment variables to control configuration? + +Yes. See [details](/getting-started/configuration/#configure-with-environment-variables). + +###### Why am I seeing inconsistent output from one build to the next? + +The most common causes are page collisions (publishing two pages to the same path) and the effects of concurrency. Use the `--printPathWarnings` command line flag to check for page collisions, and create a topic on the [forum] if you suspect concurrency problems. + +###### Which page methods trigger content rendering? + - The following methods on a `Page` object triggering content rendering: `Content`, `FuzzyWordCount`, `Len`, `Plain`, `PlainWords`, `ReadingTime`, `Summary`, `Truncated`, and `WordCount`. ++The following methods on a `Page` object trigger content rendering: `Content`, `FuzzyWordCount`, `Len`, `Plain`, `PlainWords`, `ReadingTime`, `Summary`, `Truncated`, and `WordCount`. + +{{% note %}} +For other questions please visit the [forum]. 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. + +[forum]: https://discourse.gohugo.io +[requesting help]: https://discourse.gohugo.io/t/requesting-help/9132 +{{% /note %}} + +[`Paginate`]: /methods/page/paginate +[`Paginator`]: /methods/page/paginator +[context]: /getting-started/glossary/#context +[forum]: https://discourse.gohugo.io +[installation]: /installation +[requesting help]: https://discourse.gohugo.io/t/requesting-help/9132 diff --cc docs/content/en/troubleshooting/performance.md index 589d30df6,000000000..174d6cfd9 mode 100644,000000..100644 --- a/docs/content/en/troubleshooting/performance.md +++ b/docs/content/en/troubleshooting/performance.md @@@ -1,94 -1,0 +1,94 @@@ +--- +title: Performance +description: Use template metrics and timers to identify opportunities to improve performance. +categories: [troubleshooting] +keywords: [] +menu: + docs: + parent: troubleshooting + weight: 60 +weight: 60 +toc: true +aliases: [/troubleshooting/build-performance/] +--- + +## Template metrics + - Hugo is fast, but inefficient templates impede performance. Enable template metrics to determine which templates take the most time, and to identify caching opportunties: ++Hugo is fast, but inefficient templates impede performance. Enable template metrics to determine which templates take the most time, and to identify caching opportunities: + +```sh +hugo --templateMetrics --templateMetricsHints +``` + +The result will look something like this: + +```text +Template Metrics: + + cumulative average maximum cache percent cached total + duration duration duration potential cached count count template + ---------- -------- -------- --------- ------- ------ ----- -------- + 36.037476822s 135.990478ms 225.765245ms 11 0 0 265 partials/head.html + 35.920040902s 164.018451ms 233.475072ms 0 0 0 219 articles/single.html + 34.163268129s 128.917992ms 224.816751ms 23 0 0 265 partials/head/meta/opengraph.html + 1.041227437s 3.92916ms 186.303376ms 47 0 0 265 partials/head/meta/schema.html + 805.628827ms 27.780304ms 114.678523ms 0 0 0 29 _default/list.html + 624.08354ms 15.221549ms 108.420729ms 8 0 0 41 partials/utilities/render-page-collection.html + 545.968801ms 775.523µs 105.045775ms 0 0 0 704 _default/summary.html + 334.680981ms 1.262947ms 127.412027ms 100 0 0 265 partials/head/js.html + 272.763205ms 2.050851ms 24.371757ms 0 0 0 133 _default/_markup/render-codeblock.html + 230.490038ms 8.865001ms 177.4615ms 0 0 0 26 shortcodes/template.html + 176.921913ms 176.921913ms 176.921913ms 0 0 0 1 examples.tmpl + 163.951469ms 14.904679ms 70.267953ms 0 0 0 11 articles/list.html + 153.07021ms 577.623µs 73.593597ms 100 0 0 265 partials/head/init.html + 150.910984ms 150.910984ms 150.910984ms 0 0 0 1 _default/single.html + 146.785804ms 146.785804ms 146.785804ms 0 0 0 1 _default/contact.html + 115.364617ms 115.364617ms 115.364617ms 0 0 0 1 authors/term.html + 87.392071ms 329.781µs 10.687132ms 100 0 0 265 partials/head/css.html + 86.803122ms 86.803122ms 86.803122ms 0 0 0 1 _default/home.html +``` + +From left to right, the columns represent: + +cumulative duration +: The cumulative time spent executing the template. + +average duration +: The average time spent executing the template. + +maximum duration +: The maximum time spent executing the template. + +cache potential +: Displayed as a percentage, any partial template with a 100% cache potential should be called with the [`partialCached`] function instead of the [`partial`] function. See the [caching](#caching) section below. + +percent cached +: The number of times the rendered templated was cached divided by the number of times the template was executed. + +cached count +: The number of times the rendered templated was cached. + +total count +: The number of times the template was executed. + +template +: The path to the template, relative to the layouts directory. + +[`partial`]: /functions/partials/include +[`partialCached`]: /functions/partials/includecached + +{{% note %}} +Hugo builds pages in parallel where multiple pages are generated simultaneously. Because of this parallelism, the sum of "cumulative duration" values is usually greater than the actual time it takes to build a site. +{{% /note %}} + +## Caching + +Some partial templates such as sidebars or menus are executed many times during a site build. Depending on the content within the partial template and the desired output, the template may benefit from caching to reduce the number of executions. The [`partialCached`] template function provides caching capabilities for partial templates. + +{{% note %}} +Note that you can create cached variants of each partial by passing additional parameters to `partialCached` beyond the initial context. See the `partialCached` documentation for more details. +{{% /note %}} + +## Timers + +Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottle necks in templates. See [details](/functions/debug/timer/). diff --cc docs/go.mod index b53b245e1,000000000..ac58db6b3 mode 100644,000000..100644 --- a/docs/go.mod +++ b/docs/go.mod @@@ -1,5 -1,0 +1,5 @@@ +module github.com/gohugoio/hugoDocs + +go 1.16 + - require github.com/gohugoio/gohugoioTheme v0.0.0-20231111235806-77931ac4875e // indirect ++require github.com/gohugoio/gohugoioTheme v0.0.0-20240125093153-bea12fdc0b15 // indirect diff --cc docs/go.sum index d8cea868c,000000000..3d66fb551 mode 100644,000000..100644 --- a/docs/go.sum +++ b/docs/go.sum @@@ -1,2 -1,0 +1,4 @@@ - github.com/gohugoio/gohugoioTheme v0.0.0-20231111235806-77931ac4875e h1:X4OxWNt7weGfmRHBAQWW1gsdZBd3V/6DJMNhrYS9ALE= - github.com/gohugoio/gohugoioTheme v0.0.0-20231111235806-77931ac4875e/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM= ++github.com/gohugoio/gohugoioTheme v0.0.0-20240108005931-638ffe386bd2 h1:wa2rkKQnFxJK0czyiCiKgJZZ9fQQlzn1iFsuKryffHE= ++github.com/gohugoio/gohugoioTheme v0.0.0-20240108005931-638ffe386bd2/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM= ++github.com/gohugoio/gohugoioTheme v0.0.0-20240125093153-bea12fdc0b15 h1:NJvuWADEYyNmpyRScXC/1dIwy6kqLDkwB9GP3Wq4W+I= ++github.com/gohugoio/gohugoioTheme v0.0.0-20240125093153-bea12fdc0b15/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM= diff --cc docs/hugo.toml index 026743466,000000000..209231663 mode 100644,000000..100644 --- a/docs/hugo.toml +++ b/docs/hugo.toml @@@ -1,95 -1,0 +1,100 @@@ +# This his the main configuration file. There are also environment specific configuration stored in the /config directory. + +baseURL = "https://gohugo.io/" +defaultContentLanguage = "en" +enableEmoji = true +ignoreErrors = ["error-remote-getjson", "error-missing-instagram-accesstoken"] +languageCode = "en-us" +paginate = 100 +pluralizeListTitles = false +timeZone = "Europe/Oslo" +title = "Hugo" + +# We do redirects via Netlify's _redirects file, generated by Hugo (see "outputs" below). +disableAliases = true + +[services.googleAnalytics] +ID = 'G-MBZGKNMDWC' + +[minify] + [minify.tdewolff] + [minify.tdewolff.html] + keepWhitespace = true + +[module] + [module.hugoVersion] + min = "0.56.0" + [[module.imports]] + path = "github.com/gohugoio/gohugoioTheme" + +[outputs] + home = ["HTML", "RSS", "REDIR", "HEADERS"] + section = ["HTML", "RSS"] + +[mediaTypes] + [mediaTypes."text/netlify"] + delimiter = "" + +[outputFormats] + [outputFormats.REDIR] + mediatype = "text/netlify" + baseName = "_redirects" + isPlainText = true + notAlternative = true + [outputFormats.HEADERS] + mediatype = "text/netlify" + baseName = "_headers" + isPlainText = true + notAlternative = true + +[caches] + [caches.getjson] + dir = ":cacheDir/:project" + maxAge = -1 + [caches.getcsv] + dir = ":cacheDir/:project" + maxAge = -1 + [caches.images] + dir = ":cacheDir/images" + maxAge = "1440h" + [caches.assets] + dir = ":resourceDir/_gen" + maxAge = -1 + [caches.getresource] + dir = ":cacheDir/:project" + maxage = '1h' + +[related] + threshold = 80 + includeNewer = true + toLower = false + [[related.indices]] + name = "keywords" + weight = 60 + [[related.indices]] + # Can be used as a front matter slice to link to other page fragments (headings) using their ID. + # This isn't particular useful in the current docs, but we're planning on getting a auto generated + # reference section with a better ID setup. + # For now, we just use it to give pages with same headings some similarity score. + name = "fragmentrefs" + type = "fragments" + applyFilter = false + weight = 60 + cardinalityThreshold = 50 + +[imaging] + # See https://github.com/disintegration/imaging + # CatmullRom is a sharp bicubic filter which should fit the docs site well with its many screenshots. + # Note that you can also set this per image processing. + resampleFilter = "CatmullRom" + # Default JPEG quality setting. Default is 75. + quality = 75 + anchor = "smart" + +[taxonomies] + category = "categories" ++ ++[[cascade]] ++categories = ['commands'] ++[cascade._target] ++path = '/commands/**' diff --cc docs/netlify.toml index cc46695a5,000000000..7c5633da8 mode 100644,000000..100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@@ -1,30 -1,0 +1,30 @@@ +[build] + publish = "public" + command = "hugo --gc --minify" + + [build.environment] - HUGO_VERSION = "0.120.4" ++ HUGO_VERSION = "0.121.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" + +[context.branch-deploy] + command = "hugo --gc --minify -b $DEPLOY_PRIME_URL" + +[context.next.environment] + HUGO_ENABLEGITINFO = "true" + +[[redirects]] + from = "/npmjs/*" + to = "/npmjs/" + status = 200