Nunjucks and an Eleventy shortcode aren't connecting to each other

39 Views Asked by At

I've written an Eleventy shortcode to take the filename of an image (as well as text for an alt tag, etc), and output a whole srcset so it becomes a responsive image.

The site's written using Nunjucks, so I need to call the shortcode from inside a Nunjucks partial.

Eleventy is returning an error, "Error: Unable to call responsiveImageTest, which is undefined or falsey".

In trying to diagnose the underlying error, I've ended up with the following simplified version of the code –

previewCard.njk {{ responsiveImageTest() | safe }}

.eleventy.js

  eleventyConfig.addShortcode("responsiveImageTest", function() {
    return `<p>Check</p>`;
  });

Two outcomes: When I include the curved braces in previewCard.njk, Eleventy says it's unable to call responsiveImageTest. When I remove the curved braces, Eleventy compiles just fine, but the shortcode doesn't return anything at all.

1

There are 1 best solutions below

0
Ivana Costa On

You seem to be using the wrong syntax to use a shortcode with eleventy + nunjucks. As per eleventy documentation (https://www.11ty.dev/docs/shortcodes/, in "View this example in:" you can click in "nunjucks" to change the template language of the example) you could try something as follow:

previewCard.njk

{% responsiveImageTest "fileName" %}

.eleventy.js

eleventyConfig.addShortcode("responsiveImageTest", function() {
  ...
});

Also you might want to check eleventy's image plugin that helps with image transformations, including responsive output: https://www.11ty.dev/docs/plugins/image/