Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add html classes to a Django template 'for-loop' dynamically?

I have a CSS file where some of my styles are defined:

.class-a{
    /*some styles*/
}
.class-b{
    /*some styles*/
}
.class-c{
    /*some styles*/
}
.class-d{
    /*some styles*/
}

These styles must be applied to the output of a django for-loop.

The for-loop:

{% for result in results %}
    <span class="[something]" > {{result}} </span> <br>
{% endfor %}

How do I modify this loop, the class="[something]" part, so that the output looks something like this, in or out of order:

<span class="class-a"> result </span>
<span class="class-b"> result </span>
<span class="class-c"> result </span>

Should I do it in the context this way:

results = {
    ResultOne : {
            'name' : 'someName',
            'class' : 'class-a'

    },
    ResultTwo : {
            'name' : 'someName',
            'class' : 'class-b'

    },
}

So that there goes something like {{result.class}} and {{ result.name}} for each {{ result }} ?

Or does there exist some other method? What is the best way to achieve it? Thanks.

like image 397
All Іѕ Vаиітy Avatar asked Sep 12 '25 12:09

All Іѕ Vаиітy


1 Answers

You can use the cycle template tag:

{% for result in results %}
    <span class="{% cycle "class-a" "class-b" "class-c" "class-d"%}" > {{result}} </span> <br>
{% endfor %}
like image 165
301_Moved_Permanently Avatar answered Sep 15 '25 01:09

301_Moved_Permanently