From 1a7413a16689e42a6431e357c3ae7cc9e7ab0d7e Mon Sep 17 00:00:00 2001 From: Joe Mooring Date: Thu, 30 Jan 2025 18:12:19 -0800 Subject: [PATCH] Clean up shortcode documentation --- content/en/content-management/shortcodes.md | 242 ++++++-- .../en/getting-started/glossary/shortcode.md | 2 +- content/en/methods/page/Scratch.md | 2 +- content/en/methods/shortcode/Scratch.md | 2 +- content/en/templates/home.md | 78 +-- content/en/templates/section.md | 2 +- content/en/templates/shortcode.md | 551 ++++++++---------- content/en/templates/types/index.md | 16 +- 8 files changed, 495 insertions(+), 400 deletions(-) diff --git a/content/en/content-management/shortcodes.md b/content/en/content-management/shortcodes.md index cd1f2cb43..6e49fc86f 100644 --- a/content/en/content-management/shortcodes.md +++ b/content/en/content-management/shortcodes.md @@ -1,91 +1,241 @@ --- title: Shortcodes -description: Shortcodes are simple snippets inside your content files calling built-in or custom templates. +description: Use embedded, custom, or inline shortcodes to insert elements such as videos, images, and social media embeds into your content. categories: [content management] -keywords: [markdown,content,shortcodes] +keywords: [] menu: docs: parent: content-management weight: 100 weight: 100 -toc: true aliases: [/extras/shortcodes/] -testparam: "Hugo Rocks!" +toc: true --- -## What a shortcode is +## Introduction -Hugo loves Markdown because of its simple content format, but there are times when Markdown falls short. Often, content authors are forced to add raw HTML (e.g., video ` - +{{< code file=layouts/shortcodes/image.html >}} +{{- with .Page.Resources.Get (.Get "path") }} + {{- with .Process (printf "resize %dx wepb" ($.Get "width")) }} + {{ $.Get + {{- end }} +{{- end -}} {{< /code >}} -{{< code file=youtube-embed.html >}} -
- -
+Then call the shortcode from within your markup: + +{{< code file=content/example/index.md >}} +{{}} {{< /code >}} -### Single named example: `image` +The example above uses: -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: +- The [`with`] statement to rebind the [context](g) after each successful operation +- The [`Get`] method to retrieve arguments by name +- The `$` to access the template context -{{< code file=content-image.md >}} -{{}} +[`get`]: /methods/shortcode/get/ +[`with`]: /functions/go-template/with/ + +{{% note %}} +Make sure that you thoroughly understand the concept of context. The most common templating errors made by new users relate to context. + +Read more about context in the [introduction to templating]. + +[introduction to templating]: /templates/introduction/ +{{% /note %}} + +### Insert image with error handling + +The previous example, while functional, silently fails if the image is missing, and does not gracefully exit if a required argument is missing. We'll add error handling to address these issues: + +{{< code file=layouts/shortcodes/image.html >}} +{{ with .Get "path" }} + {{- with $r := $.Page.Resources.Get ($.Get "path") }} + {{- with $.Get "width" }} + {{- with $r.Process (printf "resize %dx wepb" ($.Get "width" )) }} + {{- $alt := or ($.Get "alt") "" }} + {{ $alt }} + {{- end }} + {{- else }} + {{- errorf "The %q shortcode requires a 'width' argument: see %s" $.Name $.Position }} + {{- end }} + {{- else }} + {{ warnf "The %q shortcode was unable to find %s: see %s" $.Name ($.Get "path") $.Position }} + {{- end }} +{{- else }} + {{ errorf "The %q shortcode requires a 'path' argument: see %s" .Name .Position }} +{{- end -}} {{< /code >}} -You have created the shortcode at `/layouts/shortcodes/img.html`, which loads the following shortcode template: +This template throws an error and gracefully fails the build if the author neglected to provide a `path` or `width` argument, and it emits a warning if it cannot find the image at the specified path. If the author does not provide an `alt` argument, the `alt` attribute is set to an empty string. -{{< 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 >}} +The [`Name`] and [`Position`] methods provide helpful context for errors and warnings. For example, a missing `width` argument causes the shortcode to throw this error: -Would be rendered as: +[`name`]: /methods/shortcode/name/ +[`position`]: /methods/shortcode/position/ -{{< code file=img-output.html >}} -
- -
-

Steve Francia

-
-
-{{< /code >}} - -### Single flexible example: `vimeo` - -```go-html-template -{{}} -{{}} +```text +ERROR The "image" shortcode requires a 'width' argument: see "/home/user/project/content/example/index.md:7:1" ``` -Would load the template found at `/layouts/shortcodes/vimeo.html`: +### Positional arguments -{{< code file=layouts/shortcodes/vimeo.html >}} -{{ if .IsNamedParams }} -
- -
-{{ else }} -
- -
-{{ end }} +Shortcode arguments can be [named or positional]. We used named arguments previously; let's explore positional arguments. Here's the named argument version of our example: + +[named or positional]: /content-management/shortcodes/#arguments + +{{< code file=content/example/index.md >}} +{{}} {{< /code >}} -Would be rendered as: +Here's how to call it with positional arguments: -{{< code file=vimeo-iframes.html >}} -
- -
-
- +{{< code file=content/example/index.md >}} +{{}} +{{< /code >}} + +Using the `Get` method with zero-indexed keys, we'll initialize variables with descriptive names in our template: + +{{< code file=layouts/shortcodes/image.html >}} +{{- $path := .Get 0 }} +{{- $width := .Get 1 }} +{{- $alt := .Get 2 }} +{{< /code >}} + +{{% note %}} +Positional arguments work well for frequently used shortcodes with one or two arguments. Since you'll use them often, the argument order will be easy to remember. For less frequently used shortcodes, or those with more than two arguments, named arguments improve readability and reduce the chance of errors. +{{% /note %}} + +### Named and positional arguments + +You can create a shortcode that will accept both named and positional arguments, but not at the same time. Use the [`IsNamedParams`] method to determine whether the shortcode call used named or positional arguments: + +{{< code file=layouts/shortcodes/image.html >}} +{{- $path := cond (.IsNamedParams) (.Get "path") (.Get 0) }} +{{- $width := cond (.IsNamedParams) (.Get "width") (.Get 1) }} +{{- $alt := cond (.IsNamedParams) (.Get "alt") (.Get 2) }} +{{< /code >}} + +This example uses the `cond` alias for the [`compare.Conditional`] function to get the argument by name if `IsNamedParams` returns `true`, otherwise get the argument by position. + +[`compare.Conditional`]: /functions/compare/conditional/ +[`IsNamedParams`]: /methods/shortcode/isnamedparams/ + +### Argument collection + +Use the [`Params`] method to access the arguments as a collection. + +[`Params`]: /methods/shortcode/params/ + +When using named arguments, the `Params` method returns a map: + +{{< code file=content/example/index.md >}} +{{}} +{{< /code >}} + +{{< code file=layouts/shortcodes/image.html >}} +{{- .Params.path }} → a.jpg +{{- .Params.width }} → 300 +{{- .Params.alt }} → A white kitten +{{< /code >}} + + When using positional arguments, the `Params` method returns a slice: + +{{< code file=content/example/index.md >}} +{{}} +{{< /code >}} + +{{< code file=layouts/shortcodes/image.html >}} +{{- index .Params 0 }} → a.jpg +{{- index .Params 1 }} → 300 +{{- index .Params 1 }} → A white kitten +{{< /code >}} + +Combine the `Params` method with the [`collections.IsSet`] function to determine if a parameter is set, even if its value is falsy. + +[`collections.IsSet`]: /functions/collections/isset/ + +### Inner content + +Extract the content enclosed within shortcode tags using the [`Inner`] method. This example demonstrates how to pass both content and a title to a shortcode. The shortcode then generates a `div` element containing an `h2` element (displaying the title) and the provided content. + +[`Inner`]: /methods/shortcode/inner/ + +{{< code file=content/example.md >}} +{{}} +This is a **bold** word, and this is an _emphasized_ word. +{{}} +{{< /code >}} + +{{< code file=layouts/shortcodes/contrived.html >}} +
+

{{ .Get "title" }}

+ {{ .Inner | .Page.RenderString }}
{{< /code >}} -### Paired example: `highlight` +The preceding example called the shortcode using [standard notation], requiring us to process the inner content with the [`RenderString`] method to convert the Markdown to HTML. This conversion is unnecessary when calling a shortcode using [Markdown notation]. -The following is taken from `highlight`, which is a [built-in shortcode] that ships with Hugo. +[`RenderString`]: /methods/page/renderstring/ +[markdown notation]: /content-management/shortcodes/#markdown-notation +[standard notation]: /content-management/shortcodes/#standard-notation -{{< code file=highlight-example.md >}} -{{}} - - This HTML - -{{}} -{{< /code >}} +### Nesting -The template for the `highlight` shortcode uses the following code, which is already included in Hugo: +The [`Parent`] method provides access to the parent shortcode context when the shortcode in question is called within the context of a parent shortcode. This provides an inheritance model. -```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 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. +[`Parent`]: /methods/shortcode/parent/ The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` argument: @@ -333,23 +303,24 @@ The following example is contrived but demonstrates the concept. Assume you have You also have an `img` shortcode with a single named `src` argument that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`: {{< code file=layouts/shortcodes/img.html >}} -{{- $src := .Get "src" -}} -{{- with .Parent -}} +{{ $src := .Get "src" }} +{{ with .Parent }} -{{- else -}} +{{ else }} -{{- end -}} +{{ end }} {{< /code >}} You can then call your shortcode in your content as follows: -```go-html-template +{{< code file=content/example.md >}} {{}} {{}} {{}} {{}} {{}} -``` +{{< /code >}} + 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`: @@ -361,62 +332,30 @@ This will output the following HTML. Note how the first two `img` shortcodes inh ``` -## Error handling in shortcodes +### Other examples -Use the [`errorf`] template function with the [`Name`] and [`Position`] shortcode methods to generate useful error messages: +For guidance, consider examining Hugo's embedded shortcodes. The source code, available on [GitHub], can provide a useful model. -{{< code file=layouts/shortcodes/greeting.html >}} -{{ with .Get "name" }} -

Hello, my name is {{ . }}.

-{{ else }} - {{ errorf "The %q shortcode requires a 'name' argument. See %s" .Name .Position }} -{{ end }} +[GitHub]: https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates/shortcodes + +## Detection + +The [`HasShortcode`] method allows you to check if a specific shortcode has been called on a page. For example, consider a custom audio shortcode: + +{{< code file=content/example.md >}} +{{}} {{< /code >}} -When the above fails, you will see an `ERROR` message such as: +You can use the `HasShortcode` method in your base template to conditionally load CSS if the audio shortcode was used on the page: -```sh -ERROR The "greeting" shortcode requires a 'name' argument. See "/home/user/project/content/_index.md:12:1" -``` +{{< code file=layouts/_default/baseof.html >}} + + ... + {{ if .HasShortcode "audio" }} + + {{ end }} + ... + +{{< /code >}} -## 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 arguments if needed, using the self-closing syntax: - - ```go-html-template -{{}} -``` - -[`.Parent`]: /methods/shortcode/parent/ -[`errorf`]: /functions/fmt/errorf/ -[`Name`]: /methods/shortcode/name/ -[`Position`]: /methods/shortcode/position/ -[built-in shortcode]: /content-management/shortcodes/ -[figure]: /shortcodes/figure/ -[lookup order]: /templates/lookup-order/ -[source organization]: /getting-started/directory-structure/ -[vimeoexample]: #single-flexible-example-vimeo -[youtubeshortcode]: /shortcodes/youtube/ +[`HasShortcode`]: /methods/page/hasshortcode/ diff --git a/content/en/templates/types/index.md b/content/en/templates/types/index.md index 0bd72ccc4..8369917bf 100644 --- a/content/en/templates/types/index.md +++ b/content/en/templates/types/index.md @@ -48,9 +48,7 @@ Hugo's [template lookup order] determines the template path, allowing you to cre [template lookup order]: /templates/lookup-order/ {{% note %}} -You must have thorough understanding of the [template lookup order] when creating templates. Template selection is based on template type, page kind, content type, section, language, and output format. - -[template lookup order]: /templates/lookup-order/ +You must have thorough understanding of the template lookup order when creating templates. Template selection is based on template type, page kind, content type, section, language, and output format. {{% /note %}} The purpose of each template type is described below. @@ -88,9 +86,7 @@ Learn more about [base templates](/templates/base/). ## Home -A home template renders your site's home page. For a single page site this is the only required template. - -For example, the home template below inherits the site's shell from the base template, and renders the home page content with a list of pages. +A home page template is used to render your site's home page, and is the only template required for a single-page website. For example, the home page template below inherits the site's shell from the base template and renders the home page content, such as a list of other pages. {{< code file=layouts/_default/home.html >}} {{ define "main" }} @@ -103,7 +99,7 @@ For example, the home template below inherits the site's shell from the base tem {{% include "templates/_common/filter-sort-group.md" %}} -Learn more about [home templates](/templates/home/). +Learn more about [home page templates](/templates/home/). ## Single @@ -241,7 +237,7 @@ For example, the render hook template below adds a `rel` attribute to external l {{- with .Title }} title="{{ . }}"{{ end -}} {{- if $u.IsAbs }} rel="external"{{ end -}} > - {{- with .Text | safeHTML }}{{ . }}{{ end -}} + {{- with .Text }}{{ . }}{{ end -}} {{- /* chomp trailing newline */ -}} {{< /code >}} @@ -260,10 +256,10 @@ For example, the shortcode template below renders an audio element from a [globa {{ end }} {{< /code >}} -Call the shortcode from your content page: +Then call the shortcode from within markup: {{< code file=content/example.md >}} -{{}} +{{}} {{< /code >}} Learn more about [shortcode templates](/templates/shortcode/).