我現在想通了這個(非常哈克和醜陋)的解決方案。
t = CustomTemplate(source)
t.set_custom_context(Context())
print t.render()
使用如下替換:
from jinja2.environment import Template as JinjaTemplate
from jinja2.runtime import Context as JinjaContext
class CustomContextWrapper(JinjaContext):
def __init__(self, *args, **kwargs):
super(CustomContextWrapper, self).__init__(*args, **kwargs)
self.__custom_context = None
def set_custom_context(self, custom_context):
if not hasattr(custom_context, '__getitem__'):
raise TypeError('custom context object must implement __getitem__()')
self.__custom_context = custom_context
# JinjaContext overrides
def resolve(self, key):
if self.__custom_context:
try:
return self.__custom_context[key]
except KeyError:
pass
return super(CustomContextWrapper, self).resolve(key)
class CustomTemplate(JinjaTemplate):
def set_custom_context(self, custom_context):
self.__custom_context = custom_context
# From jinja2.environment (2.7), modified
def new_context(self, vars=None, shared=False, locals=None,
context_class=CustomContextWrapper):
context = new_context(self.environment, self.name, self.blocks,
vars, shared, self.globals, locals,
context_class=context_class)
context.set_custom_context(self.__custom_context)
return context
# From jinja2.runtime (2.7), modified
def new_context(environment, template_name, blocks, vars=None,
shared=None, globals=None, locals=None,
context_class=CustomContextWrapper):
"""Internal helper to for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or(), **vars)
if locals:
# if the parent is shared a copy should be created because
# we don't want to modify the dict passed
if shared:
parent = dict(parent)
for key, value in iteritems(locals):
if key[:2] == 'l_' and value is not missing:
parent[key[2:]] = value
return context_class(environment, parent, template_name, blocks)
誰能提供更好的解決方案?
'get_customer()'返回一個對象,這就是爲什麼我使用'getattr()'獲得'key'屬性的原因。我上面展示的例子只是爲了讓人們看到我想要做的事情。也許沒有明智地選擇,因爲這個例子與寫'customer.first'而不是'customer_first'相同。實際上,我只是想根據一個關鍵來計算一個值。將它們放入一本字典是不可能的/有效的。 –
人。我想我很困惑,爲什麼你不能將對象傳遞給模板,並訪問它的關鍵。 –