8👍
Been a while since I posted this problem. What I’ve been doing to solve it is:
- write the javascript parts you need as a library which is served statically
- 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:
- keep the javascript selectors on html tags inside the same file (ie: the template)
- avoid templatetags altogether
- re-use each javascript library in different places, and
- 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.
- Django – model unicode() show foreignkey object attribute
- How to enable history in Django shell in python
- Override signup view django-allauth
- Django Queryset __in with None value in list
- Using django-rest-interface with http put
- Is npm in Node like virtualenv in Django?
- Django generate csv file on view and download
- Does django staticfiles skip the middleware?
- How to fix Error: pg_config executable not found on Elastic Beanstalk permanently
- Django – model unicode() show foreignkey object attribute
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.