Nunjucks shortcode inside an include doesn't seems to be rendered
TixieSalander opened this issue · comments
Hi,
I may missing something but putting a Eleventy Img shortcode inside of an include make it stop working and not render the entire include.
I've first setup a shortcode inside Eleventy config file following the documentation:
const EleventyImg = require("@11ty/eleventy-img");
async function postImageShortcode(src, alt) {
if(alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` on responsiveimage from: ${src}`);
}
let metadata = await EleventyImg(src, {
widths: [184,308,616],
formats: ['avif', 'webp', 'jpeg'],
outputDir: './_site/img/'
});
let lowsrc = metadata.jpeg[0];
let highsrc = metadata.jpeg[metadata.jpeg.length - 1];
return `<picture>
${Object.values(metadata).map(imageFormat => {
return ` <source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => entry.srcset).join(", ")}">`;
}).join("\n")}
<img
style="max-width: 100%; height: auto;"
src="${lowsrc.url}"
width="${highsrc.width}"
height="${highsrc.height}"
alt="${alt}"
loading="lazy"
decoding="async">
</picture>`;
}
module.exports = function(eleventyConfig) {
eleventyConfig.addNunjucksAsyncShortcode("postImage", postImageShortcode);
eleventyConfig.addCollection("posts", function (collectionApi) {
return collectionApi.getFilteredByGlob("posts/*.md");
});
return
};
And then use it that way inside of nunjucks files:
{% postImage "img/my-image.jpg", post.data.title %}
Directly in the file it works probperly:
{%- for post in collections.posts %}
{% postImage "img/martin-bennie-5Eobs8jiW-c-unsplash.jpg", post.data.title %}
{%- endfor %}
but if I move it in an included file (in _include/my-include-file.njk
), then nothing from the include file is rendered, like it wasnt called:
{%- for post in collections.posts %}
{% include 'my-include-file.njk' %}
{%- endfor %}
I made a demo repo https://github.com/TixieBorg/demo-11ty-img-include and deployed it on Netlify to get a real life example:
https://deft-biscuit-0a72a8.netlify.app
I don't quite understand why it fails that way and since it doesn't return any error I don't know where to look at. So thank you so much in advance if you have an idea 🙏
I think Nunjucks' {% for %}
tag doesn't always like async code (which your shortcode is).
Ref: https://mozilla.github.io/nunjucks/templating.html#asynceach
Maybe something like this, using {% asyncEach post in collections.posts %}…{% endeach %}
:
{# Inside include #}
<td>
<ul>
{%- asyncEach post in collections.posts %}
<li>
{% include 'post-card.njk' %}
</li>
{%- endeach %}
</ul>
</td>
(also see 11ty/eleventy#2088 which has some details+examples and links to other related issues.)
That was that, thank you problem solved!