Olivier Le Moign
Olivier Le Moign

Reputation: 91

Jinja2 not returning loop variables

I have a website with Jinja2 on Google App Engine, so the version is 2.6. At some point, I loop through a list to produce radio buttons and I would like to have the first one checked by default. My code is the following:

     {% for publisher in publishers %}
        <tr onclick="doNav('/spt/publisher/{{ publisher.id }}');" style="cursor: pointer;">
            <td>{{ publisher.name }}</td>
            <td>{{ publisher.songs }}</td>
            <td><input form="export_publisher_form" onclick="event.cancelBubble = true;"
                       type="radio" name="export_publisher" value="{{ publisher.id }}"{% if loop.first %} checked{% endif %}></td>
        </tr>
    {% endfor %}

Problem is, Jinja doesn't seem to return any value for loop.first, nor any loop variable (I tried with loop.index, loop.length and loop.cycle). Am I doing something wrong ?

Edit: publishers is a list that looks like this (indented for clarity):

[{'id': 4974053165105152L, 'name': u'BMG', 'songs': 1}, 
 {'id': 5888297083600896L, 'name': u'Emi', 'songs': 2}, 
 {'id': 6099953071947776L, 'name': u'Ninja Tune', 'songs': 1}, 
 {'id': 4762397176758272L, 'name': u'Sony', 'songs': 0}, 
 {'id': 5325347130179584L, 'name': u'Universal', 'songs': 0}, 
 {'id': 4815173734891520L, 'name': u'Warner', 'songs': 0}]

Upvotes: 3

Views: 429

Answers (1)

Andrew Kloos
Andrew Kloos

Reputation: 4578

Weird... what version of python are you using? When I execute this code I get the following output:

 {% for publisher in heater %}
    <tr onclick="doNav('/spt/publisher/{{ publisher.id }}');" style="cursor: pointer;">
        <td>{{ publisher.name }}</td>
        <td>{{ publisher.songs }}</td>
        <td><input form="export_publisher_form" onclick="event.cancelBubble = true;"
                   type="radio" name="export_publisher" value="{{ publisher.id }}"{% if loop.index == 2 %} checked{% endif %}></td>
    </tr>
{% endfor %}

I get Emi 2 checked. What are you seeing?

I also changed your data to this:

    data = [{'id': 4974053165105152, 'name': 'BMG', 'songs': 1}, 
              {'id': 5888297083600896, 'name': 'Emi', 'songs': 2}, 
              {'id': 6099953071947776, 'name': 'Ninja Tune', 'songs': 1}, 
              {'id': 4762397176758272, 'name': 'Sony', 'songs': 0}, 
              {'id': 5325347130179584, 'name': 'Universal', 'songs': 0}, 
              {'id': 4815173734891520, 'name': 'Warner', 'songs': 0}]

Upvotes: 1

Related Questions