Home > other >  loop.last in jinja2 not working properly in django
loop.last in jinja2 not working properly in django

Time:06-09

guys I am trying to avoid printing two divs in my table in the last iteration of the loop of my Django template. I have used loop.last variable to check if the loop is in its last iteration, but it is not working for some reason. Here program session is simply a range(number_of_iterations_required). Here is my code:

                                {% for n in program_sessions %}
                                <!-- 1st session start -->
                                <tr >
                                    <td >
                                        <div >
                                            <div >
                                                <span >Row: &nbsp;</span>
                                            </div>
                                            <div >
                                                <span >{{program.workout_time}}m</span>
                                            </div>
                                            {% if not loop.last %}
                                            <div >
                                                <span >Rest: &nbsp;</span>
                                            </div>
                                            <div >
                                                <span >{{program.rest_time}}min</span>
                                            </div>
                                            {% else %}
                                            <div >
                                                <span >Last Iteration boii! &nbsp;</span>
                                            </div>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                <!-- 1st session ends -->
                                {% endfor %}

                            </tbody>
                        </table>
                    </div>

Thank you in advance for your help. Have a good day.

CodePudding user response:

Looks like the syntax is not right. Try to change it to forloop instead of loop. You can have a look at the django docs for more info

{% if not forloop.last %}
  • Related