我现在想出了这个(非常hacky和丑陋的)解决方案。
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)
谁能提供更好的解决方案?