Correctly accessing django static files from external javascript

别说谁变了你拦得住时间么 提交于 2021-01-27 15:02:06

问题


I've got a django application using AngularJS with a bunch of JavaScript and template files.

In my django template I can use the {% static %} tag to properly reference those files like so:

<script src="{% static "angular/myapp.app.js" %}"></script>

However, the external files themselves obviously do not get resolved through django's templating framework and so that's not an option. So what people most often do is just hard code the static path there:

$routeProvider.when('/', {
   // this works but is not ideal
   templateUrl: '/static/pages/some-angular-template.html',  
})

I have seen recommendations of loading STATIC_URL into javascript somewhere and using that to construct references. Something like this:

Django template:

var STATIC_URL = {{ STATIC_URL }};
function getStaticUrl(templatePath) {
  return STATIC_URL + templatePath;
}

External JS:

$routeProvider.when('/', {
   templateUrl: getStaticUrl('/pages/some-angular-template.html'),
})

This is a bit better, but still not perfect because it only handles the base path. If you want to use something like ManifestStaticFilesStorage (which I do) then you still don't get the proper resolution of the file.

Is there any good solution to this problem? Options I am considering:

  • Bootstrapping all necessary URLs into JS variables inside the django template
  • Storing the urls in some hidden HTML markup using data tags (again via the django template)
  • Creating an API to get the URLs (this seems bonkers and like it would be terrible performance-wise).

Just wondering if there's a standard practice or library that addresses this issue? I have run into this problem several times and never found a satisfactory solution.


回答1:


My current solution (which works fine if not the most elegant) is just creating a huge global dict of constants in the django template and then referencing them directly in JS.

Django Template:

<script type="text/javascript">
    NG_STATIC_FILES = {
       "HOME": "{% static '/pages/home.html' %}",
       "SOMETHING_ELSE": "{% static '/pages/some-angular-template.html' %}",
    };
</script>

External JS:

$routeProvider.when('/', {
    templateUrl: NG_STATIC_FILES.SOMETHING_ELSE,
})

etc.



来源:https://stackoverflow.com/questions/50566194/correctly-accessing-django-static-files-from-external-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!