4

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.

2 Answers 2

6

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 %}
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.