如何迭代和访问django模板中的每个值?

时间:2017-05-24 21:13:31

标签: django python-3.x django-templates iterate

我有一个包含以下数据的字典:

   { "redirects": [
            {"status":"301","url":"/ca/products/marketing-cloud/"},
            {"status":"301","url":"https://www.example.com/ca/products/marketing-cloud/"},
            {"status":"301","url":"/ca/products/marketing-cloud/overview/"}
     ] 
   }

我尝试使用for循环,如下所示

{% for key, value in data.items %}
   {{ key }} => {{ value }
{% endfor %}

但它只打印

redirects => [{'status': '301', 'url': '/ca/products/marketing-cloud/'}, {'status': '301', 'url': 'https://www.example.com/ca/products/marketing-cloud/'}, {'status': '301', 'url': '/ca/products/marketing-cloud/overview/'}]

如何迭代它以便我可以访问status的值,url?

我是python和django的新手。请帮忙解决。

谢谢。

2 个答案:

答案 0 :(得分:1)

假设您的词典名为data

{% for dict in data['redirects'] %}
    {% for k, v in dict.items %}
        {{ k }} => {{ v }}
    {% endfor %}
{% endfor%}

答案 1 :(得分:0)

我们假设您的数据为data

for item in data['redirects']:
    status = item['status']
    url = item['url']
    print("Status: {}, URL: {}".format(status, url))

如果您想对此进行进一步解释,请与我联系!