Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice including javascript in django template

Previously I used to do like this in a template

<html>
...
<script>
 {% include "myapp/includes/jquery-1.7.1.min.js" %}
{% include "myapp/includes/myscript.js" %}
</script>
...

But this causes all the js code to be shown on the page source.

I am not using any Form in my template, so can I use Media class for adding js?

Should I just use <script src=".." or link ref=".." for adding javascript files? Which is the better way?

like image 269
damon Avatar asked Apr 15 '12 13:04

damon


People also ask

Can I use JavaScript in Django template?

Adding JavaScript to Our Django Template We can add JavaScript to our template using an inline <script> tag or an external JavaScript file. Let's create a app. js file, put it in a js folder that you need to create in the static folder of your application.

How do I organize my Django templates?

There are two main ways to organize your template structure in Django: the default app-level way and a custom project-level approach.

What does include does in Django template?

include tag loads a template and renders it with the current context. This is a way of “including” other templates within a template. The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.


2 Answers

Use <script src="yourscript.js"></script> as usual, without the include template tag.

Django include template tag is not meant to load JavaScript source. It is used to include a sub template whose markup can access the template context of the including template. Read here.

like image 194
Joseph Victor Zammit Avatar answered Sep 27 '22 22:09

Joseph Victor Zammit


I know this question is 6 years old, and the answer is an exact answer for the question. But somehow this came up for me so high in my google search results, I thought I would post additional info here, to help people like me, looking for best practice. Use template inheritance, and blocks for content, css and javascript.

Docs:

https://docs.djangoproject.com/en/2.0/ref/templates/language/#template-inheritance

and a stackoverflow example, showing how to add another js file to the original js block using block.super:

how to organize JS files in Django?

like image 28
excyberlabber Avatar answered Oct 01 '22 22:10

excyberlabber