Let's say I have some Jinja2 template with several blocks in it:
{% block A %}Blah{% endblock %}
{% block B %}whatever{% endblock %}
{% block C %}you get the idea{% endblock %}
I want a Python function that will turn it into a dict (or JSON, or whatever), with one entry for each block. So the output would be something like this:
{'A': 'Blah', 'B': 'whatever', 'C': 'you get the idea'}
Is there an established way of doing this?
I'm asking because I want to have my application update pages via AJAX rather than reloads while retaining backwards compatibility. If I can parse the blocks of my Jinja2 templates, then I can use the exact same template files to easily generate whole pages or partial pages. So, as an ancillary question... is there a better way of going about this?
You can check out Template.blocks
field. It has dict of block render functions.
The block render function returns generator when it's called with context(i guess) as argument.
I hope the following code snippet would help you.
for key, blockfun in template.blocks.iteritems(): print key, ':', ''.join(blockfun({}))
And the result is:
A : Blah C : you get the idea B : whatever
This seems to work:
from jinja2 import Template
from jinja2.utils import concat
t = """{% block A %}Blah{% endblock %}
{% block B %}whatever {{ a }}{% endblock %}
{% block C %}you get the idea{% endblock %}
"""
template = Template(t)
context = template.new_context({'a': 'AAAAAAAA'})
A = concat(template.blocks['A'](context))
B = concat(template.blocks['B'](context))
C = concat(template.blocks['C'](context))
print A
print B
print C
That gives me each of the three blocks, rendered, in three separate variables.