本文整理汇总了Python中template.Template.load_template方法的典型用法代码示例。如果您正苦于以下问题:Python Template.load_template方法的具体用法?Python Template.load_template怎么用?Python Template.load_template使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类template.Template
的用法示例。
在下文中一共展示了Template.load_template方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PABL
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import load_template [as 别名]
class PABL(object):
def __init__(self, root_template_directory=None, module_directory=None):
self.template_loader = Template(root_template_directory,
module_directory)
self.formatters = {'json': self.to_json}
self.parser = PABLParser()
def render_to(self, format, obj, user=None, wrap=True):
if isinstance(obj, tuple):
template_name = obj[1]
elif hasattr(obj, '__pabl__'):
template_name = obj.__pabl__
else:
return obj
view = self._load_view(template_name)
return self.formatters[format](obj, view.resource_name,
view.visible_fields(user), user, wrap)
def _load_view(self, template_name):
unparsed_pabl = self.template_loader.load_template(template_name)
parsed_pabl = self.parser.parse_pabl(unparsed_pabl).asList()[0]
view = View(parsed_pabl[0])
return view
def to_json(self, obj, resource_name, visible_fields, user, wrap):
json_dict = self._to_json(obj, visible_fields, user)
if wrap:
return {resource_name: json_dict}
return json_dict
def _to_json(self, obj, visible_fields, user):
json_dict = {}
for field in visible_fields:
if isinstance(field, tuple): # we are aliasing this field
field_value = PABL.find_obj(obj, field[0])
field_name = field[1]
else:
field_value = PABL.find_obj(obj, field)
field_name = field
try:
field_value = field_value()
except TypeError: # object is not callable
pass
if isinstance(field_value, list):
pabl_list = []
for item in field_value:
if hasattr(item, '__pabl__'):
i = self.render_to('json', item, user, False)
else:
i = item
pabl_list.append(i)
field_value = pabl_list
if hasattr(field_value, '__pabl__'):
field_value = self.render_to('json', field_value, user, False)
json_dict[field_name] = field_value
return json_dict
@classmethod
def find_obj(cls, obj, dotted):
value = obj
while dotted.find('.') >= 0:
root, _, dotted = dotted.partition('.')
value = getattr(value, root)
return getattr(value, dotted, None)