django - 在 Django 模板上同时运行两个列表
问题描述
如何在不使用 zip 功能的情况下在 Django 模板上同时运行两个列表。
视图.py
l1=[1,2,3]
l2=[4,5,6]
return render(request,'home.html',{'l1':l1,'l2':l2})
我在模板页面上传递这种类型的列表现在需要在模板上同时运行两个列表。我怎样才能做到这一点。
注意---只有我想在我的模板页面上这样做
解决方案
在这种情况下,请尝试创建一个模板过滤器:
@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/
推荐阅读
- angular - 我应该如何在 Angular 中使用嵌套模块处理路由
- pandas - 使用 If else 语句的偏移函数
- python - 按组求和,保留 NA
- kubernetes - 我正在尝试通过结束我的 splunk 云实例的事件来测试我的 splunk HEC 令牌,如何验证我拥有正确的 HEC 主机名?
- bash - 如何从所有键值对中打印键
- alloy - Alloytools 崩溃并且不再启动
- android-studio - 在 android studio 3.5 的清单文件中编写意图过滤器时没有对 SdkConstants 的建议
- reactjs - 错误的类属性 - Emmet VSCode
- ruby-on-rails - 如何设置默认标题?
- python - Python - 将 csv 文件上传到 Dropbox