django模板中循环字典

views中

USER_DICT = {
  '1': {'name': 'root1', 'email': 'root@live.com'},
  '2': {'name': 'root2', 'email': 'root@live.com'},
  '3': {'name': 'root3', 'email': 'root@live.com'},
  '4': {'name': 'root4', 'email': 'root@live.com'},
  '5': {'name': 'root5', 'email': 'root@live.com'},
}
def index(request,nid,uid):
    return render(request, 'index.html', {'user_dict': USER_DICT})

html中

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>

  </head>
<body>
  <ul>

    {% for k,v in user_dict.tiems%}

      <li>{{k}}->{{v}}</li>

    {%endfor%}

  </ul>

  或

  

    {% for k in user_dict.keys%}

      <li>{{k}}</li>

    {%endfor%}

  

 或

    {% for v in user_dict.values%}

      <li>{{v}}</li>

    {%endfor%}

</body>
</html>

原文地址:https://www.cnblogs.com/Samuel-Leung/p/10813063.html