django在模板中的for循环中仅打印一个值 [英] django print only one value in for loop in template

查看:215
本文介绍了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" %}

它只会循环一次一次

这篇关于django在模板中的for循环中仅打印一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆