Shortcodes

Shortcodes in Eleventy

Shortcodes have some similarities to filters, but can provide some extra flexibility. Filters allow piping a variable into a function, which then returns a modified form of that variable. Shortcodes are called with multiple parameters in a very function-like manner. The idea then being that the variables are used to assemble content to be returned. A type of automated layout. There are also Paired Shortcodes which include end tags. Between the beginning and end tags there can be content which the shortcode can also process. That content can contain variables and shortcodes.

Shortcode

Edit src/index.njk to add some new front matter and a tag for a shortcode called shorttest. As can be seen, there is no pipe, and there are two variables being supplied (set in the front matter) :

---
title: Birds
subtitle: Eleventy subtitle
greeting: Welcome

birds:
  - robin
  - finch
  - sparrow
---
{% include "_head.njk" %}
    <h1>{{ title }}</h1>
    <h2>{% shorttest subtitle, greeting %}</h2>
    <ul>
        {% for bird in birds -%}
        <li>{{ bird }}</li>
        {% endfor -%}
    </ul>
{% include "_foot.njk %}
			

Edit .eleventy.js by adding the shortcode shorttest after the filter decorate. Note the function accepts two parameters :

eleventyConfig.addShortcode("shorttest", function(subtitle, greeting){
    return "<h2><em>"+subtitle+"></em>, "+greeting+"></h2>
});
			

This should result in a new <H2>, containing the two values, under the <H1> in dist/index.html :

<h1>Eleventy Title from Data</h1>
<h2><em>Eleventy subtitle</em>, Welcome</h2>
			

Paired Shortcode

Edit src/index.njk again to add a tag for a paired shortcode called pairedtest. Note both the {% pairedtest %} and the {% endpairedtest %} tags, and note there is text between them :

---
title: Eleventy Title from Data
subtitle: Eleventy subtitle
greeting: Welcome

flowers:
  - robin
  - finch
  - sparrow
---
{% include "_head.njk" %}
    <h1>{{ title }}</h1>
    {% shorttest subtitle, greeting %}
    {% pairedtest subtitle, greeting %}Paired Shortcode Content{% endpairedtest %}
    <ul>
        {% for flower in flowers -%}
        <li>{{ flower }}</li>
        {% endfor -%}
    </ul>
{% include "_foot.njk" %}
			

Edit .eleventy.js again by adding the paired shortcode pairedtest after the shortcode shorttest. Note the function accepts three parameters. The first one is the content inside the paired shortcode tags.

eleventyConfig.addPairedShortcode("pairedtest", function(data, subtitle, greeting) {
    return "<h3>"+subtitle+"</h3><h4>"+greeting+"</h4>"+"<p><em>"+data+"</em></p>";
});
			

This should result in a new line starting with the fully assembled content, in dist/index.html :

<h1>Eleventy Title from Data</h1>
<h2>Eleventy subtitle, Welcome</h2>
<h3>Eleventy subtitle</h3><h4>Welcome</h4><p><em>Paired Shortcode Content<em></p>