Jinja2: How to create multidimensional javascript array?


I am using Flask with Jinja2 as templating language.

How do you convert a multidimensional Python structure to a corresponding structure in javascript using Jinja2?

Example (Python/Flask):

pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},
            {key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},]

render_template('jinjatemplate.html', pyStruct=pyStruct)

Example (Jinja2):


I guess what I'm asking is, can it only be done by creating convoluted loop constructs in Jinja2, or am I missing a shortcut somewhere?

If the answer is, yes, one has to use convoluted loops in Jinja2, then it's probably a lot easier to just create the javascript code directly in python and pass this to Jinja2 for inclusion.

But that seems to defeat the purpose of using a template language like Jinja2 somewhat...

I tried (Jinja2):

{{ pyStruct|safe }}

...and this actually works as long as nothing is unicode, and doesn't stray out of Ascii land (which it usually does in my case).

Oh, and if you wonder why pass this kind of structure? I find I often want to pass fairly complicated structures to javascript to be used by menus and other complicated selection interfaces.

7/7/2011 11:38:14 AM

Accepted Answer

You can use the json module, either as a Jinja filter ou directly passing the results of json.dumps() to your template.

pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},
            {key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},]

render_template('jinjatemplate.html', json_struct=json.dumps(pyStruct))

In the template:

var myStruct = ({{ json_struct|e }});

Warning: I'm a bit unsure about the escaping bit (|e filter). You might want to check that the <, >, & characters are properly escaped with unicode escape sequences rather than xml entities.

7/7/2011 12:29:16 PM

Serialize it using json:

from django.utils import simplejson

pyStruct = [{'key1':'value1',
             'key3':[{'subkey1':'subvalue1', 'subkey2':'subvalue2'}]},
             'key3':[{'subkey1':'subvalue1', 'subkey2':'subvalue2'}]}]
print simplejson.dumps(pyStruct)

Flask likely has an equivalent way to json serialize data. This can also be done using loop constructs in jinja2, but is many times slower than using json.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow