简体   繁体   中英

Django accessing non-static files from static files

I have a javascript static file within which I would like to specify a source url to a non-static json file. The below doesn't seem to work (the root directory here is the root directory of the django project):

source: {url: "users/username1/nonstatic.json"}

It works if I explicitly (and non-ideally) specify an absolute static json url:

source: {url: "static/default_GCMS.json"}

Am wondering what's the correct way of calling a non-static file from a static one (.js in this case).

So you want to call a django view from a static JS file. This is a rather common problem - to solve it you need to mix and match django template logic with static JS.

One easy solution would be to assign the URL of the view you'd like to call to a global JS variable in your django template before including your static JS file and then use that variable. So, your django template would be something like this

<script>
  var g_djangoViewUrl = '{% url "my_django_view_url %}';
  // Notice that g_djangoViewUrl is global (assigned to your window object) so will be visible from other JS files
</script>
<script src='the_js_file_that_will_use_the_url.js'></script>

The above has the problem that you'll need to remember to define the urls that will be needed before including your js files. A more structured and permanent solution would be to create a django-view whose only purpose would be to output a global object that would contain all the urls you are going to use from other JS files. So, you'll have something like this in your template

<script src='{% url "my_url_creating_view" %}'></script>
<script src='the_js_file_that_will_use_the_url.js'></script>

The my_url_creating_view should have a correct content type ( application/javascript ) and should just return a object like this:

var g_URLS = {
    djangoView1: {% url "django_view_1" %},
    djangoView2: {% url "django_view_2" %}
}

etc

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