Reputation: 5863
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 %}
If I have 5 category then See All in being printed 5 times. How can I only print it once.. Thanx in adnvance..
Upvotes: 0
Views: 4460
Reputation: 2523
This code will print the first element in Category
{% for category in categories %}
{% if categories | first %}
{{category.name}}
<a href="{% url "my_url" category.id %}">See All</a>
{% endif %}
{% endfor %}
Upvotes: 0
Reputation: 4292
Not the best way but check this:
{% for category in categories %}
{% if categories|length > 1 %}
<a href="{% url "my_url" category.id %}">See All</a>
{% else %}
{{categories[1].name}}
<a href="{% url "my_url" category.id %}">{{category.name}}</a>
{% endif %}
{% endfor %}
Upvotes: 0
Reputation: 110
You should have a main page with all your categories in which you will send it context['categories']
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']
EDIT:
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" %}
It will just go through the loop once
Upvotes: 2
Reputation: 10305
You have to limit the object and send that object to template
tempalte_var['content'] = Categories.objects.all()[:5]
Upvotes: 0