简体   繁体   English

在Django的模板系统中,有时如何使它做不同的事情?

[英]In Django's template system, how do I make it to do different things sometimes?

{% for p in posts %}
    <div style="width:50px;">
    blah
    </div>
{% endfor %}

However, what if I want the div to be 100px 75% of the time? 但是,如果我希望div在75%的时间内成为100px,该怎么办? 25% of the time? 25%的时间? Randomized. 随机。

random过滤器应该做的事情

Logic does not go into templates. 逻辑不包含在模板中。

Solution: write a new template tag that returns a random number, and use that for the width. 解决方案:编写一个新的模板标签,该标签返回一个随机数,并将其用作宽度。

http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/ http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/

Your template would then look like: 您的模板如下所示:

{% for p in posts %}
    <div style="width:{% myrandomtag 0 100 %}px;">
    blah
    </div>
{% endfor %}

Or whatever. 管他呢。 Put your required logic in the python code for the tag. 将所需的逻辑放入标记的python代码中。

You can use Django's cycle method: 您可以使用Django的cycle方法:

{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
    ...
</tr>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM