Re: checking size of dict or list in template

3,488 views
Skip to first unread message
Message has been deleted

Tom Evans

unread,
Mar 3, 2010, 4:57:02 AM3/3/10
to django...@googlegroups.com
On Wed, Mar 3, 2010 at 7:52 AM, harryos <oswald...@gmail.com> wrote:
>
> hi
> I am passing a dictionary to the template
> say,
> objects_status={obj1:True,   obj2:False,  obj3:True }
>
> In the template I want to show something like
>
> {%if not  len(objects.status ) %} # just to clarify the purpose..I
> know len will not work
> No objects to show
>
> {% else %}
> Objects are:
> .....show the objects and truth values in a table ....
>
> {%endif %}
>
>
> But how can I check the size of the dictionary? If it was a Queryset I
> could have used qset.count  ..but here it would not work.
> Can somebody help?
>
> thanks
> harry
>

For this specific example, you could use the for .. empty[1] template
tag, and look at objects.items(), eg:

{% for obj, status in objects_status.items %}
{{ obj }}
{% empty %}
No objects
{% endfor %}

If you actually wanted to access the size of the dictionary, you
should use the length[2] template filter, eg:

There are {{ objects_status.items|length }} object(s).

Cheers

Tom

[1] http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#for-empty
[2] http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#length

Reply all
Reply to author
Forward
0 new messages