Move all Javascript to a separate file in Django
I am starting with Django and am doing some stuff. I want the html files to be clean, no blocks <script>
. Is it possible even if my js part is using blocks {% url %}
?
Example:
page.html
<div>
<h1> My home url is: </h1>
<div id="js-tag" ></div>
</div>
<script>
$(function(){
$('#js-tag').html("{% url 'home' %}")
});
</script>
I want to remove this and put it in a separate js file and just import it into page.html
+3
source to share
2 answers
You might want to use django-js-reverse to use named URL patterns in js files. You can also use the staticfiles app to manage your static assets in Django.
This will allow you to include your js files like this:
{% load static %} {# Only load static once at the top of your file #}
<script src="{% static 'path/to/js/in/staticfiles.js' %}"></script>
And in the js file, you can use:
$('#js-tag').html(Urls.home());
+1
source to share