简体   繁体   中英

What is the best place to store ng-templates in Angular/Django SPA

I am using Django and AngularJS to build an SPA.

I have lots of ng-templates like this:

<script type="text/ng-template" id="item.html">
 // content
</script>

Now, all of them are in one base.html file and thus the template code has become messy.

I want to put each ng-template in its own html file.

Here are the options I could think of:

1. Templates folder : Logical place would be templates folder. But when I tried to reference templates like templates/ng-templates/item.html, I got 404 Not Found. Because Django doesn't serve templates, it uses those for rendering.

2. Static directory : Django does serve the templates from static directory. But it has two minuses:

  • Server side stuff does not work in a separate html file. I mean, if you want to check whether a user is authenticated, you cannot do this:

    {% if user.is_authenticated() %}

    But if all those templates were stored inside one base.html , it would be easily possible. It is clear why.

  • Problems in production. I wanted to serve all my static files from Amazon S3 and configured my settings to do that, which means that when I do {% static 'css/main.css' %} Django will automatically give me a correct url. However, that {% static %} is not available inside angular code. So, you will have to hardcode the url, like so:

    $routeProvider .when('/search', { templateUrl: 'static/ng-templates/search.html', controller: 'SearchController', })

But, guess what? Django does not serve files from static directories in production, at least in Heroku . And configuring it to do so has been such a pain in the ass.

So, I am back to my original code: saving all ng-templates in one base.html .

My question is:

What is the better way to do this?

It is better to place ng-templates with the static files. If you need to use django tags inside of ng-templates, I suppose that something gone wrong, because you are trying to mix logic.

So, here we are moving to you problems with static directory:

1) The workaround is to compile templates on the server side (in some view) and to get compiled html with ajax. But, again, is is not a good way and it would be better to think about decomposition.

2) If you need to dynamicaly load static files, you need to keep static url somewhere in the javascript. For example, you can use tag in the django template and make global variable (global variables are bad practice, but sometime they can help) like window.static_url= "/static/" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM