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.
You can use the
jsonmodule, either as a Jinja filter ou directly passing the results ofjson.dumps()to your template.In the template:
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.