Login

Template tag "ifregex" and "ifnotregex"

Author:
arthurfurlan
Posted:
May 26, 2009
Language:
Python
Version:
1.0
Score:
6 (after 6 ratings)

Outputs the contents of the block if the second argument matches (or not, depending on the tag) the regular expression represented by the first argument.

Usage:

{% ifregex "^/comments/" request.path %}
    ...
{% endifregex %}

{% ifnotregex "^/comments/" request.path %}
    ...
{% else %}
    ...
{% endifnotregex %}
 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# On Debian systems, you can find the full text of the license in
# /usr/share/common-licenses/GPL-2
#
#
# Based on the django's default templatetags ifequal and ifnotequal.

from django.template import Node, NodeList, Template, Context, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template import Library
import re

register = Library()

class IfRegexNode(Node):
        def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
                self.var1, self.var2 = Variable(var1), Variable(var2)
                self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
                self.negate = negate

        def __repr__(self):
                return "<IfRegexNode>"

        def render(self, context):
                try:
                        val1 = self.var1.resolve(context)
                except VariableDoesNotExist:
                        val1 = None
                try:
                        val2 = self.var2.resolve(context)
                except VariableDoesNotExist:
                        val2 = None
                if (self.negate and not re.match(val1, val2)) or (not self.negate and re.match(val1, val2)):
                        return self.nodelist_true.render(context)
                return self.nodelist_false.render(context)

def do_ifregex(parser, token, negate):
        bits = list(token.split_contents())
        if len(bits) != 3:
                raise TemplateSyntaxError, "%r takes two arguments" % bits[0]
        end_tag = 'end' + bits[0]
        nodelist_true = parser.parse(('else', end_tag))
        token = parser.next_token()
        if token.contents == 'else':
                nodelist_false = parser.parse((end_tag,))
                parser.delete_first_token()
        else:
                nodelist_false = NodeList()
        return IfRegexNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)

@register.tag
def ifregex(parser, token):
        """
        Outputs the contents of the block if the second argument matches the regular
        expression represented by the first argument.

        Examples::

                {% ifregex "^/comments/" request.path %}
                        ...
                {% endifregex %}

                {% ifnotregex "^/comments/" request.path %}
                        ...
                {% else %}
                        ...
                {% endifnotregex %}
        """
        return do_ifregex(parser, token, False)

@register.tag
def ifnotregex(parser, token):
        """
        Outputs the contents of the block if the second argument doesn't match the
        regular expression represented by the first argument.
        """
        return do_ifregex(parser, token, True)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.