Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move all Javascript to a separate file in Django

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

like image 911
Kayan Almeida Avatar asked Apr 17 '15 13:04

Kayan Almeida


2 Answers

(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' %}
like image 86
Leistungsabfall Avatar answered Nov 19 '22 03:11

Leistungsabfall


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());
like image 24
aumo Avatar answered Nov 19 '22 05:11

aumo