Correctly accessing django static files from external javascript

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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *