JavaScript with Django templatetags
May 2nd, 2007 by viestards
There are lots of tutorials in web concerning integrating AJAX into Django. But they look somehow out of place- you have to insert JavaScript test from view and it’s against DRY. So, I decided to implement JavaScript through templatetags.
First, you need to create templatetag (if you know nothing of templatetags, look at Django template documentation for Python developers.
For my example I will be using Prototype and Script.alo.us JavaScript frameworks
So first things first- let’s create templatetag:
def do_visual_effect(parser, token):
"adds various JS visual effects to chosen element"
effect = token.split_contents()
wigdet="new Effect."+effect[1]+'("'+ effect[2] +'")'
return VisualEffectNode(wigdet)
As you can see, visual effect function is very simple and now works only with two arguments- EffectName and div id , but we will fix that later.
Template Node class is the same as in Django documentation, so I will not get any deeper:
class VisualEffectNode(template.Node):
def __init__(self, widget_code):
print widget_code
self.widget_code= widget_code
def render(self, context):
return self.widget_code
Only thing left is to register it as templatetag, so at the bottom of file write down:
register.tag('visual_effect', do_visual_effect)
Now for the template part: I saved file as helpers.py, so I’m gonna insert
{% load helpers %}
at the top of template file.
Now when you need any effect, just call
<div id="my_old_div">
<b>sometext</b>
</div>
<a href=”#” onclick=’{% visual_effect SwitchOff my_old_div %}’>Get out of the way!</a>
This will create link, which remove div with id “my_old_div” when clicked.
But maybe we want to add some more arguments, such as duration? So, lets modify our code a little bit:
def do_visual_effect(parser, token):
"adds various JS visual effects to chosen element"
effect = token.split_contents()
# if addition opntions are ommited, add empty string
if len(effect)==3:
effect.append("")
wigdet="new Effect."+effect[1]+'("'+ effect[2] +'",{'+ effect[3] + '})'
return VisualEffectNode(wigdet)
I just appended dictionary-like structure where additional arguments can be inserted.
In template add something like this
<a href="#" onclick='{% visual_effect Highlight model2 duration:1 %}'>Highlight model1</a>
and we’re set!
That’s it for now, I try later to write something more.