32cb8785e Fix page weights in content management section (#1896) 11977b96f Make relURL and related functions consistent (#1895) f12180207 Clarify github deployment (#1894) 958877789 Remove remaining references to Highlight.js (#1893) fc487d263 Minor edit to taxonomy page 3b6a224b2 Update theme b28553b62 Change "flavor" to "edition" when referring to builds (#1892) 660e7581c Replaced sudo in OpenBSD with doas (#1891) e3fcdea10 fix a few minor grammatical issues on Firebase docs (#1889) e4c8b30eb update Static Web Apps docs (#1890) da2197c9e Update hosting-on-firebase.md (#1347) 5f2a0c271 Adding deployment guide for Azure Static Web Apps (#1456) 5aaf570cd add Azure Static Web App config to 404 template 35fc54362 add Azure Static Web App config to 404 template d48f67ba1 Update 01-flavors.md 11debae8d Cleaned Use of ref and relref section, added refs of index.md and _in… (#1744) b77604078 docs: Add link to menu entry variables (#1827) 0fa8a6bf0 Misc copy edits (#1887) c27b545ac Improve explanation of safeHTMLAttr's function (#1503) b04a4b32e Make CLI command summaries meaningful (#1886) dbf00a81f Fix a typo in diagrams documentation (#1885) 11f884327 docs: Clarify how to remove draft/future/expired content (#1831) 6dc9e9860 Improve complement function (#1884) 56448a51a Remove erroneous sourcemap desc (#1883) a0d0d2829 Merge branch 'divinerites-patch-1' 10f20cb5e Add a plausible-hugo theme component 9f1413eb5 Minor edits to showcase example 7d78420db fix broken link to Isso Comments 925cb291f Make directory tree consistent with other examples 300fff092 Add link to security policy from getenv.md (#1746) 7b4c517a6 Fix docs menu weights ce35775e0 Update faq.md (#1763) f3fb791a4 Remove dated new-in flags (#1879) b6c634629 Remove deprecated templating langs (#1880) 1b25ca34f Update the findRE and replaceRE functions (#1881) 28757ec73 Add Alora Labs website to showcase (#1494) e3c4bc4e7 Remove unimplemented "ugly" property 86afd84ff Update editors.md (#1878) 44c093911 Add urlquery function docs (#1633) 16a8c3548 Update links to installation page (#1876) 9e357f078 Add missing sections to BSD installation page (#1875) 1b1291634 Promote "Installation" to a section 9dd51235b Add detail to description of .Plain page variable (#1870) d333d0287 Minor markdown linting fix and URL updates (#1873) d57c8aa50 Remove extraneous apostrophe (#1871) 8c25cfc5c Update index.md 09fea41e0 Add lang to fenced code block 35b904798 Add small documentation about .Site.Social.twitter variable (#1854) 672042f89 Consolidate site configuration dfd4dd873 Add help.ampio.com showcase. (#1863) e8d0e7bdf Include link to internal templates code (#1794) 7db6f0c01 Add example to split function (#1867) be87dba80 Clarify split function docs (#1792) a079193f1 Fix typo on data templates page b234c70ee Fix data templates page (#1855) 074232b45 Update front-matter.md (#1856) 711c8fa80 Added missing default value (#1862) 034762882 Fixed some grammar issues and typos (#1865) 764574a4d Fix spelling error 2698f2d44 update URLs to prevent redirects (#1864) 68f05fdc8 Fenced code blocks should have a language specified (#1861) 24393315b GitHub Workflows security hardening (#1859) 3eeee13bf Markdown formatting: Add Fenced code block languages (#1858) e152cdf1f netlify: Hugo 0.105.0 4c7fc9f7e Merge branch 'tempv0.105.0' d16710afc Change anchor reference to use relref function calls (#1853) f52af8e4a tpl/encoding: Add noHTMLEscape option to jsonify eca0046c4 Update hosting-on-keycdn docs (#1852) ffbe17a48 Add note for rsync deploy command (#1415) c482133f1 docs: Update quick start to clarify the need of extended version (#1828) 1e3b33804 use correct URL for Google Search console verification (#1851) dac034f63 Markdown and formatting fixes (#1850) 43f177e3c Fix LiveReload in quick-start (#1739) f78deaa5f Add link for ''Hugo Shortcode Syntax Highlighting' VS Code extension (#1765) 08087ecd7 Remove some hidden pages (#1848) b6cb5ae48 Markdown linting fixes (#1846) 527ec5941 Update hugo.md (#1742) 83e8f2168 Clarify that a shortcode with .Inner must be closed (#1785) 4193f4445 Add Super Linter GitHub Action (#1845) fd91bfe1a Formatting and grammar fixes (#1844) ab5a49c49 Create codeql-analysis GitHub Action (#1812) 63b3e082e Add tutorial on using fusejs to search examples (#1756) 54c253ab0 Note that Google Universal Analytics are deprecated (#1770) 385fa77c6 Update articles.toml (#1840) 5e336bd26 Replace awkward wording (ESL?) (#1842) 2446ad349 Added Introduction to Hugo tutorial/video series (#1736) 7b21b2e76 Don't use self-closing generator tag ef73712ff Image processing. available methods: add method 'Colors' (#1837) 018f83bbe [comment platform] - add new alternative (#1751) 5636c208b Grammar and spelling fixes (#1836) 3f2e26f77 Change link of repojacking vulnerable link - JekyllToHugo (#1834) 301379fc3 fix: use shorter image URL to make it easier to read (#1835) de5fa7b30 Update search.md to include Pagefind (#1826) e9d72bcda Breadcrumb example: add basic accessibility (#1832) 6cffff87a netlify: Hugo 0.104.3 892360f61 Update output-formats.md 09a7a46ae Remove my defunct and little used migrator (#1824) 347434cca netlify: Hugo 0.104.2 f8c721162 Update postcss.md c2baf7155 netlify: Hugo 0.104.1 05d1192cd Update diagrams.md (#1823) 3c43a8bbe netlify: Hugo 0.104.0 57973b334 Merge branch 'tempv0.104.0' da775a36d docs: Regen docs helper ae48b5901 docs: Regenerate CLI docs af4a823b1 resources/images: Add $image.Colors 8e3f9ca64 Remove outdated IE conditional comments example (#1821) d1a84701b fix typo in template introduction (#1820) c0c7339e0 Update internal.md 17aefc515 Remove the recommendation about where to put the GA tempalte 263297236 Adjust GA template instructions 1cc265d99 Update the GA template usage section e11968338 config/security: Allow proxy variables in subcommands 9218ab993 netlify: Hugo 0.103.1 0b0e890d1 Update markdownify and RenderString documentation (#1818) 50f5d4776 Fix internal link (#1817) 6beb443c5 netlify: Hugo 0.103.0 14b5af248 Merge branch 'tempv0.103.0' 548e7aa62 server: Add 404 support 3a20aa0ba Update theme git-subtree-dir: docs git-subtree-split: 32cb8785ea74d5b82f2e2bea79d059cab497902a
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 |
|
|
|
100 | 100 | false | 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 /*/%}}
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:
/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 by using the self-closing syntax:
{{</* innershortcode /*/>}}
{{% warning %}}
Any shortcode that refers to .Inner
must be closed or self-closed.
{{% /warning %}}
.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 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 /*/>}}