Last active
February 1, 2017 10:59
-
-
Save zrks/30d78aa611b8e3b0f8fe21170b468d47 to your computer and use it in GitHub Desktop.
jinja2 Templating Primer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| For full reference check: http://jinja.pocoo.org/docs/2.9/api/ | |
| """ | |
| import logging | |
| import json | |
| import yaml | |
| from jinja2 import Environment, FileSystemLoader, select_autoescape | |
| env = Environment( | |
| loader=FileSystemLoader('./'), | |
| autoescape=select_autoescape(['json']) | |
| ) | |
| template = env.get_template('template.json') | |
| try: | |
| with open('vars.yml') as f: | |
| variables = yaml.load(f) | |
| logging.info('Loaded variables.') | |
| except IOError: | |
| logging.error('cannot open', f) | |
| try: | |
| with open('processed_file.json', 'w') as f: | |
| json_object = json.loads(template.render( | |
| name=variables['name'], | |
| statement=variables['statement'] | |
| ) | |
| ) | |
| json.dump(json_object, f) | |
| logging.info('Wrote to ', f) | |
| except IOError: | |
| logging.error('cannot open', f) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| appdirs==1.4.0 | |
| configparser==3.5.0 | |
| enum34==1.1.6 | |
| flake8==3.2.1 | |
| Jinja2==2.9.5 | |
| MarkupSafe==0.23 | |
| mccabe==0.5.3 | |
| packaging==16.8 | |
| pycodestyle==2.2.0 | |
| pyflakes==1.3.0 | |
| pyparsing==2.1.10 | |
| PyYAML==3.12 | |
| six==1.10.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "name": "{{ name }}", | |
| "statement": "{{ statement if name == 'Aleister Crowley' else 'yo!' | safe }}" | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- | |
| name: Aleister Crowley | |
| statement: I am the Devil! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment