if(not)equal with filtering

 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
#coding=utf-8
from django import template
from django.template.defaulttags import IfEqualNode

register = template.Library()


class IfEqualNode(IfEqualNode):
    def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
        self.var1, self.var2 = var1, var2
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.negate = negate

def do_ifequal(parser, token, negate):
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise template.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 = template.NodeList()
    a = parser.compile_filter(bits[1])
    b = parser.compile_filter(bits[2])
    return IfEqualNode(a, b, nodelist_true, nodelist_false, negate)

@register.tag
def ifequal(parser, token):
    return do_ifequal(parser, token, False)

@register.tag
def ifnotequal(parser, token):
    return do_ifequal(parser, token, True)

Comments

akaihola (on September 2, 2008):

This functionality might one day be part of Django's template language. See the following Django tickets:

  • #5756 (Any template tag that uses Variable instead of parser.compile_filter does not handle filters.)
  • #7295 (quotes, escaping and translation of string literals handled inconsistently in templates)
  • #7806 (django.template refactoring)

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.