mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 635 forks source link

Template included inside switch case statement not working #1387

Open architchandra opened 2 years ago

architchandra commented 2 years ago

I'm using Nunjucks in Eleventy to build a site.

I've created component templates for various editor blocks to render a blog page, eg. components/heading.njk, components/image.njk, components/text, etc.

I'm trying to add all these to another component called Body (components/body.njk), which in turn includes these components (after passing in some inputs). In the blog template, I plan to just include the body component and pass in the blocks corresponding to the content types added by the user (text, image, heading, etc) rather than including these components directly. (This is based on Forestry's Blocks field's templating requirements.)

However, I'm facing an issue where an included template including another template is not working in conjugation with the switch statement. I'm getting a SyntaxError: Illegal break statement error in Eleventy in the console.

Here are the relevant contents of the templates in case the description wasn't clear.

{# blog.njk #}

{% set bodyParams = {
    blocks: body
} %}
{% include 'components/body.njk' %}
{# components/body.njk #}

{# Parameters #}
{% set bodyBlocksList = bodyParams.blocks if bodyParams.blocks else [] %}
{% set bodyClass = bodyParams.class if bodyParams.class else 'prose mx-auto' %}

{# Output #}
<div class="{{ bodyClass }}">
  {% if bodyBlocksList|length %}
    {% for block in bodyBlocksList %}
      {% set blockType = block.template %}
      {% switch blockType %}
        {% case 'heading' %}
          {% include 'components/heading.njk' %}
        {% case 'image' %}
          {% set imageParams = {
            image: block.image,
            altText: block.altText,
            caption: block.caption
          } %}
          {% include 'components/image.njk' %}
      {% endswitch %}
    {% endfor %}
  {% endif %}
</div>
{# components/image.njk #}

{# Parameters #}
{% set imageAsset = imageParams.image if imageParams.image else '' %}
{% set imageCaption = imageParams.caption if imageParams.caption else '' %}
{% set imageAltText = imageParams.altText if imageParams.altText else '' %}

{# Output #}
<figure>
  <img class="rounded-md" src="{{ imageAsset }}" alt="{{ imageAltText }}" title="{{ imageAltText }}">
  <figcaption class="font-prose">
    {{ imageCaption }}
  </figcaption>
</figure>
architchandra commented 2 years ago

Update: The code works fine if I use {% if %}..{% elif %}..{% endif %} instead of the {% switch %} tag.