[Solved]-How to manage Javascript modules in django templates?

8👍

Been a while since I posted this problem. What I’ve been doing to solve it is:

  1. write the javascript parts you need as a library which is served statically
  2. call the routines in the static library from the template with your server side values

Restraint is required to write it in such a way that it acts as a client side script only; don’t be tempted to try and inject values from the server at the time of serving the js. Ultimately I’ve found it less confusing to apply server side variables strictly in the html template.

In this way I’m able to:

  1. keep the javascript selectors on html tags inside the same file (ie: the template)
  2. avoid templatetags altogether
  3. re-use each javascript library in different places, and
  4. keep the css/js/html pieces in all the places where they’re expected to be found

It’s not perfect, but it’s getting me by till a neater idea comes along.

For example a js library in “media/js/alertlib.js” might include:

function click_alert(selector, msg){ 
    $(selector).click(function(){ alert(msg) })
}

and the template has:

<script type="text/javascript" src="media/js/alertlib.js"></script>
<script type="text/javascript">
    click_alert('#clickme', {% message %})
</script>

<div id='clickme'>Click Me</div>

2👍

If more than one page uses a given JS file you should consider concatenating all of them together and minifying the result. This reduces net connects which will improve overall page load time. Don’t forget to bump your expire time out to at least a week or two.

1👍

Have a look at Django Sekizai that has been created for just that purpose.

0👍

I think you are going to have a hard time keeping all four pieces together and applying them in a fell swoop – simply because some appear in your <head> tags and others in the <body> tags.

What have done is made sure that jQuery is loaded for all pages on my base.html (as well as my base css file) … then, I have block tags for {% block css %} and {% block js %}. Templates that inherit the base.html file can supply their own javascript and css (and only the stuff that is needed).

I have created some template tags that create ajax functions whose output is based on the object being displayed (for example, including the object_id) — which cuts down on re-coding.

One thing I haven’t tried but am interested in is django-compress.

Leave a comment