hugo/content/en/templates/shortcode-templates.md
Bjørn Erik Pedersen eb16165694 Squashed 'docs/' changes from 37095d540..d1cf9adc4
d1cf9adc4 Fix typo
26e10a690 Fix the name and arg mismatch between partial defn and call
2db0e53cd Merge commit '9c36cff15224f6cbd19058ad61311229b7a23c83'
9c36cff15 Squashed 'themes/gohugoioTheme/' changes from 68ddff44..b8202f53
4b021eff8 Update lang.Merge.md
b37af2916 Add title to yaml
a9a281233 Fixed incorrect usage of the code-toggle shortcode
4560a0169 Update Warning for Theme Links (#676)
0305e3c6b Document .File.ContentBaseName
6d30c5aa1 Update configuration.md
158df174a Document .Sites and .Sites.First
0c0f583b8 Add stale config
e2531afd8 Document path template functions
4dd779057 Clarify that partialCached is per site/language
19e5bbe0c Update index.md
44b000857 Add missing dot
a41300cf9 Release 0.52
2d1d92b88 Merge branch 'temp52'
c5925250d releaser: Prepare repository for 0.53-DEV
d000b04a2 releaser: Add release notes to /docs for release of 0.52
4bb983a0a releaser: Bump versions for release of 0.52
36736ca28 tpl: Add "param" shortcode
378677aa6 Add Elasticsearch/bonsai.io to services doc.
4c3fd4fa4 docs: Document inline shortcodes
6c64c374c Whitelist CSS modules from purge
817a872b9 Improve search icon position
cf86ff1c7 Add minification and resource cache clear to build command
fd77e8df3 Update asset dependencies and adopt Hugo Pipes
cdbe97e8c Update render.md
b0e279220 git command to update submodule to latest
a1cb98c12 cache/filecache: Add a :project placeholder
07c1b2b46 cache/filecache: Use time.Duration for maxAge
ffa9b165e Add AND as a title
6e7733b40 Add OR as a sub title to make it easier to find in search
72b6791a1 docs: Document the new file cache
714d3ca91 Fix minification issues
cd1e961da Revert "Add Elasticsearch/bonsai.io to services doc."
15a0cda6e Add Elasticsearch/bonsai.io to services doc.
f931d86de Release 0.51
e2ffe867a Merge branch 'temp51'
423e7f5c8 releaser: Prepare repository for 0.52-DEV
c6f2d6ae1 releaser: Add release notes to /docs for release of 0.51
5bbb556dc releaser: Bump versions for release of 0.51
3b2b172b9 docs: Document shortcode error handling
b8672f3d4 docs: Document symdiff
4bc6071e6 docs: Document complement
d1baab752 docs: Re-generate CLI docs
9ea667e24 Revert "tpl: Update Jsonify to return pretty-print output"
ce5a1403d docs: Regenerate the docs helper
99a1f4a94 Fix note for reserved partial name(starting with -> including).
eba3cbc42 fix accidentally modification on paragraph.
3eebd98c3 Add note for reserved partial name.
40b881cc2 Document templates.Exists
b5c3bcd3b Update multilingual.md
61c59c67e Fix misspelling (#648)
f21d8c4a4 Correct minor typo (#5372)
e967001b9 Release 0.50
685fd6b08 releaser: Prepare repository for 0.51-DEV
f245a9faa releaser: Add release notes to /docs for release of 0.50
4354da30d releaser: Bump versions for release of 0.50
feaa05469 docs: Regenerate CLI docs
5c724200c Merge commit 'd6a4af7018e8618944a6471ceeb7aae1d4df6afa'
2ddab36c2 Merge commit '74309fe5699a595080fdb3a14711e0869babce99'
8cf296a7c docs: Regenerate CLI docs
9097683dd tpl: Update Jsonify to return pretty-print output

git-subtree-dir: docs
git-subtree-split: d1cf9adc412245c96d9d32592a903370d3972aef
2018-12-12 09:05:31 +01:00

17 KiB

title linktitle description date publishdate lastmod categories keywords menu weight sections_weight draft aliases toc
Create Your Own Shortcodes Shortcode Templates You can extend Hugo's built-in shortcodes by creating your own using the same templating syntax as that for single and list pages. 2017-02-01 2017-02-01 2017-02-01
templates
shortcodes
templates
docs
parent weight
templates 100
100 100 false
true

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 and basic content files.

{{% note %}} Hugo also ships with built-in shortcodes for common use cases. (See 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 {{</* myshortcode /*/>}} or {{%/* myshortcode /*/%}} depending on the type of parameters you choose.

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:

{{/*< boxes/square >*/}}

Note the forward slash.

Shortcode Template Lookup Order

Shortcode templates have a simple lookup order:

  1. /layouts/shortcodes/<SHORTCODE>.html
  2. /themes/<THEME>/layouts/shortcodes/<SHORTCODE>.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:

{{ .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:

{{ .Get 0 }}

For the second position, you would just use:

{{ .Get 1 }}

with is great when the output depends on a parameter being set:

{{ 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:

{{ or .Get "title" | .Get "alt" | if }} alt="{{ with .Get "alt"}}{{.}}{{else}}{{.Get "title"}}{{end}}"{{ end }}

.Inner

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.

A shortcode with content declared via the .Inner variable can also be declared without the inline content and without the closing shortcode by using the self-closing syntax:

{{</* innershortcode /*/>}}

.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 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).
$.Page.Site.Params
refers to global variables as defined in your site's configuration file.

.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:

{{</* image src="images/my-image.jpg"*/>}}

You could then include the following as part of your shortcode templating:

{{ if .IsNamedParams }}
<img src="{{.Get "src" }}" alt="">
{{ else }}
<img src="{{.Get 0}}" alt="">
{{ end }}

See the example Vimeo shortcode below for .IsNamedParams in action.

{{% warning %}} 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. {{% /warning %}}

You can also use the variable .Page to access all the normal page variables.

A shortcodes can also be nested. In a nested shortcode, you can access the parent shortcode context with .Parent variable. 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:

{{</* year */>}}

{{< 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:

{{</* youtube 09jf3ow9jfw */>}}

Would load the template at /layouts/shortcodes/youtube.html:

{{< code file="/layouts/shortcodes/youtube.html" >}}

{{< /code >}}

{{< code file="youtube-embed.html" copy="false" >}}

{{< /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. Your goal is to be able to call the shortcode as follows in your content files:

{{< code file="content-image.md" >}} {{</* img src="/media/spf13.jpg" title="Steve Francia" */>}} {{< /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" copy="false" >}}

Steve Francia

{{< /code >}}

Single Flexible Example: vimeo

{{</* vimeo 49718712 */>}}
{{</* vimeo id="49718712" class="flex-video" */>}}

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" copy="false" >}}

{{< /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" >}} {{</* highlight html */>}}

<html> This HTML </html> {{}} {{< /code >}}

The template for the highlight shortcode uses the following code, which is already included in Hugo:

{{ .Get 0 | highlight .Inner  }}

The rendered output of the HTML example code block will be as follows:

{{< code file="syntax-highlighted.html" copy="false" >}}

<html>
    <body> This HTML </body>
</html>
{{< /code >}}

{{% note %}} The preceding shortcode makes use of a Hugo-specific template function called highlight, which uses Pygments to add syntax highlighting to the example HTML code block. See the developer tools page on syntax highlighting for more information. {{% /note %}}

Hugo's .Parent shortcode variable 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.

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 -}} <img src="{{$src}}" class="{{.Get "class"}}-image"> {{- else -}} {{- end }} {{< /code >}}

You can then call your shortcode in your content as follows:

{{</* gallery class="content-gallery" */>}}
  {{</* img src="/images/one.jpg" */>}}
  {{</* img src="/images/two.jpg" */>}}
{{</* /gallery */>}}
{{</* img src="/images/three.jpg" */>}}

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:

<div class="content-gallery">
    <img src="/images/one.jpg" class="content-gallery-image">
    <img src="/images/two.jpg" class="content-gallery-image">
</div>
<img src="/images/three.jpg">

Error Handling in Shortcodes

Use the errorf template func and .Position variable to get useful error messages in shortcodes:

{{ with .Get "name" }}
{{ else }}
{{ errorf "missing value for param 'name': %s" .Position }}
{{ end }}

When the above fails, you will see an ERROR log similar to the below:

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"

More Shortcode Examples

More shortcode examples can be found in the shortcodes directory for spf13.com and the shortcodes directory for the Hugo docs.

Inline Shortcodes

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.

This feature is disabled by default, but can be enabled in your site config:

{{< code-toggle file="config">}} 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 to be executed from the content files.

And once enabled, you can do this in your content files:

{{</* time.inline */>}}{{ now }}{{</* /time.inline */>}}

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 params if needed, using the self-closing syntax:

{{</* time.inline /*/>}}