大家都知道,在Django的模板中不允许使用字典,只能使用类;虽然我们可以定义类来代替字典,但字典各种各样,我们总不可能每次都定义不同的类吧?因此,我们需要一个可以把字典转化成类的通用方法,让我们在顺利地在模板中使用字典。从本质上来讲,在Django的模板中使用字典的关键之处在于把字典递归转化为类。
#!/usr/bin/python
#-*- coding: utf-8 -*-
def dict2obj(args):
'把字典递归转化为类'
class obj(object):
def __init__(self, d):
for a, b in d.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, obj(b) if isinstance(b, dict) else b)
return obj(args)
from django.conf import settings
import os.path
settings.configure(
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
),
TEMPLATE_DIRS = (
os.path.dirname(__file__),
)
)
child1 = {'name': 'Child1'}
child2 = {'name': 'Child2'}
child3 = {'name': 'Child3'}
child_list = [child1, child2, child3]
parent1 = {'name': 'parent1', 'children': child_list};
parent2 = {'name': 'parent2', 'children': child_list};
parent3 = {'name': 'parent3', 'children': child_list};
parent_list = [dict2obj(parent1), dict2obj(parent2), dict2obj(parent3)]
from django.template import loader, Context
t = loader.get_template('demo.tpl')
context_dict = {
'persons' : parent_list,
}
c = Context(context_dict)
print t.render(c)
由于模板文件不一定要HTML格式,为简单起见,我们就使用纯文本的方式。
{% for person in persons %} {{ person.name }} {% for child in person.children %} {{ child.name }} {% endfor %} {% endfor %}