Get row number for each record retrieved from MySQL using Twig in Symfony

symfony, twig

Solution

Try the following in Twig:

{% for row in rows %}
    <div id="row{{ loop.index0 }}"><!-- Stuff --></div>
{% endfor %}

As you can read here Twig loops have a number of variables available that you can use inside the loop. We want to know the 0-based index (according to your specification) so we have to use the `index0` property of the loop. If you would want to start at 1 you'd have to use `index` instead of `index0`.

Problem

I'm retrieving a list of names from a database using Symfony2 and MySQL, and displaying it using Twig. For each record that's retrieved I'm putting them in to a row of a table. I want to be able to give each row a unique ID based on what number record it is. So, if I have 5 records from the database, the first one would have an ID of "row0", then "row1" etc etc. How can I achieve this using Twig?

Original source