shortcode-templates.md (17519B)
1 --- 2 title: Create Your Own Shortcodes 3 linktitle: Shortcode Templates 4 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. 5 date: 2017-02-01 6 publishdate: 2017-02-01 7 lastmod: 2017-02-01 8 categories: [templates] 9 keywords: [shortcodes,templates] 10 menu: 11 docs: 12 parent: "templates" 13 weight: 100 14 weight: 100 15 sections_weight: 100 16 draft: false 17 aliases: [] 18 toc: true 19 --- 20 21 Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside of your content. In this sense, you can think of shortcodes as the intermediary between [page and list templates][templates] and [basic content files][]. 22 23 {{% note %}} 24 Hugo also ships with built-in shortcodes for common use cases. (See [Content Management: Shortcodes](/content-management/shortcodes/).) 25 {{% /note %}} 26 27 ## Create Custom Shortcodes 28 29 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. 30 31 {{< youtube Eu4zSaKOY4A >}} 32 33 ### File Location 34 35 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 `{{</* myshortcode /*/>}}` or `{{%/* myshortcode /*/%}}` depending on the type of parameters you choose. 36 37 You can organize your shortcodes in subfolders, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g: 38 39 ``` 40 {{</* boxes/square */>}} 41 ``` 42 43 Note the forward slash. 44 45 ### Shortcode Template Lookup Order 46 47 Shortcode templates have a simple [lookup order][]: 48 49 1. `/layouts/shortcodes/<SHORTCODE>.html` 50 2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html` 51 52 ### Positional vs Named Parameters 53 54 You can create shortcodes using the following types of parameters: 55 56 * Positional parameters 57 * Named parameters 58 * Positional *or* named parameters (i.e, "flexible") 59 60 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. 61 62 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. 63 64 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. 65 66 ### Access Parameters 67 68 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. 69 70 To access a parameter by name, use the `.Get` method followed by the named parameter as a quoted string: 71 72 ``` 73 {{ .Get "class" }} 74 ``` 75 76 To access a parameter by position, use the `.Get` followed by a numeric position, keeping in mind that positional parameters are zero-indexed: 77 78 ``` 79 {{ .Get 0 }} 80 ``` 81 82 For the second position, you would just use: 83 84 ``` 85 {{ .Get 1 }} 86 ``` 87 88 `with` is great when the output depends on a parameter being set: 89 90 ``` 91 {{ with .Get "class" }} class="{{ . }}"{{ end }} 92 ``` 93 94 `.Get` can also be used to check if a parameter has been provided. This is 95 most helpful when the condition depends on either of the values, or both: 96 97 ``` 98 {{ if or (.Get "title") (.Get "alt") }} alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "title" }}{{ end }}"{{ end }} 99 ``` 100 101 #### `.Inner` 102 103 If a closing shortcode is used, the `.Inner` variable will be populated with all of the content between the opening and closing shortcodes. If a closing shortcode is required, you can check the length of `.Inner` as an indicator of its existence. 104 105 A shortcode with content declared via the `.Inner` variable can also be declared without the 106 content and without the closing 107 by using the self-closing syntax: 108 109 ``` 110 {{</* innershortcode /*/>}} 111 ``` 112 113 #### `.Params` 114 115 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: 116 117 `$.Params` 118 : these are the parameters passed directly into the shortcode declaration (e.g., a YouTube video ID) 119 120 `$.Page.Params` 121 : refers to the page's params; 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`). 122 123 `$.Page.Site.Params` 124 : refers to global variables as defined in your [site's configuration file][config]. 125 126 #### `.IsNamedParams` 127 128 The `.IsNamedParams` variable checks whether the shortcode declaration uses named parameters and returns a boolean value. 129 130 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: 131 132 ``` 133 {{</* image src="images/my-image.jpg" */>}} 134 ``` 135 136 You could then include the following as part of your shortcode templating: 137 138 ``` 139 {{ if .IsNamedParams }} 140 <img src="{{ .Get "src" }}" alt=""> 141 {{ else }} 142 <img src="{{ .Get 0 }}" alt=""> 143 {{ end }} 144 ``` 145 146 See the [example Vimeo shortcode][vimeoexample] below for `.IsNamedParams` in action. 147 148 {{% warning %}} 149 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 `{{</* image src="images/my-image.jpg" "This is my alt text" */>}}` will return an error. 150 {{% /warning %}} 151 152 You can also use the variable `.Page` to access all the normal [page variables][pagevars]. 153 154 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. 155 156 ### Checking for Existence 157 158 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. 159 160 ## Custom Shortcode Examples 161 162 The following are examples of the different types of shortcodes you can create via shortcode template files in `/layouts/shortcodes`. 163 164 ### Single-word Example: `year` 165 166 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: 167 168 ``` 169 {{</* year */>}} 170 ``` 171 172 {{< code file="/layouts/shortcodes/year.html" >}} 173 {{ now.Format "2006" }} 174 {{< /code >}} 175 176 ### Single Positional Example: `youtube` 177 178 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]: 179 180 ``` 181 {{</* youtube 09jf3ow9jfw */>}} 182 ``` 183 184 Would load the template at `/layouts/shortcodes/youtube.html`: 185 186 {{< code file="/layouts/shortcodes/youtube.html" >}} 187 <div class="embed video-player"> 188 <iframe class="youtube-player" type="text/html" width="640" height="385" src="https://www.youtube.com/embed/{{ index .Params 0 }}" allowfullscreen frameborder="0"> 189 </iframe> 190 </div> 191 {{< /code >}} 192 193 {{< code file="youtube-embed.html" copy="false" >}} 194 <div class="embed video-player"> 195 <iframe class="youtube-player" type="text/html" 196 width="640" height="385" 197 src="https://www.youtube.com/embed/09jf3ow9jfw" 198 allowfullscreen frameborder="0"> 199 </iframe> 200 </div> 201 {{< /code >}} 202 203 ### Single Named Example: `image` 204 205 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: 206 207 {{< code file="content-image.md" >}} 208 {{</* img src="/media/spf13.jpg" title="Steve Francia" */>}} 209 {{< /code >}} 210 211 You have created the shortcode at `/layouts/shortcodes/img.html`, which loads the following shortcode template: 212 213 {{< code file="/layouts/shortcodes/img.html" >}} 214 <!-- image --> 215 <figure {{ with .Get "class" }}class="{{.}}"{{ end }}> 216 {{ with .Get "link" }}<a href="{{ . }}">{{ end }} 217 <img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "caption" }}{{ end }}"{{ end }} /> 218 {{ if .Get "link" }}</a>{{ end }} 219 {{ if or (or (.Get "title") (.Get "caption")) (.Get "attr") }} 220 <figcaption>{{ if isset .Params "title" }} 221 <h4>{{ .Get "title" }}</h4>{{ end }} 222 {{ if or (.Get "caption") (.Get "attr") }}<p> 223 {{ .Get "caption" }} 224 {{ with .Get "attrlink" }}<a href="{{ . }}"> {{ end }} 225 {{ .Get "attr" }} 226 {{ if .Get "attrlink" }}</a> {{ end }} 227 </p> {{ end }} 228 </figcaption> 229 {{ end }} 230 </figure> 231 <!-- image --> 232 {{< /code >}} 233 234 Would be rendered as: 235 236 {{< code file="img-output.html" copy="false" >}} 237 <figure> 238 <img src="/media/spf13.jpg" /> 239 <figcaption> 240 <h4>Steve Francia</h4> 241 </figcaption> 242 </figure> 243 {{< /code >}} 244 245 ### Single Flexible Example: `vimeo` 246 247 ``` 248 {{</* vimeo 49718712 */>}} 249 {{</* vimeo id="49718712" class="flex-video" */>}} 250 ``` 251 252 Would load the template found at `/layouts/shortcodes/vimeo.html`: 253 254 {{< code file="/layouts/shortcodes/vimeo.html" >}} 255 {{ if .IsNamedParams }} 256 <div class="{{ if .Get "class" }}{{ .Get "class" }}{{ else }}vimeo-container{{ end }}"> 257 <iframe src="https://player.vimeo.com/video/{{ .Get "id" }}" allowfullscreen></iframe> 258 </div> 259 {{ else }} 260 <div class="{{ if len .Params | eq 2 }}{{ .Get 1 }}{{ else }}vimeo-container{{ end }}"> 261 <iframe src="https://player.vimeo.com/video/{{ .Get 0 }}" allowfullscreen></iframe> 262 </div> 263 {{ end }} 264 {{< /code >}} 265 266 Would be rendered as: 267 268 {{< code file="vimeo-iframes.html" copy="false" >}} 269 <div class="vimeo-container"> 270 <iframe src="https://player.vimeo.com/video/49718712" allowfullscreen></iframe> 271 </div> 272 <div class="flex-video"> 273 <iframe src="https://player.vimeo.com/video/49718712" allowfullscreen></iframe> 274 </div> 275 {{< /code >}} 276 277 ### Paired Example: `highlight` 278 279 The following is taken from `highlight`, which is a [built-in shortcode][] that ships with Hugo. 280 281 {{< code file="highlight-example.md" >}} 282 {{</* highlight html */>}} 283 <html> 284 <body> This HTML </body> 285 </html> 286 {{</* /highlight */>}} 287 {{< /code >}} 288 289 The template for the `highlight` shortcode uses the following code, which is already included in Hugo: 290 291 ``` 292 {{ .Get 0 | highlight .Inner }} 293 ``` 294 295 The rendered output of the HTML example code block will be as follows: 296 297 {{< code file="syntax-highlighted.html" copy="false" >}} 298 <div class="highlight" style="background: #272822"><pre style="line-height: 125%"><span style="color: #f92672"><html></span> 299 <span style="color: #f92672"><body></span> This HTML <span style="color: #f92672"></body></span> 300 <span style="color: #f92672"></html></span> 301 </pre></div> 302 {{< /code >}} 303 304 ### Nested Shortcode: Image Gallery 305 306 Hugo's [`.Parent` shortcode variable][parent] returns a boolean value depending on whether the shortcode in question is called within the context of a *parent* shortcode. This provides an inheritance model for common shortcode parameters. 307 308 The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` parameter: 309 310 {{< code file="layouts/shortcodes/gallery.html" >}} 311 <div class="{{ .Get "class" }}"> 312 {{ .Inner }} 313 </div> 314 {{< /code >}} 315 316 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`: 317 318 {{< code file="layouts/shortcodes/img.html" >}} 319 {{- $src := .Get "src" -}} 320 {{- with .Parent -}} 321 <img src="{{$src}}" class="{{ .Get "class" }}-image"> 322 {{- else -}} 323 <img src="{{$src}}"> 324 {{- end -}} 325 {{< /code >}} 326 327 You can then call your shortcode in your content as follows: 328 329 ``` 330 {{</* gallery class="content-gallery" */>}} 331 {{</* img src="/images/one.jpg" */>}} 332 {{</* img src="/images/two.jpg" */>}} 333 {{</* /gallery */>}} 334 {{</* img src="/images/three.jpg" */>}} 335 ``` 336 337 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`: 338 339 ``` 340 <div class="content-gallery"> 341 <img src="/images/one.jpg" class="content-gallery-image"> 342 <img src="/images/two.jpg" class="content-gallery-image"> 343 </div> 344 <img src="/images/three.jpg"> 345 ``` 346 347 348 ## Error Handling in Shortcodes 349 350 Use the [errorf](/functions/errorf) template func and [.Position](/variables/shortcodes/) variable to get useful error messages in shortcodes: 351 352 ```bash 353 {{ with .Get "name" }} 354 {{ else }} 355 {{ errorf "missing value for param 'name': %s" .Position }} 356 {{ end }} 357 ``` 358 359 When the above fails, you will see an `ERROR` log similar to the below: 360 361 ```bash 362 ERROR 2018/11/07 10:05:55 missing value for param name: "/Users/bep/dev/go/gohugoio/hugo/docs/content/en/variables/shortcodes.md:32:1" 363 ``` 364 365 ## More Shortcode Examples 366 367 More shortcode examples can be found in the [shortcodes directory for spf13.com][spfscs] and the [shortcodes directory for the Hugo docs][docsshortcodes]. 368 369 370 ## Inline Shortcodes 371 372 {{< new-in "0.52" >}} 373 374 Since Hugo 0.52, you can 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. 375 376 This feature is disabled by default, but can be enabled in your site config: 377 378 {{< code-toggle file="config">}} 379 enableInlineShortcodes = true 380 {{< /code-toggle >}} 381 382 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. 383 384 And once enabled, you can do this in your content files: 385 386 ```go-text-template 387 {{</* time.inline */>}}{{ now }}{{</* /time.inline */>}} 388 ``` 389 390 The above will print the current date and time. 391 392 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. 393 394 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". 395 396 The same inline shortcode can be reused later in the same content file, with different params if needed, using the self-closing syntax: 397 398 ```go-text-template 399 {{</* time.inline /*/>}} 400 ``` 401 402 403 [basic content files]: /content-management/formats/ "See how Hugo leverages markdown--and other supported formats--to create content for your website." 404 [built-in shortcode]: /content-management/shortcodes/ 405 [config]: /getting-started/configuration/ "Learn more about Hugo's built-in configuration variables as well as how to us your site's configuration file to include global key-values that can be used throughout your rendered website." 406 [Content Management: Shortcodes]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes "Check this section if you are not familiar with the definition of what a shortcode is or if you are unfamiliar with how to use Hugo's built-in shortcodes in your content files." 407 [source organization]: /getting-started/directory-structure/#directory-structure-explained "Learn how Hugo scaffolds new sites and what it expects to find in each of your directories." 408 [docsshortcodes]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes "See the shortcode source directory for the documentation site you're currently reading." 409 [figure]: /content-management/shortcodes/#figure 410 [hugosc]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes 411 [lookup order]: /templates/lookup-order/ "See the order in which Hugo traverses your template files to decide where and how to render your content at build time" 412 [pagevars]: /variables/page/ "See which variables you can leverage in your templating for page vs list templates." 413 [parent]: /variables/shortcodes/ 414 [shortcodesvars]: /variables/shortcodes/ "Certain variables are specific to shortcodes, although most .Page variables can be accessed within your shortcode template." 415 [spfscs]: https://github.com/spf13/spf13.com/tree/master/layouts/shortcodes "See more examples of shortcodes by visiting the shortcode directory of the source for spf13.com, the blog of Hugo's creator, Steve Francia." 416 [templates]: /templates/ "The templates section of the Hugo docs." 417 [vimeoexample]: #single-flexible-example-vimeo 418 [youtubeshortcode]: /content-management/shortcodes/#youtube "See how to use Hugo's built-in YouTube shortcode."