Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Jinja syntax without variable interpolation

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.

like image 424
Jeff Ferland Avatar asked Jun 21 '16 08:06

Jeff Ferland


People also ask

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.


1 Answers

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
like image 121
Vasili Syrakis Avatar answered Sep 18 '22 11:09

Vasili Syrakis