github.com/lyeb/hugo@v0.47.1/docs/content/en/templates/shortcode-templates.md (about)

     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 Placement
    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  ### Shortcode Template Lookup Order
    38  
    39  Shortcode templates have a simple [lookup order][]:
    40  
    41  1. `/layouts/shortcodes/<SHORTCODE>.html`
    42  2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html`
    43  
    44  ### Positional vs Named Parameters
    45  
    46  You can create shortcodes using the following types of parameters:
    47  
    48  * Positional parameters
    49  * Named parameters
    50  * Positional *or* named parameters (i.e, "flexible")
    51  
    52  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.
    53  
    54  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.
    55  
    56  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.
    57  
    58  ### Access Parameters
    59  
    60  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.
    61  
    62  To access a parameter by name, use the `.Get` method followed by the named parameter as a quoted string:
    63  
    64  ```
    65  {{ .Get "class" }}
    66  ```
    67  
    68  To access a parameter by position, use the `.Get` followed by a numeric position, keeping in mind that positional parameters are zero-indexed:
    69  
    70  ```
    71  {{ .Get 0 }}
    72  ```
    73  
    74  `with` is great when the output depends on a parameter being set:
    75  
    76  ```
    77  {{ with .Get "class"}} class="{{.}}"{{ end }}
    78  ```
    79  
    80  `.Get` can also be used to check if a parameter has been provided. This is
    81  most helpful when the condition depends on either of the values, or both:
    82  
    83  ```
    84  {{ or .Get "title" | .Get "alt" | if }} alt="{{ with .Get "alt"}}{{.}}{{else}}{{.Get "title"}}{{end}}"{{ end }}
    85  ```
    86  
    87  #### `.Inner`
    88  
    89  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.
    90  
    91  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:
    92  
    93  ```
    94  {{</* innershortcode /*/>}}
    95  ```
    96  
    97  #### `.Params`
    98  
    99  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:
   100  
   101  `$.Params`
   102  : these are the parameters passed directly into the shortcode declaration (e.g., a YouTube video ID)
   103  
   104  `$.Page.Params`
   105  : 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`).
   106  
   107  `$.Page.Site.Params`
   108  : refers to global variables as defined in your [site's configuration file][config].
   109  
   110  #### `.IsNamedParams`
   111  
   112  The `.IsNamedParams` variable checks whether the shortcode declaration uses named parameters and returns a boolean value.
   113  
   114  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:
   115  
   116  ```
   117  {{</* image src="images/my-image.jpg"*/>}}
   118  ```
   119  
   120  You could then include the following as part of your shortcode templating:
   121  
   122  ```
   123  {{ if .IsNamedParams }}
   124  <img src="{{.Get "src" }}" alt="">
   125  {{ else }}
   126  <img src="{{.Get 0}}" alt="">
   127  {{ end }}
   128  ```
   129  
   130  See the [example Vimeo shortcode][vimeoexample] below for `.IsNamedParams` in action.
   131  
   132  {{% warning %}}
   133  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.
   134  {{% /warning %}}
   135  
   136  You can also use the variable `.Page` to access all the normal [page variables][pagevars].
   137  
   138  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.
   139  
   140  ### Checking for Existence
   141  
   142  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.
   143  
   144  ## Custom Shortcode Examples
   145  
   146  The following are examples of the different types of shortcodes you can create via shortcode template files in `/layouts/shortcodes`.
   147  
   148  ### Single-word Example: `year`
   149  
   150  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:
   151  
   152  ```
   153  {{</* year */>}}
   154  ```
   155  
   156  {{< code file="/layouts/shortcodes/year.html" >}}
   157  {{ now.Format "2006" }}
   158  {{< /code >}}
   159  
   160  ### Single Positional Example: `youtube`
   161  
   162  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]:
   163  
   164  ```
   165  {{</* youtube 09jf3ow9jfw */>}}
   166  ```
   167  
   168  Would load the template at `/layouts/shortcodes/youtube.html`:
   169  
   170  {{< code file="/layouts/shortcodes/youtube.html" >}}
   171  <div class="embed video-player">
   172  <iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/{{ index .Params 0 }}" allowfullscreen frameborder="0">
   173  </iframe>
   174  </div>
   175  {{< /code >}}
   176  
   177  {{< code file="youtube-embed.html" copy="false" >}}
   178  <div class="embed video-player">
   179      <iframe class="youtube-player" type="text/html"
   180          width="640" height="385"
   181          src="http://www.youtube.com/embed/09jf3ow9jfw"
   182          allowfullscreen frameborder="0">
   183      </iframe>
   184  </div>
   185  {{< /code >}}
   186  
   187  ### Single Named Example: `image`
   188  
   189  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:
   190  
   191  {{< code file="content-image.md" >}}
   192  {{</* img src="/media/spf13.jpg" title="Steve Francia" */>}}
   193  {{< /code >}}
   194  
   195  You have created the shortcode at `/layouts/shortcodes/img.html`, which loads the following shortcode template:
   196  
   197  {{< code file="/layouts/shortcodes/img.html" >}}
   198  <!-- image -->
   199  <figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
   200      {{ with .Get "link"}}<a href="{{.}}">{{ end }}
   201          <img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt"}}{{.}}{{else}}{{ .Get "caption" }}{{ end }}"{{ end }} />
   202      {{ if .Get "link"}}</a>{{ end }}
   203      {{ if or (or (.Get "title") (.Get "caption")) (.Get "attr")}}
   204      <figcaption>{{ if isset .Params "title" }}
   205          <h4>{{ .Get "title" }}</h4>{{ end }}
   206          {{ if or (.Get "caption") (.Get "attr")}}<p>
   207          {{ .Get "caption" }}
   208          {{ with .Get "attrlink"}}<a href="{{.}}"> {{ end }}
   209              {{ .Get "attr" }}
   210          {{ if .Get "attrlink"}}</a> {{ end }}
   211          </p> {{ end }}
   212      </figcaption>
   213      {{ end }}
   214  </figure>
   215  <!-- image -->
   216  {{< /code >}}
   217  
   218  Would be rendered as:
   219  
   220  {{< code file="img-output.html" copy="false" >}}
   221  <figure>
   222      <img src="/media/spf13.jpg"  />
   223      <figcaption>
   224          <h4>Steve Francia</h4>
   225      </figcaption>
   226  </figure>
   227  {{< /code >}}
   228  
   229  ### Single Flexible Example: `vimeo`
   230  
   231  ```
   232  {{</* vimeo 49718712 */>}}
   233  {{</* vimeo id="49718712" class="flex-video" */>}}
   234  ```
   235  
   236  Would load the template found at `/layouts/shortcodes/vimeo.html`:
   237  
   238  {{< code file="/layouts/shortcodes/vimeo.html" >}}
   239  {{ if .IsNamedParams }}
   240    <div class="{{ if .Get "class" }}{{ .Get "class" }}{{ else }}vimeo-container{{ end }}">
   241      <iframe src="//player.vimeo.com/video/{{ .Get "id" }}" allowfullscreen></iframe>
   242    </div>
   243  {{ else }}
   244    <div class="{{ if len .Params | eq 2 }}{{ .Get 1 }}{{ else }}vimeo-container{{ end }}">
   245      <iframe src="//player.vimeo.com/video/{{ .Get 0 }}" allowfullscreen></iframe>
   246    </div>
   247  {{ end }}
   248  {{< /code >}}
   249  
   250  Would be rendered as:
   251  
   252  {{< code file="vimeo-iframes.html" copy="false" >}}
   253  <div class="vimeo-container">
   254    <iframe src="//player.vimeo.com/video/49718712" allowfullscreen></iframe>
   255  </div>
   256  <div class="flex-video">
   257    <iframe src="//player.vimeo.com/video/49718712" allowfullscreen></iframe>
   258  </div>
   259  {{< /code >}}
   260  
   261  ### Paired Example: `highlight`
   262  
   263  The following is taken from `highlight`, which is a [built-in shortcode][] that ships with Hugo.
   264  
   265  {{< code file="highlight-example.md" >}}
   266  {{</* highlight html */>}}
   267    <html>
   268      <body> This HTML </body>
   269    </html>
   270  {{</* /highlight */>}}
   271  {{< /code >}}
   272  
   273  The template for the `highlight` shortcode uses the following code, which is already included in Hugo:
   274  
   275  ```
   276  {{ .Get 0 | highlight .Inner  }}
   277  ```
   278  
   279  The rendered output of the HTML example code block will be as follows:
   280  
   281  {{< code file="syntax-highlighted.html" copy="false" >}}
   282  <div class="highlight" style="background: #272822"><pre style="line-height: 125%"><span style="color: #f92672">&lt;html&gt;</span>
   283      <span style="color: #f92672">&lt;body&gt;</span> This HTML <span style="color: #f92672">&lt;/body&gt;</span>
   284  <span style="color: #f92672">&lt;/html&gt;</span>
   285  </pre></div>
   286  {{< /code >}}
   287  
   288  {{% note %}}
   289  The preceding shortcode makes use of a Hugo-specific template function called `highlight`, which uses [Pygments](http://pygments.org) to add syntax highlighting to the example HTML code block. See the [developer tools page on syntax highlighting](/tools/syntax-highlighting/) for more information.
   290  {{% /note %}}
   291  
   292  ### Nested Shortcode: Image Gallery
   293  
   294  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.
   295  
   296  The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` parameter:
   297  
   298  {{< code file="layouts/shortcodes/gallery.html" >}}
   299  <div class="{{.Get "class"}}">
   300    {{.Inner}}
   301  </div>
   302  {{< /code >}}
   303  
   304  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`:
   305  
   306  {{< code file="layouts/shortcodes/img.html" >}}
   307  {{- $src := .Get "src" -}}
   308  {{- with .Parent -}}
   309    <img src="{{$src}}" class="{{.Get "class"}}-image">
   310  {{- else -}}
   311    <img src="{{$src}}">
   312  {{- end }}
   313  {{< /code >}}
   314  
   315  You can then call your shortcode in your content as follows:
   316  
   317  ```
   318  {{</* gallery class="content-gallery" */>}}
   319    {{</* img src="/images/one.jpg" */>}}
   320    {{</* img src="/images/two.jpg" */>}}
   321  {{</* /gallery */>}}
   322  {{</* img src="/images/three.jpg" */>}}
   323  ```
   324  
   325  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`:
   326  
   327  ```
   328  <div class="content-gallery">
   329      <img src="/images/one.jpg" class="content-gallery-image">
   330      <img src="/images/two.jpg" class="content-gallery-image">
   331  </div>
   332  <img src="/images/three.jpg">
   333  ```
   334  
   335  ## More Shortcode Examples
   336  
   337  More shortcode examples can be found in the [shortcodes directory for spf13.com][spfscs] and the [shortcodes directory for the Hugo docs][docsshortcodes].
   338  
   339  [basic content files]: /content-management/formats/ "See how Hugo leverages markdown--and other supported formats--to create content for your website."
   340  [built-in shortcode]: /content-management/shortcodes/
   341  [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."
   342  [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."
   343  [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."
   344  [docsshortcodes]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes "See the shortcode source directory for the documentation site you're currently reading."
   345  [figure]: /content-management/shortcodes/#figure
   346  [hugosc]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes
   347  [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"
   348  [pagevars]: /variables/page/ "See which variables you can leverage in your templating for page vs list templates."
   349  [parent]: /variables/shortcodes/
   350  [shortcodesvars]: /variables/shortcodes/ "Certain variables are specific to shortcodes, although most .Page variables can be accessed within your shortcode template."
   351  [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."
   352  [templates]: /templates/ "The templates section of the Hugo docs."
   353  [vimeoexample]: #single-flexible-example-vimeo
   354  [youtubeshortcode]: /content-management/shortcodes/#youtube "See how to use Hugo's built-in YouTube shortcode."