Skip to content

Instantly share code, notes, and snippets.

@lanky
Created October 27, 2016 11:54
Show Gist options
  • Select an option

  • Save lanky/00db47de71f572442e40f09c5ebb3aa7 to your computer and use it in GitHub Desktop.

Select an option

Save lanky/00db47de71f572442e40f09c5ebb3aa7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import print_function, absolute_import, division
import os
import sys
from jinja2 import Environment, Template, FileSystemLoader
from jinja2.exceptions import TemplateSyntaxError
from argparse import ArgumentParser
import traceback
def parseargs(argv):
parser = ArgumentParser()
parser.add_argument("template", help="path to a jinja2 template file")
args = parser.parse_args(argv)
if not os.path.isfile(args.template):
print ("No such file: %s" % args.template)
print("USAGE: %s TEMPLATE" % os.path.basename(__file__))
parser.print_help()
sys.exit(1)
return args
def main(templatepath):
"""create a jinja2 environment and attempt to load the templatepath provided"""
env = Environment(loader=FileSystemLoader(os.path.dirname(templatepath)))
try:
tmpl = env.get_template(os.path.basename(templatepath))
exc_info = sys.exc_info
except TemplateSyntaxError, E:
exclass, ex, tb = sys.exc_info()
lasttb = traceback.extract_tb(tb)[-1]
print ("TemplateSyntaxError: line %d ('%s')" % (lasttb[1], lasttb[-1]))
print ("Error: %s" % ex)
if __name__ == "__main__":
args = parseargs(sys.argv[1:])
main(args.template)
@lanky

lanky commented Oct 27, 2016 •

Copy link
Copy Markdown
Author

"{{ varname" - unclosed print statement - error shows the start of the following line (which is the next character)

[lanky@ultra ansibletests]$ ./testjinjatemplate.py brokentemplate.j2 
TemplateSyntaxError: line 482 ('# Default glance host name or IP (string value)')
Error: unexpected char u'#' at 17711

once that's fixed, try again...
The original 'space in variable name inside print statement' error:

[lanky@ultra ansibletests]$ ./testjinjatemplate.py brokentemplate.j2 
TemplateSyntaxError: line 3070 ('memcached_servers = {{ memcached_ server }}')
Error: expected token 'end of print statement', got 'server'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment