Last active
April 3, 2019 16:48
-
-
Save jeffbrl/cc04fcac2affe46c4934e5109fad88a9 to your computer and use it in GitHub Desktop.
Jinja2 rendering examples in python
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
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)) |
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
The VPC name is {{ vpc.name }}. | |
The VPC ID is {{ vpc.id }}. |
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: 'dev-east' | |
id: 'vpc-998774' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment