#!/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)
Comments