Skip to content

Instantly share code, notes, and snippets.

@sevennineteen
Created December 28, 2012 18:16
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save sevennineteen/4400462 to your computer and use it in GitHub Desktop.
Save sevennineteen/4400462 to your computer and use it in GitHub Desktop.
Example using Jinja2 to populate a JSON payload template
{ "path": "/content/geometrixx/my-first-jinja-page",
"properties": [
{ "name": "jcr:primaryType",
"value": "cq:Page" }],
"nodes": [
{ "path": "jcr:content",
"properties": [
{ "name": "jcr:primaryType",
"value": "cq:PageContent"},
{ "name": "sling:resourceType",
"value": "geometrixx/components/widepage"},
{ "name": "jcr:title",
"value": "{{ page.title }}" },
{ "name": "cq:template",
"value": "/apps/geometrixx/templates/widepage"},
{ "name": "cq:tags",
"type": "String[]",
"value": {{ page.tags|jsonify }} },
{ "name": "jcr:description",
"value": "{{ page.description }}" },
{ "name": "sling:vanityPath",
"value": "/connector-examples/json/" }]}
]
}
import json
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('app', 'templates'))
env.filters['jsonify'] = json.dumps
# Template file at ./app/templates/example.json
template = env.get_template('example.json')
page = {
'title': 'Jinja Example Page',
'tags': ['jinja', 'python', 'migration'],
'description': 'This is an example page created using Jinja2 with a JSON template.'
}
print template.render(page=page)
@loveJesus
Copy link

Praise the Lord, blessings, would the above give an error if for example page.title or description have double quotes in them? it might be better to leave them unquoted and pass them through jsonify?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment