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
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
- What do you mean by "without <script> blocks"? You have to bind your JavaScript files to your HTML files. I don't know how this could be done without <script src="yourjavascript.js"> direction. – cezar Commented Apr 17, 2015 at 14:04
- I edited my question, sorry @cezar. Hope it's clear now... – Kayan Almeida Commented Apr 17, 2015 at 14:16
2 Answers
Reset to default 7(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());