是否可以将 AngularJS 与 Jinja2 模板引擎一起使用? [英] Is it possible to use AngularJS with the Jinja2 template engine?
问题描述
我有一个 Flask 站点,我想使用 AngularJS JavaScript 框架.不幸的是,似乎分隔符重叠.
I have a Flask site and I want to use the AngularJS JavaScript framework. Unfortunately, it seems as if the delimiters overlap.
如果 Angular 和 Jinja2 都依赖双花括号 ({{ expr }}
),我该如何使用?甚至有可能吗?
How do I use Angular with Jinja2 if both rely on double curly braces ({{ expr }}
)? Is it even possible?
推荐答案
您有一些选择.
1) 更改 Angular 的分隔符符号:
1) Change the delimiter notation for Angular:
var app = angular.module('Application', []);
app.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{a');
$interpolateProvider.endSymbol('a}');
}]);
为开始和结束符号选择的任何内容都将用作新的分隔符.在这种情况下,您将使用 {a some_variable a}
向 Angular 表达一个变量.
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) 更改 Jinja2 的分隔符符号.
2) Change the delimiter notation for Jinja2.
覆盖或子类化 Flask.jinja_options.update
在您绑定到应用程序的 Flask
对象上(相关变量:block_start_string
、block_end_string
、variable_start_string
、variable_end_string
、comment_start_string
、comment_end_string
):
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
由于从服务器端未扩展敏感数据的风险更高,我建议在您不是唯一开发人员的任何项目中更改前端(即 Angular)的语法.
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) 输出一个raw block 在 Jinja2 中使用 {% raw %}
或 {% verbatim %}
:
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) 使用 Jinja2 在模板中写花括号:
4) Use Jinja2 to write the curly braces in the template:
{{ '{{ some_var }}' }}
这将在 HTML 中输出为 {{ some_var }}
.
this will be output as {{ some_var }}
in the HTML.
我对方法 #1 的偏好是显而易见的,但以上任何一种都可以.
My preference for approach #1 is apparent, but any of the above will work.
这篇关于是否可以将 AngularJS 与 Jinja2 模板引擎一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!