Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Templates First element of a List

I pass a dictionary to my Django Template,

Dictionary & Template is like this -

lists[listid] = {'name': l.listname, 'docs': l.userdocs.order_by('-id')}

{% for k, v in lists.items %}
    <ul><li>Count: {{ v.docs.count }}, First: {{ v.docs|first }}</li></ul>
{% endfor %}

Now docs is a list of userdocs type. i.e. is an instance. So first filter returns me this instance. From this I need to extract it's id. How do I do that?

I tried {{ v.docs|first }}.id and various other futile trials.

like image 882
Srikar Appalaraju Avatar asked Nov 26 '10 15:11

Srikar Appalaraju


3 Answers

You can try this:

{{ v.docs.0 }}

Like arr.0

You can get elements by index (0, 1, 2, etc.).

like image 100
Abdul Majeed Avatar answered Sep 24 '22 18:09

Abdul Majeed


You can use the {% with %} templatetag for this sort of thing.

{% with v.docs|first as first_doc %}{{ first_doc.id }}{% endwith %}
like image 32
Daniel Roseman Avatar answered Sep 21 '22 18:09

Daniel Roseman


I don't know if this is helpful..

What you want is the first value of an iterable (v.docs) and you are iterating over another encapsulating iterable (lists).

For the count, I would do the same, but for the first element.. I'd iterate over the v.docs individually and retrieve the first value via an inner loop.

{% for doc in v.docs %}
    {% if v.docs | first %}  
    <li>doc</li>
    {% endif %}
{% endfor %}

Note: the first filter is applied to v.docs , not doc. Yeah. It involves another loop :(

like image 8
Johnson Avatar answered Sep 20 '22 18:09

Johnson