django在模板中的for循环中仅打印一个值
我只想显示模板中for循环的一个值. 假设我有这个:
I want to display only one value from for loop in template. Let's say I have this:
{% for category in categories %}
{{category.name}}
<a href="{% url "my_url" category.id %}">See All</a>
{% endfor %}
如果我有5个类别,则请参阅全部打印5次.我怎么只能打印一次. 非常感谢.
If I have 5 category then See All in being printed 5 times. How can I only print it once.. Thanx in adnvance..
您应该拥有一个包含所有类别的主页,您可以在其中将其发送给它context['categories']
You should have a main page with all your categories in which you will send it context['categories']
如果您不需要详细地在类别之间建立链接,只需在views.py中发送当前类别:
And if you don't need to have a link between your categories in detail just send the current category in the views.py :
context['category']
如果您要做的只是中断循环,则无法使用django模板,但可以使用slice
:
If all you want to do is break in the loop you can't in django template but you can use slice
:
{% for category in categories|slice:":1" %}
它只会循环一次一次