Python Django 模板列表的第一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4286461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Templates First element of a List
提问by Srikar Appalaraju
I pass a dictionary to my Django Template,
我将字典传递给我的 Django 模板,
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 docsis a list of userdocstype. i.e. is an instance. So firstfilter returns me this instance. From this I need to extract it's id. How do I do that?
现在docs是userdocs类型列表。即是一个实例。所以first过滤器返回我这个实例。从这里我需要提取它的id. 我怎么做?
I tried
{{ v.docs|first }}.idand various other futile trials.
我试过
{{ v.docs|first }}.id和其他各种徒劳的试验。
采纳答案by Daniel Roseman
You can use the {% with %}templatetag for this sort of thing.
您可以将{% with %}模板标签用于此类事情。
{% with v.docs|first as first_doc %}{{ first_doc.id }}{% endwith %}
回答by Johnson
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).
您想要的是可迭代对象(v.docs)的第一个值,并且您正在迭代另一个封装可迭代对象(列表)。
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.
对于计数,我会做同样的事情,但对于第一个元素..我会单独迭代 v.docs 并通过内部循环检索第一个值。
{% 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 :(
注意:第一个过滤器应用于 v.docs ,而不是 doc。是的。它涉及另一个循环:(
回答by Abdul Majeed
You can try this:
你可以试试这个:
{{ v.docs.0 }}
Like arr.0
喜欢 arr.0
You can get elements by index (0, 1, 2, etc.).
你可以通过索引(元素0,1,2,等)。

