如何验证Django模板的语法?

2024-04-26 10:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想客户端管理员能够编辑他们的网站正在发送的各种状态电子邮件。电子邮件是非常简单的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设置,但这是整个站点的设置。在

^{pr2}$

缺少结束标记/值也不会导致任何异常。。在

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

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

我是否必须从头开始编写解析器来进行基本语法验证?在


Tags: todjango标记testtxt电子邮件defas
1条回答
网友
1楼 · 发布于 2024-04-26 10:29:05

I don't know how I would detect an empty variable though?

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)

missing closing tags/values don't cause any exceptions either..

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

相关问题 更多 >