Is it possible to use AngularJS with the Jinja2 template engine?
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.
There's also another option: flask-triangle is an extension to help you building forms while integrating angular templating in jinja2.
Instead of changing angular(or jinja2) bracket delimiter, you can simply add an identifier to tell jinja2 if the expression has to be rendered as an angular one. Just add |angular
after your variable:
<div>{{variable|angular}}</div>
Which will be rendered in the HTML output as:
<div>{{variable}}</div>
Please note that flask-triangle also comes with other features (for building forms in angular style), however I think it might be a valuable option to make angular templating in jinja2 more readable.