2014-09-12 107 views
4

我希望客戶管理員能夠編輯其網站發送的各種狀態電子郵件。電子郵件是非常簡單的django模板,存儲在數據庫中。如何驗證django模板的語法?

我想驗證他們沒有任何語法錯誤,缺少變量等,但我不能想出一個簡單的方法來這樣做。

對於未知的塊標記,很容易:

from django import template 

def render(templ, **args): 
    """Convenience function to render a template with `args` as the context. 
     The rendered template is normalized to 1 space between 'words'. 
    """ 
    try: 
     t = template.Template(templ) 
     out_text = t.render(template.Context(args)) 
     normalized = ' '.join(out_text.split()) 
    except template.TemplateSyntaxError as e: 
     normalized = str(e) 
    return normalized 

def test_unknown_tag(): 
    txt = render(""" 
     a {% b %} c 
    """) 
    assert txt == "Invalid block tag: 'b'" 

我不知道我怎麼會雖然檢測空變量?我知道TEMPLATE_STRING_IF_INVALID設置,但這是一個網站範圍的設置。

def test_missing_value(): 
    txt = render(""" 
     a {{ b }} c 
    """) 
    assert txt == "?" 

失蹤關閉標籤/值不會引起任何異常要麼..

def test_missing_close_tag(): 
    txt = render(""" 
     a {% b c 
    """) 
    assert txt == "?" 

def test_missing_close_value(): 
    txt = render(""" 
     a {{ b c 
    """) 
    assert txt == "?" 

我必須從頭開始寫一個解析器做基本的語法驗證?

回答

1

我不知道如何檢測一個空變量?

class CheckContext(template.Context): 

    allowed_vars = ['foo', 'bar', 'baz'] 

    def __getitem__(self, k): 
     if k in self.allowed_vars: 
      return 'something' 
     else: 
      raise SomeError('bad variable name %s' % k) 

失蹤關閉標籤/值不會引起任何異常要麼..

你可以簡單地檢查沒有{%}}等留在呈現的字符串中。