On Mon, Feb 15, 2010 at 2:54 AM, Javier Rivera <jav...@castroparga.com>wrote:

> Karen Tracey wrote:
>
>>    Now in a template I want to iterate over them as follows:
>>    {% for project in projects %}
>>    <h1 class="a">{{ project }}</h1>
>>     {% for chain in project.chains %}
>>     -- {{ chain }}
>>     {% endfor %}
>>    {% endfor %}
>>
>
>
Note what you've posted above is the original non-working template block.
What I posted to take its place was:

{% for project, chains_dict in projects.items %}
<h1 class="a">{{ project }}</h1>
 {% for chain in chains_dict.chains %}
 -- {{ chain }}
 {% endfor %}
{% endfor %}

And recall the value of projects that was posted:

projects = {u'NetMinutes': {'chains': [u'Arendus', u'Uuslahendus']},
u'Veel': {'chains': []}}



I'm usually use the values() property to iteract dictionary values. I find
> it more readable than items(), and usually, as I need to sort the output,
> the fact that it returns a list is quite useful.


If all you need to iterate over are the dictionary values, and you do not
care what the keys are, then using values() is appropriate.  That's not the
case for the originally posted block.


> {% for project in projects %}
>        <h1 class="a">{{ project }}</h1>
>                {% for chain in project.chains.values %}
>                 -- {{ chain }}
>        {% endfor %}
> {% endfor %}
>
>
This block suffers from the same problem as the original.  Iterating over
'project in projects' just gives you the keys from projects, as strings. For
the posted projects value, project will take on the values u'NetMinutes' and
u'Veel' (not necessarily in that order) during successive iterations of the
loop. u'NetMinutes', or u'<anything else>' does not have an attribute
chains, so the inner 'for chain in project.chains.values' has nothing to
iterate over.

For the originally posted block, it was clear that the intent was to use
both the keys and the values from the projects dictionary, that's why the
replacement proposed using items() when iterating over the projects dict.
Replacing 'for project in projects' with 'for project in projects.values'
would also not work since then the inclusion of {{ project }} in the <h1>
header would not produce the desired output.

Karen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to