Skip to content

Instantly share code, notes, and snippets.

@timsavage
Created March 14, 2016 16:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsavage/6554b93c2129216e6c66 to your computer and use it in GitHub Desktop.
Save timsavage/6554b93c2129216e6c66 to your computer and use it in GitHub Desktop.
Code Generation with Jinja
from jinja2 import Template, Environment
# The environment is used to configure the template engine
# See: http://jinja.pocoo.org/docs/dev/api/#jinja2.Environment
env = Environment(autoescape=False, optimized=False)
# Open your template and compile into a template object.
with open("template.txt", "r") as f:
template = env.from_string(f.read())
# Render the template
with open("/path/to/output-file.txt", "w") as f:
# Stream renders the template to a stream for writing to a file.
# Pass your variables as kwargs
template.stream(
Host="localhost",
IP="127.0.0.1",
BT=[12, 12, 32]
).dump(f)
Host: {{ Host }}
IP: {{ IP }}
{% for entry in BT %}
BT_{{ loop.index }}: {{ entry }}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment