#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from html.parser import HTMLParser register = template.Library() def unescape(value): parser = HTMLParser() return parser.unescape(value) register.filter(unescape) def raw(parser, token): # Whatever is between {% raw %} and {% endraw %} will be preserved as # raw, unrendered template code. text = [] parse_until = 'endraw' tag_mapping = { template.base.TOKEN_TEXT: ('', ''), template.base.TOKEN_VAR: ('{{', '}}'), template.base.TOKEN_BLOCK: ('{%', '%}'), template.base.TOKEN_COMMENT: ('{#', '#}'), } # By the time this template tag is called, the template system has already # lexed the template into tokens. Here, we loop over the tokens until # {% endraw %} and parse them to TextNodes. We have to add the start and # end bits (e.g. "{{" for variables) because those have already been # stripped off in a previous part of the template-parsing process. while parser.tokens: token = parser.next_token() if token.token_type == template.base.TOKEN_BLOCK and \ token.contents == parse_until: return template.base.TextNode(u''.join(text)) start, end = tag_mapping[token.token_type] text.append(u'%s%s%s' % (start, token.contents, end)) parser.unclosed_block_tag(parse_until) raw = register.tag(raw)