alientag

 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. admin: edit related object shortcut by christian 5 years, 7 months ago
  2. A dict template tag by Batiste 5 years, 1 month ago
  3. Unobtrusvie Foldable Admin Interface by whiteinge 5 years, 4 months ago
  4. Add special field lookups to the Admin list_filter display by whiteinge 5 years, 3 months ago
  5. Templatetag for JS merging and compression by msaelices 5 years, 8 months ago

Comments

(Forgotten your password?)