在Django模板中如何简洁地表示if / else来指定CSS类 [英] How to concisely represent if/else to specify CSS classes in Django templates

查看:230
本文介绍了在Django模板中如何简洁地表示if / else来指定CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django模板中,我想根据某些条件将CSS类添加到DIV中,例如:

In a Django template, I'd like to add 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 v 是一个循环变量;整个事情都在中,循环)

(note that v is a loop variable; the whole thing is inside a for loop)

上面添加了CSS类基于两个条件,活动或不活动,最新或最新。

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.

这篇关于在Django模板中如何简洁地表示if / else来指定CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆