title: How can I validate the syntax of a django template?
body: <p>I would like client admins to be able to edit the various status emails that their site is sending.  The emails are very simple django templates, stored in the database.  </p>
  
  <p>I would like to verify that they don't have any syntax errors, missing variables, etc., but I can't figure a simple way to do so.</p>
  
  <p>For unknown block tags, it's easy:</p>
  
  <pre><code>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'"
  </code></pre>
  
  <p>I don't know how I would detect an empty variable though? I'm aware of the <code>TEMPLATE_STRING_IF_INVALID</code> setting, but that is a site-wide setting.</p>
  
  <pre><code>def test_missing_value():
      txt = render("""
        a {{ b }} c
      """)
      assert txt == "?"
  </code></pre>
  
  <p>missing closing tags/values don't cause any exceptions either..</p>
  
  <pre><code>def test_missing_close_tag():
      txt = render("""
        a {% b c
      """)
      assert txt == "?"
  
  def test_missing_close_value():
      txt = render("""
        a {{ b c
      """)
      assert txt == "?"
  </code></pre>
  
  <p>Do I have to write a parser from scratch to do basic syntax validation?</p>