summaryrefslogtreecommitdiff
path: root/netzbon/render.py
blob: 8bce6007992c44e3a0f8543c9a6c2b72e6d520e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/python3
# This file is in the public domain.

"""Expand Jinja2 templates based on JSON input.

The tool then reads the template from stdin and writes the expanded
output to stdout.

TODO: proper installation, man page, error handling, --help option.

@author Christian Grothoff

"""

import sys
import json
import jinja2
from jinja2 import BaseLoader


class StdinLoader(BaseLoader):
     def __init__ (self):
         self.path = '-'
     def get_source(self, environment, template):
              source = sys.stdin.read()
              return source, self.path, lambda: false


jsonFile1 = open (sys.argv[1], 'r')
jsonData1 = json.load(jsonFile1)

jinjaEnv = jinja2.Environment(loader=StdinLoader(),
                              lstrip_blocks=True,
                              trim_blocks=True,
                              undefined=jinja2.StrictUndefined,
                              autoescape=False)
tmpl = jinjaEnv.get_template('stdin');

try:
     print(tmpl.render(data = jsonData1))
except jinja2.TemplateSyntaxError as error:
     print("Template syntax error: {error.message} on line {error.lineno}.".format(error=error))
     exit(1)
except jinja2.UndefinedError as error:
     print("Template undefined error: {error.message}.".format(error=error))
     exit(1)
except TypeError as error:
     print("Template type error: {0}.".format(error.args[0]))
     exit(1)