AngularJS with Django - Conflicting template tags

2018-12-31 19:47发布

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?

13条回答
情到深处是孤独
2楼-- · 2018-12-31 19:55

For AngularJS v1.3.3 you should define your own template tags like this

AngularJS module

angular.module('myapp', []).config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('{$');
    $interpolateProvider.endSymbol('$}');
});

Webpage

<a>{$ variable $}</a> 
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 19:59

you can maybe try verbatim Django template tag and use it like this :

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

{% verbatim %}
<div ng-app="">
    <p>10 is {{ 5 + 5 }}</p>
</div>
{% endverbatim %}

查看更多
余欢
4楼-- · 2018-12-31 20:01

We created a very simple filter in Django 'ng' that makes it easy to mix the two:

foo.html:

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

The ng filter looks like this:

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)
查看更多
唯独是你
5楼-- · 2018-12-31 20:03

You can tell Django to output {{ and }}, as well as other reserved template strings by using the {% templatetag %} tag.

For instance, using {% templatetag openvariable %} would output {{.

查看更多
不再属于我。
6楼-- · 2018-12-31 20:07

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.

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:

angular.module('YourAppName', [], function ($interpolateProvider) {
    $interpolateProvider.startSymbol('<[');
    $interpolateProvider.endSymbol(']>');
}); 

API docs.

查看更多
零度萤火
7楼-- · 2018-12-31 20:07

You could always use ng-bind instead of {{ }} http://docs.angularjs.org/api/ng/directive/ngBind

<span ng-bind="name"></span>
查看更多
登录 后发表回答