Which is the best solution to pass {{ STATIC_URL }} to javascript files?
I'm working with django and python.
Thanks in advance. Regards.
To load JavaScript file, just add the following line of code in index. html file. Run the server by using python manage.py runserver command. After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.
While most of Django core is Python, the admin and gis contrib apps contain JavaScript code. Please follow these coding standards when writing JavaScript code for inclusion in Django.
As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script . The new tag will safely serialize template values and protects against XSS. Django docs excerpt: Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.
Django also provides a mechanism for collecting static files into one place so that they can be served easily. Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT .
Using a global javascript variable with the static url value is more simple :
<script language="javascript">var STATIC_URL = "{{ STATIC_URL|escapejs }}";</script>
<script src="{{ STATIC_URL }}js/myfile.js"></script>
Then, you can simply use the static url by calling STATIC_URL in myfile.js :
html = '<img src="'+STATIC_URL+'/icons/flags/tn.gif">';
django-compressor
lets you do this as well as optimize your site by condensing all of your required JS or CSS into one file and optimizing file size.
UPDATE: By default, compressor will convert relative urls into absolute urls using STATIC_URL
. If you download the development version, it comes with a django template engine parser which lets you use all django template code directly in your CSS files, such as the {% static %}
tag.
https://github.com/jezdez/django_compressor
Enable the TemplateFilter
in settings.py after installing to parse your js or css files via the template engine.
COMPRESS_JS_FILTERS = [
'compressor.filters.template.TemplateFilter',
]
Now any JS within {% compress js %}
blocks will be parsed by the django template language...
{% compress js %}
<script src="/my_script.js" type="text/javascript"></script>
{% endcompress %}
// my_script.js
alert('{{ STATIC_URL|escapejs }}');
You asked for the best way -- I think this is the best. Certainly better than serving dynamic files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With