Login

A dict template tag

Author:
Batiste
Posted:
April 21, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

crashrox (on February 4, 2010):

import statement should be:

from django.template import Library, TemplateSyntaxError, Node

#

Please login first before commenting.