Inside the Head of PyDanny

Hi, I'm Daniel Roy Greenfeld, and welcome to my blog. I write about Python, Django, and much more.

It seems like that for every few weeks I find myself needing to generate something out of a template while working outside a framework. For this task, my preferred solution is Jinja2. I've used Jinja2 to generate HTML, code, and text. If I were brave enough I would even say I've used it to generate XML (While my preferred xml tool is great for parsing, even lxml is not so much fun for XML generation).

I frequently use this snippet of code to render templates. Since I'm tired of digging through my code to find it, I'm placing it here for personal reference.

from jinja2 import FileSystemLoader, Environment

def render_from_template(directory, template_name, **kwargs):
    loader = FileSystemLoader(directory)
    env = Environment(loader=loader)
    template = env.get_template(template_name)
    return template.render(**kwargs)

Sample usage:

>>> from simple_script import render_from_template
>>> data = {
...     "date": "June 12, 2014",
...     "items": ["oranges", "bananas", "steak", "milk"]
... }
>>> render_from_template(".", "shopping_list.html", **data)

I've thought about packaging this up with cookiecutter-pypackage and placing it on PyPI, but I think it might be overkill.

Update 2014/06/12: Fixed cookiecutter link thanks to

Published: 2014-06-12 09:00

Tags: python jinja2


If you read this far, you might want to follow me on twitter or github and subscribe via email below (I'll email you new articles when I publish them).



Content Copyright © 2012-2018 Daniel Greenfeld. Proudly harnessed by Mountain, powered by Flask, and rendered by Frozen Flask, all of which take great advantage of Python.