2014-09-12 37 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) 

失踪关闭标签/值不会引起任何异常要么..

你可以简单地检查没有{%}}等留在呈现的字符串中。