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:


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"