简体   繁体   中英

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? 25% of the time? 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/

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.

You can use Django's cycle method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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