Is it possible to use AngularJS with the Jinja2 template engine?

user559633 picture user559633 · May 21, 2015 · Viewed 13.6k times · Source

I have a Flask site and I want to use the AngularJS JavaScript framework. Unfortunately, it seems as if the delimiters overlap.

How do I use Angular with Jinja2 if both rely on double curly braces ({{ expr }})? Is it even possible?

Answer

user559633 picture user559633 · May 21, 2015

You have some options.

1) Change the delimiter notation for Angular:

var app = angular.module('Application', []);

app.config(['$interpolateProvider', function($interpolateProvider) {
  $interpolateProvider.startSymbol('{a');
  $interpolateProvider.endSymbol('a}');
}]);

Whatever is chosen for the start and end symbols will act as the new delimiters. In this case, you would express a variable to Angular using {a some_variable a}.

This approach has the advantage of only needed to be set once and being explicit.

2) Change the delimiter notation for Jinja2.

Override or subclass Flask.jinja_options.update on the Flask object that you bind to your application (relevant vars: block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string):

jinja_options = app.jinja_options.copy()

jinja_options.update(dict(
    block_start_string='<%',
    block_end_string='%>',
    variable_start_string='%%',
    variable_end_string='%%',
    comment_start_string='<#',
    comment_end_string='#>'
))
app.jinja_options = jinja_options

As there's a higher risk of sensitive data coming un-expanded from from the server-side, I suggest instead changing the syntax on the front-end (i.e. Angular) on any project in which you're not the sole developer.

3) Output a raw block in Jinja2 using {% raw %} or {% verbatim %}:

<ul>
{% raw %}
  {% for item in seq %}
      <li>{{ some_var }}</li>
  {% endfor %}
{% endraw %}
</ul>

4) Use Jinja2 to write the curly braces in the template:

{{ '{{ some_var }}' }}

this will be output as {{ some_var }} in the HTML.

My preference for approach #1 is apparent, but any of the above will work.