【问题标题】:how to iterate and access each values in django template?如何迭代和访问 django 模板中的每个值?
【发布时间】:2017-05-24 21:13:31
【问题描述】:

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

   { "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 的新手。请帮忙解决。

谢谢。

【问题讨论】:

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


【解决方案1】:

假设您的字典名为data

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

【讨论】:

    【解决方案2】:

    假设您的数据是data

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

    如果您想对此进行进一步解释,请告诉我!

    【讨论】:

    • 我已经更新了我的问题。您能否进一步指导如何在 django 模板中实现?
    猜你喜欢
    • 1970-01-01
    • 2019-04-26
    • 2011-11-05
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多