Search code examples
shortcodeeleventy

11ty one shorcode call another shortcode?


Is it possible for me to write one shortcode, and it would trigger several others? Let's say I have shorcode using njk:

{% card %}

inside, let's say the following code:

  eleventyConfig.addNunjucksShortcode("card", function() {
    return `
    <div class="card">
    </div>
    `
  });

And I have another shortcode:

{% img "path-to-img.jpg" %}.

It has an img src parameter, and will render to some img.

  eleventyConfig.addNunjucksShortcode("img", function(path) {
    return `
    <img src="${path}">
    `
  });

I need that when I call the card shortcode, it called the img shortcode and passed the parameter to it.Let's say that I write:

{% card 'path-to-img.jpg' %}

And it will render at:

<div class="card">
  <img src="path-to-img.jpg">
</div

Just in case, I need to call one shortcode, paired and nested shortcodes will not suit me:

{% column %}
  {% img 'path-to-img.jpg' %}
{% endcolumn %}

Solution

  • I got this way (there is not a img, but the meaning is the same):

      eleventyConfig.addNunjucksShortcode("inner", function() {
        return `<div class="inner">`;
      });
    
      eleventyConfig.addNunjucksShortcode("endinner", function() {
        return `</div>`;
      });
    
      eleventyConfig.addShortcode("card", function(text) {
        return `<div class="card">
                  ${eleventyConfig.nunjucksShortcodes.inner()}
                  ${text}
                  ${eleventyConfig.nunjucksShortcodes.endinner()}
                </div>`;
       });
    

    And call it:

    {% card "text" %}