Evans Evans - 4 months ago 37
Twig Question

Use loop.index as part of template name to include with Twig?

I have an array of 3 items so in the following I'm including sub-component.twig 3 times:

{% for i in array %}
<div class="my-class">
{% include "sub-component.twig" %}
</div>
{% endfor %}


However I actually have 3 slightly different templates and I would like to load a different one for each iteration over the array:

sub-component-1.twig
sub-component-2.twig
sub-component-3.twig


When I print loop.index in the template the result is "1", "2" and "3". Can I therefore use the index to form the template name?

{% for i in array %}
<div class="my-class">
{{ loop.index }}
{% include ["sub-component-" ~ loop.index ~ ".twig"] %}
</div>

Answer

Possibly because I'm using gulp twig I had to break things out into variables for this to work.

https://github.com/zimmen/gulp-twig

{% for i in array %}
  <div class="my-class">

    {% set sub-component_1 = "sub-component-" %}

    {% set sub-component_2 = loop.index %}

    {% set sub-component_3 = ".twig" %}

    {% set sub-component_full = sub-component_1 ~ sub-component_2 ~ sub-component_3 %}

    {% include sub-component_full %}

  </div>
{% endfor %}
Comments