python add a new div every 3rd iteration

穿精又带淫゛_ 提交于 2019-12-30 07:56:10

问题


I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding <div> around each group of 3 products will solve this is the template file at the moment

{% for product in category.products.all %}
        <div class="{% cycle 'clear' '' '' %}">
            <a href="{% url shop.views.product category.slug product.slug %}"><img src="{{MEDIA_URL}}{{product.mini_thumbnail}}" alt="{{product.name}}" class="thumbnail"/></a>
            <div class="prod-details">
            <h3><a href="{% url shop.views.product category.slug product.slug %}">{{product.get_product_name}}</a></h3>
            <h4 class="strap">{{product.get_product_detail}}</h4>
            <p>{{ product.strap }}</p>
            <ul>
                <li class="price">&pound;{{product.price}}</li>
                <li class="quantity">
                    <select name="quantity_{{product.id}}">
                        <option label="1" value="1">1</option>
                        <option label="2" value="2">2</option>
                        <option label="3" value="3">3</option>
                        <option label="4" value="4">4</option>
                        <option label="5" value="5">5</option>
                        <option label="6" value="6">6</option>
                        <option label="7" value="7">7</option>
                        <option label="8" value="8">8</option>
                        <option label="9" value="9">9</option>
                    </select>
                </li>
                <li><a href="{% url shop.views.product category.slug product.slug %}">Details &gt;</a></li>
                <li class="right"><input type="submit" name="add_to_basket_{{product.id}}" value="Add to Basket &gt;"/></li>
            </ul>
            </div>
        </div>
    {% endfor %}

回答1:


codeape's solution only works if you are using a very recent SVN checkout of Django trunk. If you're using version 1.1 or below, that syntax is not supported.

Instead, you can use the divisibleby filter:

{% if forloop.counter|divisibleby:3 %}<div>{% endif %}



回答2:


Use forloop.counter and a modulo operator inside the loop:

{% for ... %}
{% if forloop.counter|divisibleby:3 %}<div>{% endif %}
...
{% if forloop.counter|divisibleby:3 %}</div>{% endif %}
{% endfor %}

See http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

EDIT:

Fixed the code example.



来源:https://stackoverflow.com/questions/1945379/python-add-a-new-div-every-3rd-iteration

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