I'm beginning with Django and doing some stuff. I want to keep html files clean, without <script>
blocks. Is it possible, even if my js part is using {% url %}
blocks?
Example:
page.html
<div>
<h1> My home url is: </h1>
<div id="js-tag" ></div>
</div>
<script>
$(function(){
$('#js-tag').html("{% url 'home' %}")
});
</script>
What I want to is remove this and place it on a separate js file and just import it to page.html
(Almost) everything is possible with Django! ;)
You just have to put your JavaScript code in a separate HTML file and then you simply include it in your main template (here: page.html
) like this:
{% include 'path/to/my/template_file/js_code.html' %}
You might want to use django-js-reverse to be able to used named URL patterns in js files. You may also use the staticfiles app to manage your static assets within Django.
That will allow you to include your js files this way:
{% 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());
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