Login

WithTag Tag

Author:
versae
Posted:
June 30, 2008
Language:
Python
Version:
.96
Score:
4 (after 6 ratings)

Set a context variable with the returned value by any templatetag. Useful for example in order to use url templatetag inside blocktrans:

{% withtag url my_app.views.my_view as my_view_url %} {% blocktrans %} Click <a href="{{ my_view_url }}">here</a> {% endblocktrans %} {% endwithtab %}

Or with include templatetag: {% withtag include "js_template.js" as js_template %} {{ js_template }} {% endwithtab %}

It works properly with your own custom templatetags.

 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding: utf-8 -*-
from django.template import Library, Node, TemplateSyntaxError, Token, TOKEN_BLOCK

register = Library()

class WithTagNode(Node):
    """Set a context variable with the returned value by any templatetag.

    For example::
        {% withtag url projects.views.profile user.username as user_profile_url %}
        ...
        {{ user_profile_url }}
        ...
        {% endwithtag %}

    """
    def __init__(self, tag, var_name, parser, token, nodelist):
        self.tag = tag
        self.var_name = var_name
        self.parser = parser
        self.token = token
        self.nodelist = nodelist

    def __repr__(self):
        return "<WithTagNode>"

    def render(self, context):
        templatetag = self.parser.tags.get(self.tag, None)
        if not templatetag or not callable(templatetag):
            raise TemplateSyntaxError, "Invalid block tag '%r' as argument " \
                                       "for withtag block." % self.tag
        node = templatetag(self.parser, self.token)
        context.push()
        context[self.var_name] = node.render(context)
        output = self.nodelist.render(context)
        context.pop()
        return output

def do_withtag(parser, token):
    bits = token.split_contents()
    bits_length = len(bits)
    nodelist = parser.parse(('endwithtag',))
    parser.delete_first_token()
    if bits_length > 3 and bits[bits_length-2] == 'as':
        new_token = Token(TOKEN_BLOCK, ' '.join(bits[1:bits_length-2]))
        return WithTagNode(bits[1], bits[bits_length-1], parser, new_token, nodelist)
    else:
        raise TemplateSyntaxError, "%r tag requires one \"as\" argument." \
                                   % token.contents.split()[0]

register.tag('withtag', do_withtag)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.