0

I have an array which prints the list of some elements. I want to print those elements in a group of say '4'. That is if our array has 10 elements. Then in my template first <div> shows first 4 elements and next <div> shows next 4 elements. and so on.

I have tried to print like as we prints in PHP but it does not work here so please suggest me some way to do that.

There are 9 products in c.list and i want to show them as i have mentioned above:

{% if c.list|length >= 1 or c.list|length < 5 %}
        {% for p in c.list %}

        <div class="dis_box1">

        <div class="item_imagebox_01"><a href="/shop/product/{{p.title}}"><img style ="width:145px;height:190px;"alt="" src="{{ MEDIA_URL }}{{p.image}}"></a>
        <div class="img_line1"></div>
        </div>

        <div class="left"><span class="heart_text1"><a href="/shop/product/jhgjgj/">{{p.title}}</a></span></div>

            </div> 

        {% endfor %}
{% endif %}
6
  • 1
    Can we see the code you have tried? Your question is hard to interpret. I assume you want the if and for tags that you nest inside of templates? Commented Dec 12, 2012 at 7:20
  • I have edited my question please look at that Commented Dec 12, 2012 at 7:23
  • 2
    Can you try {% if forloop.counter|divisibleby:"4" %}</div><div>{% endif %} Commented Dec 12, 2012 at 7:29
  • I think the easiest way would be to split the list up into groups of four in your views code, and then pass that through so the template has to do less work. Commented Dec 12, 2012 at 7:31
  • That's what i am asking how to split the lists..I am using c.list[3] to show 3rd product of the array..but it throughs error.. Commented Dec 12, 2012 at 8:42

1 Answer 1

2

This is the kind of work you should really be doing in your view.

In your view:

list_by_fours = []
list_len = len(c.list)
last_point = 0
next_point = 4

while last_point < list_len:
  if next_point > list_len:
    next_point = list_len
  list_by_fours.append(c.list[last_point:next_point])
  last_point += 4
  next_point += 4

#Make sure you add list_by_fours to the template context

Then in your template:

{% for bucket in list_by_fours %}
        {% for p in bucket %}
             ...
        {% endfor %}
{% endif %}

I'm sure there's a way to do this with itertools or some other fancy trick, but this is clean and easy to understand for beginners.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.