Javascript AngularJS 与 Django - 冲突的模板标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8302928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS with Django - Conflicting template tags
提问by Endophage
I want to use AngularJS with Django however they both use {{ }}
as their template tags. Is there an easy way to change one of the two to use some other custom templating tag?
我想在 Django 中使用 AngularJS,但是它们都{{ }}
用作模板标签。是否有一种简单的方法可以更改两者之一以使用其他一些自定义模板标签?
采纳答案by Igor Minar
For Angular 1.0 you should use the $interpolateProvider apis to configure the interpolation symbols: http://docs.angularjs.org/api/ng.$interpolateProvider.
对于 Angular 1.0,您应该使用 $interpolateProvider apis 来配置插值符号:http: //docs.angularjs.org/api/ng.$interpolateProvider。
Something like this should do the trick:
像这样的事情应该可以解决问题:
myModule.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
Keep in mind two things:
请记住两件事:
- mixing server-side and client-side templates is rarely a good idea and should be used with caution. The main issues are: maintainability (hard to read) and security (double interpolation could expose a new security vector - e.g. while escaping of serverside and clientside templating by themselves might be secure, their combination might not be).
- if you start using third-party directives (components) that use
{{ }}
in their templates then your configuration will break them. (fix pending)
- 混合服务器端和客户端模板很少是一个好主意,应该谨慎使用。主要问题是:可维护性(难以阅读)和安全性(双插值可能会暴露一个新的安全向量——例如,虽然逃避服务器端和客户端模板本身可能是安全的,但它们的组合可能不安全)。
- 如果您开始使用
{{ }}
在其模板中使用的第三方指令(组件),那么您的配置将破坏它们。(修复待定)
While there is nothing we can do about the first issue, except for warning people, we do need to address the second issue.
虽然我们对第一个问题无能为力,除了警告人们之外,我们确实需要解决第二个问题。
回答by Bessoufi Mounir
回答by thanksnote
If you did separate sections of page properly then you can easily use angularjs tags in "raw" tag scope.
如果您正确地将页面的各个部分分开,那么您可以轻松地在“原始”标签范围内使用 angularjs 标签。
In jinja2
在 jinja2
{% raw %}
// here you can write angularjs template tags.
{% endraw %}
In Django template (above 1.5)
在 Django 模板中(1.5 以上)
{% verbatim %}
// here you can write angularjs template tags.
{% endverbatim %}
回答by Wes Alvaro
We created a verysimple filter in Django 'ng' that makes it easy to mix the two:
我们在 Django 'ng' 中创建了一个非常简单的过滤器,可以很容易地将两者混合:
foo.html:
foo.html:
...
<div>
{{ django_context_var }}
{{ 'angularScopeVar' | ng }}
{{ 'angularScopeFunction()' | ng }}
</div>
...
The ng
filter looks like this:
该ng
过滤器看起来是这样的:
from django import template
from django.utils import safestring
register = template.Library()
@register.filter(name='ng')
def Angularify(value):
return safestring.mark_safe('{{%s}}' % value)
回答by Endophage
So I got some great help in the Angular IRC channel today. It turns out you can change Angular's template tags very easily. The necessary snippets below should be included after your angular include (the given example appears on their mailing listsand would use (())
as the new template tags, substitute for your own):
所以我今天在 Angular IRC 频道中得到了一些很大的帮助。事实证明,您可以非常轻松地更改 Angular 的模板标签。下面的必要片段应该包含在你的 angular include 之后(给定的例子出现在他们的邮件列表中,并将(())
用作新的模板标签,替代你自己的):
angular.markup('(())', function(text, textNode, parentElement){
if (parentElement[0].nodeName.toLowerCase() == 'script') return;
text = text.replace(/\(\(/g,'{{').replace(/\)\)/g, '}}');
textNode.text(text);
return angular.markup('{{}}').call(this, text, textNode, parentElement);
});
angular.attrMarkup('(())', function(value, name, element){
value = value.replace(/\(\(/g,'{{').replace(/\)\)/, '}}');
element[0].setAttribute(name, value);
return angular.attrMarkup('{{}}').call(this, value, name, element);
});
Also, I was pointed to an upcoming enhancement that will expose startSymbol
and endSymbol
properties that can be set to whatever tags you desire.
此外,我还提到了即将推出的增强功能,它将公开startSymbol
和endSymbol
设置为您想要的任何标签的属性。
回答by Lukas Bünger
I vote against using double parentheses (()) as template tag. It may work well as long as no function call is involved but when tried the following
我投票反对使用双括号 (()) 作为模板标签。只要不涉及函数调用,它就可以很好地工作,但是在尝试以下操作时
ng:disabled=(($invalidWidgets.visible()))
with Firefox (10.0.2) on Mac I got a terribly long error instead of the intended logic. <[]> went well for me, at least up until now.
在 Mac 上使用 Firefox (10.0.2) 我得到了一个非常长的错误,而不是预期的逻辑。<[]> 对我来说很顺利,至少到目前为止是这样。
Edit 2012-03-29:Please note that $invalidWidgets is deprecated. However I'd still use another wrapper than double braces. For any angular version higher than 0.10.7 (I guess) you could change the wrapper a lot easier in your app / module definition:
编辑 2012-03-29:请注意 $invalidWidgets 已弃用。但是我仍然会使用另一个包装而不是双大括号。对于任何高于 0.10.7(我猜)的角度版本,您可以在应用程序/模块定义中更轻松地更改包装器:
angular.module('YourAppName', [], function ($interpolateProvider) {
$interpolateProvider.startSymbol('<[');
$interpolateProvider.endSymbol(']>');
});
回答by nu everest
I found the code below helpful. I found the code here: http://djangosnippets.org/snippets/2787/
我发现下面的代码很有帮助。我在这里找到了代码:http: //djangosnippets.org/snippets/2787/
"""
filename: angularjs.py
Usage:
{% ng Some.angular.scope.content %}
e.g.
{% load angularjs %}
<div ng-init="yourName = 'foobar'">
<p>{% ng yourName %}</p>
</div>
"""
from django import template
register = template.Library()
class AngularJS(template.Node):
def __init__(self, bits):
self.ng = bits
def render(self, ctx):
return "{{%s}}" % " ".join(self.ng[1:])
def do_angular(parser, token):
bits = token.split_contents()
return AngularJS(bits)
register.tag('ng', do_angular)
回答by Indomitable
You could always use ng-bind instead of {{ }} http://docs.angularjs.org/api/ng/directive/ngBind
你总是可以使用 ng-bind 而不是 {{ }} http://docs.angularjs.org/api/ng/directive/ngBind
<span ng-bind="name"></span>
回答by cat
If you use django 1.5 and newer use:
如果您使用 django 1.5 及更新版本,请使用:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
If you are stuck with django 1.2 on appengine extend the django syntax with the verbatim template command like this ...
如果您在 appengine 上坚持使用 django 1.2,请使用像这样的逐字模板命令扩展 django 语法...
from django import template
register = template.Library()
class VerbatimNode(template.Node):
def __init__(self, text):
self.text = text
def render(self, context):
return self.text
@register.tag
def verbatim(parser, token):
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == template.TOKEN_VAR:
text.append('{{')
elif token.token_type == template.TOKEN_BLOCK:
text.append('{%')
text.append(token.contents)
if token.token_type == template.TOKEN_VAR:
text.append('}}')
elif token.token_type == template.TOKEN_BLOCK:
text.append('%}')
return VerbatimNode(''.join(text))
In your file use:
在您的文件中使用:
from google.appengine.ext.webapp import template
template.register_template_library('utilities.verbatim_template_tag')
Source: http://bamboobig.blogspot.co.at/2011/09/notebook-using-jquery-templates-in.html
来源:http: //bamboobig.blogspot.co.at/2011/09/notebook-using-jquery-templates-in.html
回答by Thomas Orozco
You can tell Django to output {{
and }}
, as well as other reserved template strings by using the {% templatetag %}
tag.
您可以使用标记告诉 Django 输出{{
and}}
以及其他保留的模板字符串{% templatetag %}
。
For instance, using {% templatetag openvariable %}
would output {{
.
例如,使用{% templatetag openvariable %}
将输出{{
.