Twig, add first and last class

Twig, add first and last class

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Twig, add first and last class

When rendering a list of items in a loop, you often need to apply specific CSS classes to the first and last elements to handle layout edge cases. Perhaps you want to remove borders on adjacent items, or perhaps you are building a carousel where the end caps require special styling. A naive approach might involve passing an index variable into your view, but Twig offers a cleaner way to handle this logic directly within the template engine without cluttering your controller.

The core challenge is accessing the current iteration's position and comparing it against the total count of the iterable. In the example you provided, the loop iterates over arrMenu. To distinguish the boundaries, you need two pieces of information: the current index (usually 0-based in PHP) and the total length of the array.

Twig provides the loop variable within a {% for %} tag that exposes exactly this data. The loop.index property gives you the current zero-based index, while loop.length provides the total number of iterations. You can use these to conditionally append classes. Here is how you modify your existing loop:

{% for elem in arrMenu %}
    <div class="topmenu-button">
        {% if loop.first %}
            class="first"
        {% endif %}
        {# You might want to separate base and dynamic classes for cleaner output #}
        {% set dynamicClass = loop.last ? "last" : "" %}
        
        <a href="{{ elem.url }}" class="{{ 'topmenu-button' ~ (loop.first ? ' first' : '') ~ (dynamicClass ? ' ' ~ dynamicClass) }}">
            {{ elem.name }}
        </a>
    </div>
{% endfor %}

While the logic above works, it introduces a slight redundancy by checking loop.last inside a separate line. A more concise pattern involves combining the conditional strings directly within the template expression. You can construct the full class string in one go:

{% for elem in arrMenu %}
    <div class="topmenu-button">
        {% if loop.first %}first{% endif %}
        {% if loop.last %}last{% endif %}
        <a href="{{ elem.url }}">
            {{ elem.name }}
        </a>
    </div>
{% endfor %}

In this version, the class attribute is built by concatenating strings conditionally. If it's the first item, "first" is added; if it's the last, "last" is added. For middle items, no extra text is appended. This approach keeps the template logic self-contained. However, be mindful of whitespace control. If you strictly need a single space between classes (e.g., topmenu-button first last), ensure your conditional blocks or string concatenation handles spacing correctly to avoid double spaces like topmenu-button last.

There is also a potential pitfall when the array contains only one element. In that specific case, loop.first and loop.last are both true simultaneously. The logic naturally handles this because you simply add both classes: first last. This is usually the desired behavior for single-item lists, as the CSS selector can handle overlapping modifiers without conflict.

If you prefer not to rely on template logic for such structural decisions, you could modify the data in your controller. Passing a property like is_first or is_last alongside each item works well if your application frequently needs these flags elsewhere. However, keeping the logic inside the view using loop.index and loop.length is often preferable for simple lists, as it decouples the rendering logic from the business layer. This separation of concerns keeps your controllers clean and allows you to tweak the visual structure without touching the PHP codebase.

Our network