在Django模板中的另一个字典中迭代一个键的字典

时间:2021-10-06 14:30:25

I have a dictionary that looks like the following:

我有一个字典,如下所示:

timeTables = {
        'today': {'date_start': datetime.now(), 'date_end': None},
        'yesterday': {'date_start': (datetime.now() - timedelta(days=1)), 'date_end': None},
        'week': {'date_start': (datetime.now() - timedelta(weeks=1)), 'date_end': datetime.now()},
        'month': {'date_start': (datetime.now() - timedelta(days=30)), 'date_end': datetime.now()},
    }

I want to output the today keys dictionary elements in a for loop within the Django template.

我想在Django模板中的for循环中输出今天的键字典元素。

I can accomplish this in normal Python via:

我可以通过以下方式在普通的Python中完成

for key, value in timeTables['today'].items():
        print key, value

But this same thing won't work in a Django template.

但是同样的事情在Django模板中不起作用。

Doing this gives an error:

这样做会出错:

{% for key, value in data['today'].items %}
    {{ key }} {{ value }}
{% endfor %}

TemplateSyntaxError at /
Could not parse the remainder: '['today'].items' from 'data['today'].items'

2 个解决方案

#1


1  

In Django templates, you cannot use the data['today'] syntax to access the value of a dictionnary, you need to use the . (data.today):

在Django模板中,您无法使用数据['today']语法来访问字典的值,您需要使用。 (data.today):

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

#2


0  

try this: If you want only dictionary field with only 'today' key then simply send data['today'] from view {'data': data['today']} and then render it like:

试试这个:如果你只想要只有'今日'键的字典字段,那么只需从view {'data':data ['today']}发送数据['today']然后渲染它:

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

If you want whole dictionary to be sent then,

如果你想要发送整本字典,

{% for key, value in data.items %}
    {% for k,v in value.items %}
     {{k}} {{v}}
    {% endfor %}
{% endfor %}

#1


1  

In Django templates, you cannot use the data['today'] syntax to access the value of a dictionnary, you need to use the . (data.today):

在Django模板中,您无法使用数据['today']语法来访问字典的值,您需要使用。 (data.today):

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

#2


0  

try this: If you want only dictionary field with only 'today' key then simply send data['today'] from view {'data': data['today']} and then render it like:

试试这个:如果你只想要只有'今日'键的字典字段,那么只需从view {'data':data ['today']}发送数据['today']然后渲染它:

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

If you want whole dictionary to be sent then,

如果你想要发送整本字典,

{% for key, value in data.items %}
    {% for k,v in value.items %}
     {{k}} {{v}}
    {% endfor %}
{% endfor %}