How to briefly imagine if / else specify CSS classes in Django templates

In a Django template, I would like to add CSS classes to the DIV based on certain “conditions”, for example:

<div class="pkg-buildinfo 
            {% if v.release.version == pkg.b.release.version %}active{% else %}inactive{% endif %} 
            {% if v.release.version == project.latest.version %}latest{% else %}notlatest{% endif %}">

(note that vthis is a loop variable, it's all inside the loop for)

The above adds the CSS classes "active" or "inactive" and "latest" or "notlatest" based on two conditions.

It is, however, difficult to read and verbose. I found that the operator withdoes not support assigning values ​​to expressions / conditions (as opposed to complex variables), which is very pathetic. Is there a better way to do this?

+5
source share
3

, "" "", .. .

+5

with:

{% with v.release.version as version %}
<div class="pkg-buildinfo 
            {% if version == pkg.b.release.version %}active{% else %}inactive{% endif %} 
            {% if version == project.latest.version %}latest{% else %}notlatest{% endif %}">
{% endwith %}

, , :

context_data = {
    'class_active': v.release.version == pkg.b.release.version and "active" or "inactive",
    'class_latest': v.release.version == project.latest.version and "latest" or "notlatest",
    ... }

:

<div class="pkg-buildinfo {{ class_active }} {{ class_latest }}"
+3

A custom filter can be a nice alternative.

@register.filter
def active_class(obj, pkg):
    if obj.release.version == pkg.b.release.version:
         return 'active'
    else:
        return 'inactive'

and use it in the template:

<div class="pkg-buildinfo {{ obj|active_class:pkg }}" 
+3
source

All Articles