Jinja Templates and JSON with Python

  1. Loading up a Jinja Template and some JSON using Python then outputting that JSON in the template:

k.py

#!/usr/bin/python
import jinja2, yaml, json

templateFilePath = jinja2.FileSystemLoader('./')
jinjaEnv = jinja2.Environment(loader=templateFilePath)
jTemplate = jinjaEnv.get_template("template.j2")

with open('api.json') as f:
    json_out = json.load(f)

print jTemplate.render(json_out=json_out)

template.j2

{{ json_out }}

api.json

{"done":"false","api":"this_api"}

2. Outputting the value of api when done is true

api.json

{"done":"true","api":"this_api"}

template.j2

{% if json_out['done'] == 'true' %}
{{ json_out['api'] }}
{% endif %}

See also:

http://jinja.pocoo.org/docs/dev/templates/#expressions