2013-08-03 30 views
3

我想使用實現__getitem__接口的自定義對象呈現Jinja2模板。該對象實現了一個懶惰變量查找,因爲不可能從它創建一個字典(可用變量的數量幾乎是無限的,值檢索在查詢的鍵上動態地工作)。Jinja模板中的懶惰變量查找

是否可以使用上下文對象呈現Jinja2模板?

# Invalid code, but I'd like to have such an interface. 
# 

from jinja2 import Template 

class Context(object): 

    def __getitem__(self, name): 
     # Create a value dynamically based on `name` 
     if name.startswith('customer'): 
      key = name[len('customer_'):] 
      return getattr(get_customer(), key) 
     raise KeyError(name) 

t = Template('Dear {{ customer_first }},\n') 
t.render(Context()) 

回答

1

我現在想通了這個(非常哈克和醜陋)的解決方案。

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) 

誰能提供更好的解決方案?

1

它看起來像你有一個函數,get_customer()它返回一個字典,或者是一個對象?

爲什麼不把它傳遞給模板?

from jinja2 import Template 
t = Template('Dear {{ customer.first }},\n') 
t.render(customer=get_customer()) 

IIRC,神社是相當寬容不存在的鑰匙,所以customer.bogus_key應該不會崩潰。

+0

'get_customer()'返回一個對象,這就是爲什麼我使用'getattr()'獲得'key'屬性的原因。我上面展示的例子只是爲了讓人們看到我想要做的事情。也許沒有明智地選擇,因爲這個例子與寫'customer.first'而不是'customer_first'相同。實際上,我只是想根據一個關鍵來計算一個值。將它們放入一本字典是不可能的/有效的。 –

+0

人。我想我很困惑,爲什麼你不能將對象傳遞給模板,並訪問它的關鍵。 –