Login

A dict template tag

Author:
Batiste
Posted:
April 21, 2008
Language:
Python
Version:
.96
Tags:
template javascript dict stack
Score:
4 (after 4 ratings)

When you need to include a specific javascript file/code snippet in your page, it's always better to do it at the bottom of your page to avoid to block the rendering too soon. This tag provide you a nice way to include and launch only what is needed:

Example in an included template that need to display google maps:

{% dict js_file google_api %}
    <script src="http://www.google.com/jsapi?key={{ MAPS_API_KEY }}" type="text/javascript" charset="utf-8"></script>
    <script src="{{MEDIA_URL}}js/map.display.js" type="text/javascript">...</script>
{% enddict %}

{% dict js_code link_map %}
    $('.show-map').click(function() {
        ...
    });
    $('.hide-map').click(function() {
        ...
    });
{% enddict %}

Finaly you just have to add this to the very bottom of your base.html file:

....
</body>

{% for k,v in js_file.items %}
    {{v}}
{% endfor %}

<script type="text/javascript">
/* <![CDATA[ */
{% for k,v in js_code.items %}
    {{v}}
{% endfor %}
/* ]]> */
</script>
</html>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.template import Library, TemplateSyntaxError

@register.tag(name='dict')
def do_dict(parser, token):
    try:
        tag_name, varname, key = token.contents.split(None, 2)
    except ValueError:
        raise TemplateSyntaxError("'dict' node requires a dict and a key name.")
    nodelist = parser.parse(('enddict',))
    parser.delete_first_token()
    return DictNode(nodelist, varname, key)

class DictNode(Node):
    def __init__(self, nodelist, varname, key):
        self.nodelist = nodelist
        self.varname, self.key = varname, key
        
    def render(self, context):
        output = self.nodelist.render(context)
        # get the top level context
        dict = context.dicts[len(context.dicts)-1]
        if self.varname in dict:
            dict[self.varname][self.key] = output
        else:
            dict[self.varname] = {self.key:output}
        return ''

More like this

  1. YUI Loader as Django middleware by akaihola 6 years, 11 months ago
  2. Unobtrusvie Foldable Admin Interface by whiteinge 7 years, 2 months ago
  3. Integrate Wymeditor with filebrowser plugin by jonasvp 6 years, 4 months ago
  4. AddThis Social Networking TemplateTag by yeago 6 years, 2 months ago
  5. Template tags to integrate with modconcat by matthanger 5 years, 8 months ago

Comments

crashrox (on February 4, 2010):

import statement should be:

from django.template import Library, TemplateSyntaxError, Node

#

Please login first before commenting.