django模板中for语句同时遍历两个列表

烂漫一生 提交于 2020-02-12 04:28:24

首先,如果在模板中直接遍历两个列表是会报错的,因为不支持。
那么,我们怎么解决?
有办法,在视图中先把两个列表用zip()函数打包即可,这样,就可以在模板中对两个列表同时for输出了

视图:

def personal(request,account):
    account=account
    user = User.objects.get(account=account)
    icon_path=user.img
    #此处是将两个列表打包
    information=['昵称','账号','性别','注册时间']
    information2=[user.name,user.account,user.gender,user.create_time]
    user2=zip(information,information2)
    return render(request,'personal.html',{'user':user2,'icon':icon_path})

模板:

{% for x,y in user %}
            {% if y == True %}
            <p><label for="{{ x }}">{{ x }}:--------->></label><span>  </span></p>
            {% elif y == False %}
            <p><label for="{{ x }}">{{ x }}:--------->></label><span>  </span></p>
            {% else %}
            <p><label for="{{ x }}">{{ x }}:--------->></label><span>  {{ y }}</span></p>
            {% endif %}
    {% endfor %}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!