39af43ef1 Update postprocess.md 3ec192d08 Update multilingual.md 7fc7bf862 Add a note about some changes in 0.112.0 742510ae8 Fix ordinal abbrev example fe557031a Correct spelling for 'GitHub' and 'GitLab' (#2082) 84a059b9a Fix typo in hosting-on-azure.md (#2080) 3383786fe Add i18n to list of directories affected by ignoreFiles 5bfb95234 Update 404.md (#2076) 87545a4fd Update hosting-on-cloudflare-pages.md (#2078) aa5952c28 Add default module mount to example (#2075) ced5292c8 Align permalinks examples (#2073) 77b5009fd Fix typo c79319a6a Clarify description of baseURL e93a9807b Fix typo in frontmatter description (#2071) 05fe9163a Remove erroneous statement aa59ef383 docs: Remove note about hugo server not using 404 (#2068) 4a387a6b8 Clarify findRESubmatch (#2065) 47a9181b5 Clarify findRE, replaceRE, and findRESubmatch (#2064) e5eedbb5e Update theme 5d392c3d4 Clarify pageRef menu property (#2059) a557b0ebf Fix typos on Configure Hugo page (#2058) 17ef283e6 Clarify module.replacements wording (#2052) 5db4aa421 Fixing broken links (#2057) 9afa0c2fa Fix broken links (#2055) 49b981b1f Correct repo URL for migration tool (contentful.com) (#2056) 969c24c16 Remove duplicate content 0b91e7676 Revert "Delete duplicate content" 3229e79f2 Delete duplicate content ec4eddb98 Fix typo 6509159d5 Describe snap package strict confinement (#2050) 1589bcdb7 Remove hugo.Generator admonition (#2048) 7e553d11b Add example 48bec0335 Replace blockquotes with admonitions where appropriate (#2043) 98226fe61 Remove orphaned param fron admonition calls (#2042) 2a37a1d21 Clarify cast functions (#2041) 03fd1d404 Fix typo 1898013ef Fix typos 944e27430 Replace output shortcode calls 0c66fb055 Add example of shortcode calls within sample code f25a79c69 Replace tip and warning shortcode calls 3afac22fc Refactor code shortcode ad65d2931 Clarify seq function 59f8a1f48 Clarify title function 47535dc87 Cleanup hasPrefix hasSuffix 7bee3e4c1 Cleanup action delimiters cc96070f0 Correct functions archetype ffe5d39b9 Remove duplicate shortcodes 075c9f3fe Remove old todos bc3ec033c Front matter cleanup (#2039) 928b94505 Add code fence types (#2038) 856fa293c Document .File.Filename (#2037) 0988c4a42 Update output-formats.md (#2036) 289da5658 Change findRe to findRE 1e50f0583 Update theme f90fb1bf5 Improve type formatting (#2032) 7785fa7d9 Use code-toggle shortcode where appropriate f11cabf37 Add space after and before action delimiters ac333c795 Replace erroneous use of nocopy shortcode param 064896c06 Use bool param when calling code-toggle fb33bf59b Update code-toggle shortcode 6ddeab4f8 Add missing go-html-template code fence type (#2030) 1bba4cefb Fix links (#2029) 77f4d6c32 Link destination cleanup (#2028) fc0ecc027 Improve breadcrumb example (#2026) 6148be2de Update the breadcrumb navigation example (#2025) 6ebb37b1b Clarify sort function (#2024) 31269bad9 Add Winget installation method (#1988) d6c5f940e Resource methods: add signatures, minor improvements (#2017) d2e594cbc Modify inner variable shortcode-template explanation (#1985) a54927a7f Update GitHub Pages starter workflow (#2023) 2964c2d44 Remove orphaned static files (#2022) 97e5567cc Complete documentation on '.Scratch' and '.Store' (#2016) fa7b2e299 Fix typo bdce77c57 Remove literal from example menu template c0f23b216 Correct and improve menu documentation (#2010) 464368fd9 Document .Page.Store (#2011) a3d7c4a3a Improve urls.Parse function (#2012) d2cec3776 Clarify postcss config option (#2013) eb3003fef Fixed typo (#2007) 90c82d7ea Clarify mermaid markdown example (#2004) 1b11dcd5c docs(Diagrams): Update mermaid import mechanism (#1967) 4aceb6855 Fingerprinting, asset management: minor improvements (#2003) bcbc519bb resources.GetRemote: minor improvement (#2002) d54185bef Clarify markdownify behavior (#1999) afb582a80 Clarify usage of slug in front matter (#1998) f71985315 Update hasSuffix.md 29ad622a3 netlify: Hugo 0.111.3 adf223ecc Merge branch 'tempv0.111.3' 06858c646 docs: Improve examples of variadic math functions 8b656994e tpl/math: Allow multi numbers in add, sub, mul, div, min and max 2a38c4046 tpl: Add hasSuffix alias 4e0b98d54 switch transfers to workers 11651ac0f customize parallel transfer count 142f5da81 Update GitHub hosting instructions (#1991) ad7901d2f netlify: Hugo 0.111.2 0651a76e0 add headings to distinguish render hook context params d96d75be4 netlify: Hugo 0.111.1 226cb9e3a Add a paragraph about the new page template function 4c0157a49 Add .Fragments docs 6c78c0679 netlify: Bump to Hugo 0.111.0 7b11c24cf Merge branch 'feat/related-fragments' 615d18ef8 Add Related fragments config a36449b0c cods: Regen docs helper 0272fa45f Merge commit '336622d5e7afd9334cd2de7150d4f16bdf7c24f9' c5a962b93 related: Add config option cardinalityThreshold f91677377 docs: Another fix related docs example 17aa939ea docs: Fix related docs example 12c449150 Merge commit 'cf591b7c0c598d34896709db6d28598da37e3ff6' cb998b3d6 Add page fragments support to Related git-subtree-dir: docs git-subtree-split: 39af43ef11c23b8eaea7e17b59ff065a169305ac
17 KiB
title | linktitle | description | categories | keywords | menu | weight | 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. |
|
|
|
100 | true |
Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside 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 /*/%}}
.
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:
/layouts/shortcodes/<SHORTCODE>.html
/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:
{{ 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. 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 content and without the closing tag by using the self-closing syntax:
{{</* innershortcode /*/>}}
{{% 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 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.
{{% 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 {{</* image src="images/my-image.jpg" "This is my alt text" */>}}
will return an error.
{{% /note %}}
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 file="youtube-embed.html" copy=false >}}
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" >}}
{{< /code >}}Would be rendered as:
{{< code file="img-output.html" copy=false >}}
{{< /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 }}
Would be rendered as:
{{< code file="vimeo-iframes.html" copy=false >}}
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>
Nested Shortcode: Image Gallery
Hugo's .Parent
shortcode variable 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" >}}
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
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 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 /*/>}}