Login

alientag

Author:
itchyfingrs
Posted:
October 10, 2011
Language:
Python
Version:
1.3
Tags:
templatetag
Score:
1 (after 1 ratings)

Renders enclosing contents as it is. Useful to avoid tags conflict with certain javascript libraries (eg. jquery-tmpl.js, mustache.js)

Example usage: <script class="content-tmpl" type="text/x-jquery-tmpl"> {% alien %} {{ tmpl(results) "#results .item-tmpl" }} {% endalien %} </script>

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.template.base import Node
from django.template.base import TemplateSyntaxError, TOKEN_VAR, TOKEN_BLOCK, \
        TOKEN_COMMENT, VARIABLE_TAG_START, VARIABLE_TAG_END, BLOCK_TAG_START, \
        BLOCK_TAG_END, COMMENT_TAG_START, COMMENT_TAG_END
from django import template


register = template.Library()


class AlienNode(Node):
    def __init__(self, tokens):
        self.tokens = tokens

    def render(self, context):
        contents = []
        for token in self.tokens:
            tagpair = ()
            if token.token_type == TOKEN_VAR:
                tagpair = (VARIABLE_TAG_START, VARIABLE_TAG_END)
            elif token.token_type == TOKEN_BLOCK:
                tagpair = (BLOCK_TAG_START, BLOCK_TAG_END)
            elif token.token_type == TOKEN_COMMENT:
                tagpair = (COMMENT_TAG_START, COMMENT_TAG_END)
            if tagpair:
                contents.append("%s%s%s" % (
                    tagpair[0], token.contents, tagpair[1]))
            else:
                contents.append(token.contents)
        return "".join([c for c in contents])


def alien(parser, token):
    bits = token.contents.split()
    if len(bits) != 1:
        raise TemplateSyntaxError("'alien' statement takes no arguments")

    tokens = []
    endtag = 'endalien'
    while parser.tokens:
        token = parser.next_token()
        if token.token_type == TOKEN_BLOCK and token.contents == endtag:
            return AlienNode(tokens)
        else:
            tokens.append(token)
    parser.unclosed_block_tag([endtag])

templatetag = register.tag(alien)

More like this

  1. Add special field lookups to the Admin list_filter display by whiteinge 7 years, 1 month ago
  2. Add extra form elements in your contib admin by sergejdergatsjev 6 years, 4 months ago
  3. Unobtrusvie Foldable Admin Interface by whiteinge 7 years, 2 months ago
  4. Analogue template filter to removetags that also removes the content of the tag by piquadrat 4 years, 4 months ago
  5. YUI Loader as Django middleware by akaihola 6 years, 11 months ago

Comments

Please login first before commenting.