【问题标题】:ng-include angular with django template systemng-include Angular 与 Django 模板系统
【发布时间】:2014-06-12 15:40:07
【问题描述】:

我正在使用带有 Angular 的 Django,

在我的角度范围内,我有:

$scope.templates = [
    { name: 'addSongTemplateAjax', url: "templates/add_song_for_ajax.html"}, 
    { name: '', url: ''}
];
$scope.template = $scope.templates[0];

在我的 html 文件中:

<div class = "add_song_submit_form" ng-include="template.url">
</div>

所以,我想从 javascript 角度加载模板 add_song_for_ajax.html。这是行不通的。 Django 给我一个错误 404。我知道这是逻辑,因为我们试图在 urls.py 中找到 url ...

所以我确信我必须处理我的应用程序的设置和 urls.py 才能对 django 说,是的,客户端可以加载这个文件!但我不知道怎么做。

我要加载的 template.html

<div class="alert alert-info" style = "margin-bottom:10px!important; margin-top:10px;">The song will be added to the playlist selected <strong>//playlist_selected.fields.name//</strong></div>
<form role = "form">
    <div class="form-group">
        <label for = "artist_band">Artist / Band</label>
        <input class="form-control" id="artist_band" placeholder = "Enter artist / band">
    </div>
    <div class="form-group">
        <label for="Title">Title / Song name</label>
        <input type="text" class="form-control" id="title" placeholder="Title / Song name">
    </div>
    <div class="form-group">
        <label for = "url">Url</label>
        <input class="form-control" id="url" placeholder = "Url">
    </div>
        <button type="submit" class="btn btn-default" ng-click = "submit_add_song()">Submit</button>
</form>

有什么想法吗?

【问题讨论】:

    标签: javascript python django angularjs


    【解决方案1】:

    您应该将您的网址用单引号括起来,如 documentation

    $scope.templates = [
        { name: 'addSongTemplateAjax', url: "'templates/add_song_for_ajax.html'"}, 
        { name: '', url: ''}
    ];
    

    【讨论】:

    • 这不是解决问题...不是引号的问题,是路由的问题
    【解决方案2】:

    您需要在 Django 的 url 列表中输入模板。有关示例和简要说明,请参阅 How do I go straight to template, in Django's urls.py? 中的更新答案。根据您在 urls.py 中输入的内容,您可能希望从客户端模板类中的 url 中取出“templates/”。

    【讨论】:

      【解决方案3】:

      这些动态模板纯粹只是 AngularJS 还是它们也需要 Django 的上下文?


      1。仅限角度

      如果这些模板不需要 Django 的上下文或模板标签,那么您可以将它们视为静态文件。并将它们放在您的 STATICFILES 目录中。

      然后,您可以通过向 angular 提供这些模板的完整 url(例如 {% static 'templates/add_song_for_ajax.html' %} 的输出)以 angular 加载它们。

      Angular 的 AJAX 应该能够毫无问题地加载那些静态 HTML 文件。

      此解决方案的缺点是,如果您在 Django 设置中更改 STATIC_URL,您也应该在 JS 中更改它。

      2。 Angular 加 Django

      如果您的动态模板需要 Django 的上下文,那么您应该将这些模板编写为 Django 模板,编写它们各自的视图并配置您的 urls.py

      然后你可以在你的 JS 中使用你配置的 url 来指向那些 Django URL。

      不要忘记 Django 和 AngularJS 的模板标签冲突。见AngularJS with Django - Conflicting template tags

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-21
        • 2020-03-01
        • 1970-01-01
        • 2016-08-24
        • 1970-01-01
        • 2018-06-18
        • 2017-01-12
        • 2016-12-24
        相关资源
        最近更新 更多