Skip to content

Instantly share code, notes, and snippets.

@jeffbrl
Last active April 3, 2019 16:48
Show Gist options
  • Save jeffbrl/cc04fcac2affe46c4934e5109fad88a9 to your computer and use it in GitHub Desktop.
Save jeffbrl/cc04fcac2affe46c4934e5109fad88a9 to your computer and use it in GitHub Desktop.
Jinja2 rendering examples in python
from jinja2 import Environment, FileSystemLoader, BaseLoader
import yaml
env = Environment(loader=FileSystemLoader("./"), trim_blocks=True, lstrip_blocks=True)
template = env.get_template("simple_template.j2")
# Example of rendering template using dict
vpc = dict(name='dev-west', id='vpc-3432344' )
print(template.render(vpc=vpc))
print('==============================')
# Example of rendering template using YAML file as input
with open('vpc.yml', "r") as stream:
try:
vpc = yaml.load(stream)
except yaml.YAMLError as exc:
print("===Invalid YAML===")
print(exc)
sys.exit(1)
print(template.render(vpc=vpc))
print('==============================')
# Example of rendering template inline
simple_template = """\
The VPC name is {{ vpc.name }}.
The VPC ID is {{ vpc.id }}.
"""
env = Environment(loader=BaseLoader(), trim_blocks=True, lstrip_blocks=True)
template = env.from_string(simple_template)
vpc = dict(name='dev-south', id='vpc-7368494')
print(template.render(vpc=vpc))
The VPC name is {{ vpc.name }}.
The VPC ID is {{ vpc.id }}.
name: 'dev-east'
id: 'vpc-998774'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment