[英]Using dictionary of dictionaries in django templates not working well
加权有向图在python中表示为字典的字典。 如下所示(示例):
digraph = {'a': {'b':2, 'c':3}, 'b': { 'a':1, 'd',2}}
我的问题涉及将这个有向图对象传递给Django模板系统。 在此示例中,“ a”,“ b”,“ c”,“ d”是图形的节点,并且有向图表示这些节点之间的连接以及由整数值给出的每个连接边的权重。
考虑一个通用节点: node 。
我在访问模板内部的digraph.node.items时遇到困难。 对于任何字典D, D.items都适用。 但是当我们要访问子词典的项目时(在上面的图中),则不是。 这正是我想要的(但效果不佳):
{% for node in node_list %}
{% for adj_node,weight in digraph.node.items %}
{{ adj_node }}, {{ weight }} <br/>
{% endfor %}
{% endfor %}
adj_node和权重未打印。
可以定义自己的过滤器以从字典中提取感兴趣的值: http : //ralphminderhoud.com/posts/variable-as-dictionary-key-in-django-templates/
简短版本:
在project/app/templatetags/dictionary_extras.py
:
from django import template
register = template.Library()
@register.filter(name='access')
def access(value, arg):
return value[arg]
在urls.py
:
url(r'^testing', 'views.vTestingLists', name='testing_lists'),
在views.html
:
def vTestingLists(request):
context= {'d': {'a':'apple', 'b': 'banana', 'm':'mango', 'e':'egg', 'c':'carrot'}}
return render_to_response( 'testinglists.html', context )
在名为testinglists.html
的模板中:
{% load dictionary_extras %}
{% for key in d %}
{{ d|access:key }}
{% endfor %}
然后访问…/testing
URL,以查看您的手工结果。
这不是我的代码,全部归功于Ralph Minderhoud (链接文章的作者)。 我已验证此代码可以从此答案转录到Django 1.1环境中(而不是复制/粘贴)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.