首页 > 解决方案 > 在 Django 模板上同时运行两个列表

问题描述

如何在不使用 zip 功能的情况下在 Django 模板上同时运行两个列表。

视图.py

l1=[1,2,3]
l2=[4,5,6]
return render(request,'home.html',{'l1':l1,'l2':l2})

我在模板页面上传递这种类型的列表现在需要在模板上同时运行两个列表。我怎样才能做到这一点。

注意---只有我想在我的模板页面上这样做

标签: djangodjango-templates

解决方案


在这种情况下,请尝试创建一个模板过滤器:

@register.filter(name='zip')
def zip_lists(a, b):
  return zip(a, b)

在您的模板中:

{%for a, b in l1|zip:l2 %}
  {{a}}
  {{b}}
{%endfor%}

通过这种方式,您不需要修改您的视图更多详细信息:https ://docs.djangoproject.com/en/dev/howto/custom-template-tags/


推荐阅读