Search code examples
wordpresstwigadvanced-custom-fieldstimberacfpro

Timber + ACF - How to get get_row_index() working?


Problem: I would need to get the current layout index from flexible content field. ACF already have built-in functionality for this - https://www.advancedcustomfields.com/resources/get_row_index/

Timber template:

{% extends "base.twig" %}

{% block content %}

    {% for flex_content in post.meta('flex_components') %}
        {{ get_row_index() }} <!-- I'm stuck here -->
        {% include [flex_content.acf_fc_layout|sanitize ~ '.twig'] ignore missing %}
    {% endfor %}

{% endblock %}

My current solution: Is using a simple counter, but I would like to learn how to get this working with get_row_index() function (if is possible).

{% extends "base.twig" %}

{% block content %}

    {% set my_counter = 1 %}
    {% for flex_content in post.meta('flex_components') %}
        {% include [flex_content.acf_fc_layout|sanitize ~ '.twig'] ignore missing %}
        {% set my_counter = my_counter + 1 %}
    {% endfor %}

{% endblock %}

Solution

  • Unfortunately, you can’t use get_row_index() when using Timber, because that function relies on a global variable set by ACF when using have_rows(), which we don’t have in Timber. This works similar to the WordPress Loop, which Timber tries to get rid of.

    In Twig, you can always use the loop variable inside a for loop. This variable provides you with the counter you need.

    {% extends "base.twig" %}
    
    {% block content %}
        {{ dump(loop.index) }}
    
        {% for flex_content in post.meta('flex_components') %}
            {% include [flex_content.acf_fc_layout|sanitize ~ '.twig'] ignore missing %}
        {% endfor %}
    {% endblock %}