nunjuckseleventy

Nunjucks variables inside eleventy-img shortcode


I could find any solution about this problem. Basically I want to be able to get the data from a Nunjucks variables to be correctly rendered inside a shortcode.

{% for foo in bar %}
    {% image "{{foo.src}}", "alt", "sizes", "imgClass" %}
{% endfor %}

but this results in an error

[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] 1. Having trouble rendering njk template ./src/index.html (via TemplateContentRenderError)
[11ty] 2. (./src/index.html)
[11ty]   Template render error: (...test.html)
[11ty]   EleventyShortcodeError: Error with Nunjucks shortcode `image` (via Template render error)
[11ty] 3. ENOENT: no such file or directory, stat '{{foo.src}}.png' (via Template render error)

So it can not get the right variable value in there. But how can I do this?


Solution

  • You can use the variables directly in that case:

    {% set images = [
        {
          src: "src/images/image-file.jpg",
          alt: "image description",
          imgClass: "center fit"
        },
        ...
      ]
    %}
    
    {% for item in images %}
       {% image item.src, item.alt, item.imgClass %}
    {% endfor %}