Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

twig

symfony

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?

like image 987
mickburkejnr Avatar asked Dec 02 '25 06:12

mickburkejnr


1 Answers

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.

like image 82
Ramon Kleiss Avatar answered Dec 04 '25 00:12

Ramon Kleiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!