Quickly render text from the command line using Jinja2 and Django templating

Django LogoBoth Django and Jinja offer awesome string templating libraries. I wondered how difficult it would be to simply script some string templates for use in Bash scripts, and I found that it’s really not so hard at all.

To start, we’ll use Jinja, since I like it a bit better than Django and it seems to be faster and more lightweight. First, ensure that the Jinja2 library is installed on your system. Since I’m on a Debian/Ubuntu derivative, this is as easy as sudo apt-get install python-jinja2. Now, let’s template!

$ python -c "import jinja2 ; print jinja2.Template(\"Hello, World\").render()"
Hello, World

Let’s use a filter to convert the amount of bytes in one megabyte into a more readable value:

$ python -c "import jinja2 ; print jinja.Template(\"{{ bytes|filesizeformat }}\").render(bytes=\"1500000\")"
1.5 MB

Due to an issue in Jinja2 which hasn’t been largely released yet (as of 2012-01-16), the filesizeformat filter has an issue which will cause values to render as 0.0 MB instead of the expected result.

Awesome, now onto the same thing in Django. Make sure that Django is installed and continue:

$ python -c "from django.template import Template,Context ; from django.conf import settings ; settings.configure() ; print Template(\"Hello, World\").render(Context())"
Hello, World

As you can see, Django is a lot more verbose to get the same result. In any case, we’ll move on to formatting file sizes:

$ python -c "from django.template import Template,Context ; from django.conf import settings ; settings.configure() ; print Template(\"{{ bytes|filesizeformat }}\").render(Context({\"bytes\":\"1572864\"}))"
1.5MB

These simple examples should allow you to do some pretty rad stuff with command-line templating in Django and Jinja2.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>