【发布时间】:2018-05-08 08:07:35
【问题描述】:
我使用自定义小部件来修改小部件模板的上下文(添加更多信息)。
上下文:
'selected': [[3, 9], [3, 4, 7, 6]], 'depth_levels': {0: [{'name': 'Category A', 'value': 3, 'depth': 0, 'parent_id': None, 'children': [4, 9]}, {'name': 'Category B', 'value': 8, 'depth': 0, 'parent_id': None, 'children': []}], 1: [{'name': 'Category A_1', 'value': 4, 'depth': 1, 'parent_id': 3, 'children': [5, 7]}
{% for path in widget.selected %}
{% for selected in path %}
{% for level in widget.depth_levels.forloop.counter0 %}
{{ level }}
{% endfor %}
{% endfor %}
{% endfor %}
首先我循环遍历选定的(路径)和内部数组(选定的)。 我想使用 {{forloop.counter0}} 作为 depth_levels 的键。
问题:{{widget.depth_levels.forloop.counter0}} 不返回任何内容。
forloop.counter 不用作列表的索引,但它用作字典的键。
使用“。”访问是 Django 模板访问字典的默认方式* 使用 '0'、'1' - {{widget.depth_levels.0}}- 等而不是 forloop.counter0 它可以工作。
再次使用自定义模板标签会出现问题,因为访问位于for 内部,无法在内部使用{{}}:
{% for level in widget.depth_levels.forloop.counter0 %}
我需要访问 depth_levels 的键是从 0 到 selected 中每个数组的长度,示例中的“路径”数组。
选择数组中的值告诉我稍后在哪里添加属性与 depth_levels 的键无关。
我的最终目标是访问数组中字典中的name、value。
【问题讨论】:
-
This 可能有帮助
-
^看第二个答案
-
@Laur Ivan - 我的情况不同我不需要访问 {{forloop.counter}} 作为默认值或他的父母(我可以这样做没有问题),而是像使用它一样字典的键
-
@Sayse forloop.counter 不用作列表的索引,但它用作字典的键(如在另一篇文章中)。使用 '。' to access 是 Django 模板访问字典的默认方式,这就是为什么我不明白为什么它不起作用。如果我使用“0”、“1”,而不是“动态”,它会起作用