How to validate Jinja syntax without variable interpolation

Jeff Ferland picture Jeff Ferland · Jun 21, 2016 · Viewed 10.3k times · Source

I have had no success in locating a good precommit hook I can use to validate that a Jinja2 formatted file is well-formed without attempting to substitute variables. The goal is something that will return a shell code of zero if the file is well-formed without regard to whether variable are available, 1 otherwise.

Answer

Vasili Syrakis picture Vasili Syrakis · Jun 21, 2016

You can do this within Jinja itself, you'd just need to write a script to read and parse the template.

Since you only care about well-formed templates, and not whether or not the variables are available, it should be fairly easy to do:

#!/usr/bin/env python
# filename: check_my_jinja.py
import sys
from jinja2 import Environment

env = Environment()
with open(sys.argv[1]) as template:
    env.parse(template.read())

or something that iterates over all templates

#!/usr/bin/env python
# filename: check_my_jinja_recursive.py
import sys
import os
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('./mytemplates'))
templates = [x for x in env.list_templates() if x.endswith('.jinja2')]
for template in templates:
    t = env.get_template(template)
    env.parse(t)

If you have incorrect syntax, you will get a TemplateSyntaxError

So your precommit hook might look like

python check_my_jinja.py template.jinja2
python check_my_jinja_recursive.py /dir/templates_folder