Search code examples
for-loopif-statementtwigindentation

Using Twig to generate Markdown, how to indent blocks in twig?


I have very few hours of use with Twig so I probably missed an important tip; please forgive me if this is a trivial question.

I'm using Twig with PHP for the generation of markdown files.

My twig file contains one or more {% for %}...{% endfor %} block and inside a for-loop, a few {% if %}...{% endif %} and ... I can't make any indentation in my Twig otherwise the spaces are also present in my output.

A very stupid example: https://twigfiddle.com/fb6nzq (use the Show raw result to make sure to see the spaces before the word true).

If I don't indent my {% if %}...{% endif %}, I got the correct result (https://twigfiddle.com/fb6nzq/2) but I don't have anymore indentation of blocks in my template.

In my real world twig file, I can have multiple {% endif %} like below and it becomes unreadable.

{% for (variable) %}
{% if (condition) %}
{% if (condition) %}
{% if (condition) %}
{% endif %}
{% endif %}
{% endif %}
{% endfor%}

So ... do you know if there is a wonderful trick to keep an indentation in your code but without having an impact on the output?

Desired twig template:

{% for (variable) %}
   {% if (condition) %}
      {% if (condition) %}
         {% if (condition) %}
         {% endif %}
      {% endif %}
   {% endif %}
{% endfor%}

Solution

  • You can use a dash - on any opening or closing twig expression where:

    • a dash on the closing expression would do a trim on the left.
      {% if true -%}
    • a dash on the opening expression would do a trim on the right
      {%- if true %}
    • a dash on the both the opening and closing expression would do a trim on the both sides
      {%- if true -%}

    Mind that: this is acting as a PHP trim, so that means that it will also trim your line feeds!

    Here is an example:

    {% for i in 1..5 %}
       {% if true %}
          {% if true %}
             {%- if  true %}   
    foo
             {%- endif %}
          {%- endif %}
       {% endif %}
    {% endfor %}
    

    That renders:

    foo
    foo
    foo
    foo
    foo
    

    This is testable here: https://twigfiddle.com/1awhzk

    Also note: that there is a spaceless tag to achieve those kind of things.