Skip to content Skip to sidebar Skip to footer

Django Print Only One Value In For Loop In Template

I want to display only one value from for loop in template. Let's say I have this: {% for category in categories %} {{category.name}}

Solution 1:

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

Solution 2:

You have to limit the object and send that object to template

tempalte_var['content'] = Categories.objects.all()[:5]

Solution 3:

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 %}

Solution 4:

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 %}

Post a Comment for "Django Print Only One Value In For Loop In Template"