Debian Codegraph @

docs/content/en/templates/shortcode.md

raw
1 ---
2 title: Shortcode templates
3 description: Create custom shortcodes to simplify and standardize content creation.
4 categories: []
5 keywords: []
6 weight: 120
7 aliases: [/templates/shortcode-templates/]
8 ---
9
10 {{< newtemplatesystem >}}
11
12 > [!NOTE]
13 > Before creating custom shortcodes, please review the [shortcodes][] page in the [content management][] section. Understanding the usage details will help you design and create better templates.
14
15 ## Introduction
16
17 Hugo provides [embedded shortcodes][] for many common tasks, but you'll likely need to create your own for more specific needs. Some examples of custom shortcodes you might develop include:
18
19 - Audio players
20 - Video players
21 - Image galleries
22 - Diagrams
23 - Maps
24 - Tables
25 - And many other custom elements
26
27 ## Directory structure
28
29 Create _shortcode_ templates within the `layouts/_shortcodes` directory, either at its root or organized into subdirectories.
30
31 ```tree
32 layouts/
33 └── _shortcodes/
34 ├── diagrams/
35 │ ├── kroki.html
36 │ └── plotly.html
37 ├── media/
38 │ ├── audio.html
39 │ ├── gallery.html
40 │ └── video.html
41 ├── capture.html
42 ├── column.html
43 ├── include.html
44 └── row.html
45 ```
46
47 When calling a shortcode in a subdirectory, specify its path relative to the `_shortcode` directory, excluding the file extension.
48
49 ```md
50 {{</* media/audio path=/audio/podcast/episode-42.mp3 */>}}
51 ```
52
53 ## Lookup order
54
55 Hugo selects _shortcode_ templates based on the shortcode name, the current output format, and the current language. The examples below are sorted by specificity in descending order. The least specific path is at the bottom of the list.
56
57 Shortcode name|Output format|Language|Template path
58 :--|:--|:--|:--
59 foo|html|en|`layouts/_shortcodes/foo.en.html`
60 foo|html|en|`layouts/_shortcodes/foo.html.html`
61 foo|html|en|`layouts/_shortcodes/foo.html`
62 foo|html|en|`layouts/_shortcodes/foo.html.en.html`
63
64 Shortcode name|Output format|Language|Template path
65 :--|:--|:--|:--
66 foo|rss|en|`layouts/_shortcodes/foo.en.rss.xml`
67 foo|rss|en|`layouts/_shortcodes/foo.rss.xml`
68 foo|rss|en|`layouts/_shortcodes/foo.en.xml`
69 foo|rss|en|`layouts/_shortcodes/foo.xml`
70
71 ## Methods
72
73 Use these methods in your _shortcode_ templates. Refer to each method's documentation for details and examples.
74
75 {{% render-list-of-pages-in-section path=/methods/shortcode %}}
76
77 ## Examples
78
79 These examples range in complexity from simple to moderately advanced, with some simplified for clarity.
80
81 ### Insert year
82
83 Create a shortcode to insert the current year:
84
85 ```go-html-template {file="layouts/_shortcodes/year.html"}
86 {{- now.Format "2006" -}}
87 ```
88
89 Then call the shortcode from within your markup:
90
91 ```md {file="content/example.md"}
92 This is {{</* year */>}}, and look at how far we've come.
93 ```
94
95 This shortcode can be used inline or as a block on its own line. If a shortcode might be used inline, remove the surrounding [whitespace][] by using [template action](g) delimiters with hyphens.
96
97 ### Insert image
98
99 This example assumes the following content structure, where `content/example/index.md` is a [page bundle](g) containing one or more [page resources](g).
100
101 ```tree
102 content/
103 ├── example/
104 │ ├── a.jpg
105 │ └── index.md
106 └── _index.md
107 ```
108
109 Create a shortcode to capture an image as a page resource, resize it to the given width, convert it to the WebP format, and add an `alt` attribute:
110
111 ```go-html-template {file="layouts/_shortcodes/image.html"}
112 {{- with .Page.Resources.Get (.Get "path") }}
113 {{- with .Process (printf "resize %dx wepb" ($.Get "width")) -}}
114 <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ $.Get "alt" }}">
115 {{- end }}
116 {{- end -}}
117 ```
118
119 Then call the shortcode from within your markup:
120
121 ```md {file="content/example/index.md"}
122 {{</* image path=a.jpg width=300 alt="A white kitten" */>}}
123 ```
124
125 The example above uses:
126
127 - The [`with`][] statement to rebind the [context](g) after each successful operation
128 - The [`Get`][] method to retrieve arguments by name
129 - The `$` to access the template context
130
131 > [!NOTE]
132 > Make sure that you thoroughly understand the concept of context. The most common templating errors made by new users relate to context.
133 >
134 > Read more about context in the [introduction to templating][].
135
136 ### Insert image with error handling
137
138 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:
139
140 ```go-html-template {file="layouts/_shortcodes/image.html"}
141 {{- with .Get "path" }}
142 {{- with $r := $.Page.Resources.Get ($.Get "path") }}
143 {{- with $.Get "width" }}
144 {{- with $r.Process (printf "resize %dx wepb" ($.Get "width" )) }}
145 {{- $alt := or ($.Get "alt") "" -}}
146 <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ $alt }}">
147 {{- end }}
148 {{- else }}
149 {{- errorf "The %q shortcode requires a 'width' argument: see %s" $.Name $.Position }}
150 {{- end }}
151 {{- else }}
152 {{- warnf "The %q shortcode was unable to find %s: see %s" $.Name ($.Get "path") $.Position }}
153 {{- end }}
154 {{- else }}
155 {{- errorf "The %q shortcode requires a 'path' argument: see %s" .Name .Position }}
156 {{- end -}}
157 ```
158
159 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.
160
161 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:
162
163 ```text
164 ERROR The "image" shortcode requires a 'width' argument: see "/home/user/project/content/example/index.md:7:1"
165 ```
166
167 ### Positional arguments
168
169 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:
170
171 ```md {file="content/example/index.md"}
172 {{</* image path=a.jpg width=300 alt="A white kitten" */>}}
173 ```
174
175 Here's how to call it with positional arguments:
176
177 ```md {file="content/example/index.md"}
178 {{</* image a.jpg 300 "A white kitten" */>}}
179 ```
180
181 Using the `Get` method with zero-indexed keys, we'll initialize variables with descriptive names in our template:
182
183 ```go-html-template {file="layouts/_shortcodes/image.html"}
184 {{ $path := .Get 0 }}
185 {{ $width := .Get 1 }}
186 {{ $alt := .Get 2 }}
187 ```
188
189 > [!NOTE]
190 > 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.
191
192 ### Named and positional arguments
193
194 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:
195
196 ```go-html-template {file="layouts/_shortcodes/image.html"}
197 {{ $path := cond (.IsNamedParams) (.Get "path") (.Get 0) }}
198 {{ $width := cond (.IsNamedParams) (.Get "width") (.Get 1) }}
199 {{ $alt := cond (.IsNamedParams) (.Get "alt") (.Get 2) }}
200 ```
201
202 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.
203
204 ### Argument collection
205
206 Use the [`Params`][] method to access the arguments as a collection.
207
208 When using named arguments, the `Params` method returns a map:
209
210 ```md {file="content/example/index.md"}
211 {{</* image path=a.jpg width=300 alt="A white kitten" */>}}
212 ```
213
214 ```go-html-template {file="layouts/_shortcodes/image.html"}
215 {{ .Params.path }} → a.jpg
216 {{ .Params.width }} → 300
217 {{ .Params.alt }} → A white kitten
218 ```
219
220 When using positional arguments, the `Params` method returns a slice:
221
222 ```md {file="content/example/index.md"}
223 {{</* image a.jpg 300 "A white kitten" */>}}
224 ```
225
226 ```go-html-template {file="layouts/_shortcodes/image.html"}
227 {{ index .Params 0 }} → a.jpg
228 {{ index .Params 1 }} → 300
229 {{ index .Params 1 }} → A white kitten
230 ```
231
232 Combine the `Params` method with the [`collections.IsSet`][] function to determine if a parameter is set, even if its value is falsy.
233
234 ### Inner content
235
236 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.
237
238 ```md {file="content/example.md"}
239 {{</* contrived title="A Contrived Example" */>}}
240 This is a **bold** word, and this is an _emphasized_ word.
241 {{</* /contrived */>}}
242 ```
243
244 ```go-html-template {file="layouts/_shortcodes/contrived.html"}
245 <div class="contrived">
246 <h2>{{ .Get "title" }}</h2>
247 {{ .Inner | .Page.RenderString }}
248 </div>
249 ```
250
251 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][].
252
253 ### Nesting
254
255 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.
256
257 The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` argument:
258
259 ```go-html-template {file="layouts/_shortcodes/gallery.html"}
260 <div class="{{ .Get "class" }}">
261 {{ .Inner }}
262 </div>
263 ```
264
265 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`:
266
267 ```go-html-template {file="layouts/_shortcodes/img.html"}
268 {{ $src := .Get "src" }}
269 {{ with .Parent }}
270 <img src="{{ $src }}" class="{{ .Get "class" }}-image">
271 {{ else }}
272 <img src="{{ $src }}">
273 {{ end }}
274 ```
275
276 You can then call your shortcode in your content as follows:
277
278 ```md {file="content/example.md"}
279 {{</* gallery class="content-gallery" */>}}
280 {{</* img src="/images/one.jpg" */>}}
281 {{</* img src="/images/two.jpg" */>}}
282 {{</* /gallery */>}}
283 {{</* img src="/images/three.jpg" */>}}
284 ```
285
286 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`:
287
288 ```html
289 <div class="content-gallery">
290 <img src="/images/one.jpg" class="content-gallery-image">
291 <img src="/images/two.jpg" class="content-gallery-image">
292 </div>
293 <img src="/images/three.jpg">
294 ```
295
296 ### Rendering order
297
298 The [notation][] used to call a shortcode determines when it executes relative to Markdown rendering:
299
300 1. Shortcodes called using [Markdown notation][] execute before the Markdown renderer, in document order.
301 1. The Markdown renderer runs.
302 1. Shortcodes called using [standard notation][] execute after the Markdown renderer, in document order.
303
304 This means a shortcode called using standard notation that appears earlier in the document still executes after a shortcode called using Markdown notation that appears later.
305
306 Within each phase, shortcodes at the same nesting level execute in document order, top to bottom. When shortcodes are nested, Hugo renders them from the inside out: each nested shortcode executes before its parent. The parent receives the fully rendered output of all nested shortcodes as its [`Inner`][] content.
307
308 For example, given:
309
310 ```md {file="content/example.md"}
311 {{</* outer */>}}
312 {{</* inner-a */>}}
313 {{</* inner-b */>}}
314 {{</* /outer */>}}
315 {{</* standalone */>}}
316 ```
317
318 Hugo renders in this order:
319
320 1. `inner-a`
321 1. `inner-b`
322 1. `outer` (receiving the rendered output of `inner-a` and `inner-b` as `.Inner`)
323 1. `standalone`
324
325 ### Other examples
326
327 For guidance, consider examining Hugo's embedded shortcodes. The source code, available on [GitHub][], can provide a useful model.
328
329 ## Detection
330
331 The [`HasShortcode`][] method allows you to check if a specific shortcode has been called on a page. For example, consider a custom `audio` shortcode:
332
333 ```md {file="content/example.md"}
334 {{</* audio src=/audio/test.mp3 */>}}
335 ```
336
337 You can use the `HasShortcode` method in your _base_ template to conditionally load CSS if the `audio` shortcode was used on the page:
338
339 ```go-html-template {file="layouts/baseof.html"}
340 <head>
341 {{ if .HasShortcode "audio" }}
342 <link rel="stylesheet" src="/css/audio.css">
343 {{ end }}
344 </head>
345 ```
346
347 [GitHub]: https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates/_shortcodes
348 [Markdown notation]: /content-management/shortcodes/#markdown-notation
349 [`Get`]: /methods/shortcode/get/
350 [`HasShortcode`]: /methods/page/hasshortcode/
351 [`Inner`]: /methods/shortcode/inner/
352 [`IsNamedParams`]: /methods/shortcode/isnamedparams/
353 [`Name`]: /methods/shortcode/name/
354 [`Params`]: /methods/shortcode/params/
355 [`Parent`]: /methods/shortcode/parent/
356 [`Position`]: /methods/shortcode/position/
357 [`RenderString`]: /methods/page/renderstring/
358 [`collections.IsSet`]: /functions/collections/isset/
359 [`compare.Conditional`]: /functions/compare/conditional/
360 [`with`]: /functions/go-template/with/
361 [content management]: /content-management/shortcodes/
362 [embedded shortcodes]: /shortcodes/
363 [introduction to templating]: /templates/introduction/
364 [named or positional]: /content-management/shortcodes/#arguments
365 [notation]: /content-management/shortcodes/#notation
366 [shortcodes]: /content-management/shortcodes/
367 [standard notation]: /content-management/shortcodes/#standard-notation
368 [whitespace]: /templates/introduction/#whitespace