Search code examples
javascriptpythondjangotemplatesdjango-staticfiles

Django: reference static file from js in static file directory


I'm trying to call a static file from a js file placed in the static files directory of my Django project.
Here it is an example.
From my template I call a js from the static files in the following way:

{% load staticfiles %}
...
<script src="{% static 'js/init.js' %}"></script>
...

No problems till now.
So, I have a static file called init.js that has a function with this line of code:

global: { href: 'css/style.css', containers: '70em', grid: { gutters: ['2.5em', 0] } },

where init.js is a static file and css/style.css is a static file too.
Naturally changing the code in the following way is causing problems to the init.js file that is not able to recognize python/Django code

{% load staticfiles %}
global: { href: "{% static 'css/style.css' %}", containers: '70em', grid: { gutters: ['2.5em', 0] } },

Is there a way to call the static file directly from another static file like this case?
Thanks!


Solution

  • you can save it somewhere in template

    <script type="text/javascript" charset="utf-8">var tem_css_location = {% static 'css/style.css' %}</script>
    

    and now you can call tem_css_location in init.js:

    <script type="text/javascript" charset="utf-8">var tem_css_location = {% static 'css/style.css' %}</script>
    <script src="{% static 'js/init.js' %}"></script>
    

    in init.js will look like this:

    global: { href: tem_css_location, containers: '70em', grid: { gutters: ['2.5em', 0] } },