Burke Software Blog


Django Static files in Angular

December 27, 2014 by Burke Software

angular static example

Problem

If you use staticfiles in django your files you could anywhere. Maybe S3 or maybe you're distributing a third party app and static files are wherever the user configures them to be. 

Solution

We'll create a javascript function to work very much like the django static template tag in staticfiles. First let's get our static and media urls. Place these variables in your django template where you run angular from.


<script>

    var STATIC_URL = '{{ STATIC_URL|escapejs }}';

    var MEDIA_URL  = '{{ MEDIA_URL|escapejs }}';

    function static(path) {

        return STATIC_URL + path;

    }

    function static_media(path) {

        return MEDIA_URL + path;

    }

</script>


We could just append STATIC_URL but the function will let us change things easily if needed in one location. Use it like


templateUrl: static('partials/home.html')

or bind it to scope to use like this

Controller:


$scope.static = static;


Partial:


<div ng-include="static('report_builder/partials/fields.html')"></div>


Or if it's an image or other static resource not processed by javascript or angular:

<md-icon icon="{{ static('report_builder/img/add.svg') }}"></md-icon>