summaryrefslogtreecommitdiff
path: root/chimere/templatetags/unescape.py
blob: 45ce0d5cbcf3aced7564346d0129337a2f7c2856 (plain)
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
#!/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)