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

我与影子孤独终老i 提交于 2019-12-05 08:01:14

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.

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

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 }}" 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!