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

5👍

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

5👍

Minimize logic in the Template

I think what you suggested is the way to go, i.e. pre-process your data before it goes into the template

With Django templates complex logic will become unmaintainable and unreadable quickly

Don’t mix Python and HTML

It won’t be very good to have class as in CSS class in Python code, so maybe call it something within the domain of your models, e.g.

results = [
    {
            'name' : 'some_name_1',
            'result_type' : 'a'

    },
    {
            'name' : 'some_name_2',
            'result_type' : 'b'

    },
]

and make it so that the HTML/CSS just uses that result-type to resolve the CSS name, so:

<span class="class-{{result.result_type}}"> {{result.name}} </span>
👤bakkal

Leave a comment