Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding ambiguous mustaches from Jinja2 that includes jQuery templates

I'm trying to insert jQuery templates into Jinja2 templates. Alas they both (in the default setup) use the mustaches {{ & }} to indicate expressions and literals, respectively.

I'm inserting my jQuery templates into HTML with script tags, like this:

<script type='text/x-jquery-template'>     <div>The people are:          {{ each people }}            ${$value}          {{ /each }}     </div> </script> 

If the above is in a Jinja template, however, it balks because Jinja tries to interpret each as a literal.

In the circumstances (we've lots of templates already) it isn't practical to change Jinja2's start and end delimiters for variables. Plus it's confusing, decreases interoperability, and requires extra training. It is preferable to avoid this option.

So the two alternative things I've thought of to solve this are:

  1. Jinja2 escaping each '{{' and '}}', which I'm not quite sure how to do best ("{{ "{{" }}`, perhaps, but that's verbose);

  2. More practical - perhaps ideal - would be telling Jinja2 to not parse a block of code, perhaps via a jQuery extension.

I'd be grateful for thoughts and feedback. Thank you for reading.

like image 741
Brian M. Hunt Avatar asked Feb 25 '11 12:02

Brian M. Hunt


1 Answers

You can use the {% raw %}{% endraw %} construct to ease your escaping woes (straight from the Jinja2 docs).

Example:

<script type='text/x-jquery-template'>     <div>The people are:         {% raw %}<!-- Everything in here will be left untouched by Jinja2 -->          {{ each people }}            ${$value}         {{ /each }}          {% endraw %}     </div> </script> 
like image 70
Cameron Avatar answered Sep 21 '22 13:09

Cameron