开发者

How to concisely represent if/else to specify CSS classes in Django templates

In a Django template, I'd like to add开发者_C百科 CSS classes to a 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 v is a loop variable; the whole thing is inside a for loop)

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

This is however hard to read and verbose. I discovered that the with statement does not support assigning the value of expressions/conditions (as opposed to complex variables) which is a pity. Is there a better way to do this?


You could put that logic into your view instead, and create attributes on the object that are "active" or "inactive", etc. Then you only have to access the attributes in the template.


A custom filter might 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 your template:

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


You can shorten it a bit by the with statement:

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

But it surely would be better to put that logic into the view:

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",
    ... }

and in the template:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜