0

I have a list following

list = {a,1,b,2,c,3,d,4,.....}

I want to show it in Django template with 4 column like below

<table>
<tr>
<td>a</td>
<td>1</td>
<td>b</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>3</td>
<td>d</td>
<td>4</td>
</tr>
</table>

How can I do that in Django Template

2 Answers2

1

make template tag

in my_tag.py

from django import template

register = template.Library()

@register.filter(name='chunks')
def chunks(iterable, chunk_size):
    if not hasattr(iterable, '__iter__'):
        yield iterable
    else:
        i = 0
        chunk = []
        for item in iterable:
            chunk.append(item)
            i += 1
            if not i % chunk_size:
                yield chunk
                chunk = []
        if chunk:
            yield chunk

and in html

{% my_tag %}
<table class="table">
    {% for chunk in lst|chunks:4 %}
    <tr>
        {% for x in chunk %}
        <td>
            {{ x }}
        </td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
Nikunj
  • 305
  • 1
  • 7
0

Why don't solve the chunking part in Python and then render the template appropriately?

Template:

<table>
    {% for row in data %}
        <tr>
        {% for cell in row %}
            <td>{{ cell }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>

Python part:

l = ['a',1,'b',2,'c',3,'d',4]
data = chunks(l)
print(data)
# prints [['a', 1, 'b', 2], ['c', 3, 'd', 4]]

where chunks is coming from this answer.


Demo (all in the console without a Django project set):

In [1]: from django.conf import settings

In [2]: TEMPLATES = [{'BACKEND':  'django.template.backends.django.DjangoTemplates'}]

In [3]: settings.configure(TEMPLATES=TEMPLATES)

In [4]: from django.template import Template, Context

In [5]: import django

In [6]: django.setup()

In [7]: l = ['a',1,'b',2,'c',3,'d',4]

In [8]: data = chunks(l, n=4)

In [9] t = """
    ...: <table>
    ...:     {% for row in data %}
    ...:         <tr>
    ...:         {% for cell in row %}
    ...:             <td>{{ cell }}</td>
    ...:         {% endfor %}
    ...:         </tr>
    ...:     {% endfor %}
    ...: </table>
    ...: """


In [10]: print(Template(t).render(Context({'data': data})))

<table>
    
        <tr>
        
            <td>a</td>
        
            <td>1</td>
        
            <td>b</td>
        
            <td>2</td>
        
        </tr>
    
        <tr>
        
            <td>c</td>
        
            <td>3</td>
        
            <td>d</td>
        
            <td>4</td>
        
        </tr>
    
</table>
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195