django模版中的比较运算的方式一直是被众人所诟病的,提供的很少的几个运算符如ifequal、ifnotequal等,看起来很怪异,也不够灵活。而&gt;,<,==等这些常见的运算完全不支持,被广大django粉丝所抱怨,每次在模板中用到比较运算时都有拍案而起的冲动-_ -!

好在django从善如流!

昨晚在阅读django的文档时,发现在最新版本的模版api中已经加入了操作符的支持,激动啊。但目前还没有放出,仍在开发版本中( New in Django Development version)。最新版本的模版加入了==, !=, &lt;, >, <=, >=,in这几种比较运算,使用起来很方便。特别赞的是in运算,支持如下几种方式:

{% if "bc" in "abcdef" %}
    This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if "hello" in greetings %}
    If greetings is a list or set, one element of which is the string
    "hello", this will appear.
{% endif %}

{% if user in users %}
    If users is a QuerySet, this will appear if user is an
    instance that belongs to the QuerySet.
{% endif %}


很帅吧!另外操作符还支持filters,将filters的结果进行比较运算:

{% if messages|length >= 100 %}
     You have lots of messages today!
{% endif %}


更多详细说明,请 猛击这里围观。

其实django的模版从1.0以来已经做出了很多改变,加入了很多方便开发的新特性,只是我没有关注过而已。以后要多加关注,养成阅读在线文档的好习惯。

希望django越来越强大,走的更远!