Sunday, 23 August 2015

10 day - forloop and if in template

Basic Template Tags and Filters


if
{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% endif %}

{% if athlete_list %}
    <p>Here are the athletes: {{ athlete_list }}.</p>
{% else %}
    <p>No athletes are available.</p>
    {% if coach_list %}
        <p>Here are the coaches: {{ coach_list }}.</p>
    {% endif %}
{% endif %}


for

{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}

for and if

{% if athlete_list %}
    {% for athlete in athlete_list %}
        <p>{{ athlete.name }}</p>
    {% endfor %}
{% else %}
    <p>There are no athletes. Only computer programmers.</p>
{% endif %}

  • forloop.counter is always set to an integer representing the number of times the loop has been entered. This is one-indexed, so the first time through the loop, forloop.counter will be set to 1. Here’s an example:
    {% for item in todo_list %}
        <p>{{ forloop.counter }}: {{ item }}</p>
    {% endfor %}



  • forloop.parentloop is a reference to the forloop object for the parent loop, in case of nested loops. Here’s an example:
    {% for country in countries %}
        <table>
        {% for city in country.city_list %}
            <tr>
            <td>Country #{{ forloop.parentloop.counter }}</td>
            <td>City #{{ forloop.counter }}</td>
            <td>{{ city }}</td>
            </tr>
        {% endfor %}
        </table>
    {% endfor %}



it’s quite a common template requirement to compare two values and display something if they’re equal – and Django provides an {% ifequal %} tag for that purpose.
The {% ifequal %} tag compares two values and displays everything between {% ifequal %} and{% endifequal %} if the values are equal.
This example compares the template variables user and currentuser:
{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}

No comments:

Post a Comment