我想使用AngularJS与Django,但他们都使用{{}}作为他们的模板标签。是否有一种简单的方法来更改其中之一,以使用其他自定义模板标签?


当前回答

我们在Django 'ng'中创建了一个非常简单的过滤器,可以很容易地混合这两者:

foo.html:

...
<div>
  {{ django_context_var }}
  {{ 'angularScopeVar' | ng }}
  {{ 'angularScopeFunction()' | ng }}
</div>
...

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)

其他回答

你可以使用{% templatetag %}标签告诉Django输出{{和}},以及其他保留的模板字符串。

例如,使用{% templatetag openvariable %}将输出{{。

如果你使用django 1.5及更新版本:

  {% verbatim %}
    {{if dying}}Still alive.{{/if}}
  {% endverbatim %}

如果你还在使用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))

在你的文件中使用:

from google.appengine.ext.webapp import template
template.register_template_library('utilities.verbatim_template_tag')

来源: http://bamboobig.blogspot.co.at/2011/09/notebook-using-jquery-templates-in.html

你总是可以使用ng-bind而不是{{}} http://docs.angularjs.org/api/ng/directive/ngBind

<span ng-bind="name"></span>

所以今天我在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);
});

此外,我还指出了即将进行的增强,它将公开startSymbol和endSymbol属性,可以将它们设置为您想要的任何标记。

我会坚持使用一个解决方案,既使用django标签{{}},也使用angularjs{{}},并使用一个逐字section或templatetag。

这只是因为你可以通过$interpolateProvider改变angularjs的工作方式(如上所述)。startSymbol interpolateProvider美元。但是如果你开始使用其他angularjs组件,比如ui-bootstrap,你会发现一些模板已经用标准angularjs标签{{}}构建了。

例如,查看https://github.com/angular-ui/bootstrap/blob/master/template/dialog/message.html。