2

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!

2 Answers 2

4

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] } },
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you mate, this is a very good answer! especially putting the location into a variable and reusing it in the other js file instead of doing all in the template
-1

Let me suggest a different way of approaching the problem. Consider fetching the static file location in the view, then render it to template. If this fits your need, you can simplify your js and sidestep the issue entirely.

from django.templatetags.static import static

url = static('x.jpg')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.