Python 来自列表的Django模板中的多列表
我有一个清单如下Python 来自列表的Django模板中的多列表,python,django,django-templates,Python,Django,Django Templates,我有一个清单如下 list = {a,1,b,2,c,3,d,4,.....} 我想在Django模板中显示它,有4列,如下所示 <table> <tr> <td>a</td> <td>1</td> <td>b</td> <td>2</td> </tr> <tr> <td>c</td> <td>3</td>
list = {a,1,b,2,c,3,d,4,.....}
我想在Django模板中显示它,有4列,如下所示
<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>
A.
1.
B
2.
C
3.
D
4.
在Django模板中如何实现这一点?为什么不在Python中解决分块部分,然后适当地呈现模板 模板:
<table>
{% for row in data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
在哪里
演示(都在控制台中,没有Django项目集): [1]中的
:来自django.conf导入设置
在[2]中:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates'}]
在[3]中:设置.配置(模板=模板)
在[4]中:从django.template导入模板,上下文
在[5]中:导入django
在[6]:django.setup()中
在[7]中:l=['a',1,'b',2,'c',3,'d',4]
在[8]中:数据=块(l,n=4)
在[9]t=“”
...:
…:{%用于数据%中的行}
...:
…:{行%]中的单元格的%
…:{{cell}
…:{%endfor%}
...:
…:{%endfor%}
...:
...: """
在[10]中:print(Template(t).render(Context({'data':data})))
A.
1.
B
2.
C
3.
D
4.
制作模板标签
在我的标签里
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
和html格式
{% my_tag %}
<table class="table">
{% for chunk in lst|chunks:4 %}
<tr>
{% for x in chunk %}
<td>
{{ x }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{%my_tag%}
{lst中块的百分比|块:4%}
{区块%中x的百分比}
{{x}
{%endfor%}
{%endfor%}
非常感谢。我对django没有兴趣。这就是为什么我不能理解这一点。现在很清楚了,非常感谢。我遵循了这个代码片段。它起作用了
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
{% my_tag %}
<table class="table">
{% for chunk in lst|chunks:4 %}
<tr>
{% for x in chunk %}
<td>
{{ x }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>