Getting a dict of all the blocks in a Jinja2 template

Go To StackoverFlow.com

1

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?

2012-04-05 21:45
by dumbmatter


5

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

2012-04-06 03:06
by Hyungoo Kang


2

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.

2012-04-06 03:10
by dumbmatter
Ads