我想客户端管理员能够编辑他们的网站正在发送的各种状态电子邮件。电子邮件是非常简单的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_close_tag():
txt = render("""
a {% b c
""")
assert txt == "?"
def test_missing_close_value():
txt = render("""
a {{ b c
""")
assert txt == "?"
我是否必须从头开始编写解析器来进行基本语法验证?在
您可以简单地检查呈现的字符串中没有
{%
,}}
等。在相关问题 更多 >
编程相关推荐