Fixed #256 and #334 -- Added {% ifequal %} template tag. Also, {% ifequal %} and {% ifnotequal %} now both accept an optional {% else %} clause. Unit tests included.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@574 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2005-08-29 21:11:41 +00:00
parent bcce1d901f
commit d80ac5ac25
2 changed files with 86 additions and 45 deletions

View File

@ -126,18 +126,21 @@ class IfChangedNode(template.Node):
else: else:
return '' return ''
class IfNotEqualNode(template.Node): class IfEqualNode(template.Node):
def __init__(self, var1, var2, nodelist): def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
self.var1, self.var2, self.nodelist = var1, var2, nodelist self.var1, self.var2 = var1, var2
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.negate = negate
def __repr__(self): def __repr__(self):
return "<IfNotEqualNode>" return "<IfEqualNode>"
def render(self, context): def render(self, context):
if template.resolve_variable(self.var1, context) != template.resolve_variable(self.var2, context): val1 = template.resolve_variable(self.var1, context)
return self.nodelist.render(context) val2 = template.resolve_variable(self.var2, context)
else: if (self.negate and val1 != val2) or (not self.negate and val1 == val2):
return '' return self.nodelist_true.render(context)
return self.nodelist_false.render(context)
class IfNode(template.Node): class IfNode(template.Node):
def __init__(self, boolvars, nodelist_true, nodelist_false): def __init__(self, boolvars, nodelist_true, nodelist_false):
@ -449,22 +452,34 @@ def do_for(parser, token):
parser.delete_first_token() parser.delete_first_token()
return ForNode(loopvar, sequence, reversed, nodelist_loop) return ForNode(loopvar, sequence, reversed, nodelist_loop)
def do_ifnotequal(parser, token): def do_ifequal(parser, token, negate):
""" """
Output the contents of the block if the two arguments do not equal each other. Output the contents of the block if the two arguments equal/don't equal each other.
Example:: Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %} {% ifnotequal user.id comment.user_id %}
... ...
{% else %}
...
{% endifnotequal %} {% endifnotequal %}
""" """
bits = token.contents.split() bits = token.contents.split()
if len(bits) != 3: if len(bits) != 3:
raise template.TemplateSyntaxError, "'ifnotequal' takes two arguments" raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
nodelist = parser.parse(('endifnotequal',)) end_tag = 'end' + bits[0]
parser.delete_first_token() nodelist_true = parser.parse(('else', end_tag))
return IfNotEqualNode(bits[1], bits[2], nodelist) token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse((end_tag,))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
return IfEqualNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)
def do_if(parser, token): def do_if(parser, token):
""" """
@ -736,7 +751,8 @@ template.register_tag('debug', do_debug)
template.register_tag('filter', do_filter) template.register_tag('filter', do_filter)
template.register_tag('firstof', do_firstof) template.register_tag('firstof', do_firstof)
template.register_tag('for', do_for) template.register_tag('for', do_for)
template.register_tag('ifnotequal', do_ifnotequal) template.register_tag('ifequal', lambda parser, token: do_ifequal(parser, token, False))
template.register_tag('ifnotequal', lambda parser, token: do_ifequal(parser, token, True))
template.register_tag('if', do_if) template.register_tag('if', do_if)
template.register_tag('ifchanged', do_ifchanged) template.register_tag('ifchanged', do_ifchanged)
template.register_tag('regroup', do_regroup) template.register_tag('regroup', do_regroup)

View File

@ -4,95 +4,120 @@ from django.core import template, template_loader
class SomeClass: class SomeClass:
def __init__(self): def __init__(self):
self.otherclass = OtherClass() self.otherclass = OtherClass()
def method(self): def method(self):
return "SomeClass.method" return "SomeClass.method"
def method2(self, o): def method2(self, o):
return o return o
class OtherClass: class OtherClass:
def method(self): def method(self):
return "OtherClass.method" return "OtherClass.method"
# SYNTAX -- # SYNTAX --
# 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class) # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
TEMPLATE_TESTS = { TEMPLATE_TESTS = {
### BASIC SYNTAX ########################################################## ### BASIC SYNTAX ##########################################################
# Plain text should go through the template parser untouched # Plain text should go through the template parser untouched
'basic-syntax01': ("something cool", {}, "something cool"), 'basic-syntax01': ("something cool", {}, "something cool"),
# Variables should be replaced with their value in the current context # Variables should be replaced with their value in the current context
'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"), 'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"),
# More than one replacement variable is allowed in a template # More than one replacement variable is allowed in a template
'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"), 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
# Fail silently when a variable is not found in the current context # Fail silently when a variable is not found in the current context
'basic-syntax04': ("as{{ missing }}df", {}, "asdf"), 'basic-syntax04': ("as{{ missing }}df", {}, "asdf"),
# A variable may not contain more than one word # A variable may not contain more than one word
'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError), 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError for empty variable tags # Raise TemplateSyntaxError for empty variable tags
'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError), 'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError),
'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError), 'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError),
# Attribute syntax allows a template to call an object's attribute # Attribute syntax allows a template to call an object's attribute
'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"), 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
# Multiple levels of attribute access are allowed # Multiple levels of attribute access are allowed
'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"), 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
# Fail silently when a variable's attribute isn't found # Fail silently when a variable's attribute isn't found
'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ""), 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ""),
# Raise TemplateSyntaxError when trying to access a variable beginning with an underscore # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError), 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError when trying to access a variable containing an illegal character # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError), 'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError),
'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError), 'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError),
'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError), 'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError),
'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError), 'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError),
'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError), 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
# Attribute syntax allows a template to call a dictionary key's value # Attribute syntax allows a template to call a dictionary key's value
'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"), 'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"),
# Fail silently when a variable's dictionary key isn't found # Fail silently when a variable's dictionary key isn't found
'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ""), 'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ""),
# Fail silently when accessing a non-simple method # Fail silently when accessing a non-simple method
'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ""), 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ""),
# Basic filter usage # Basic filter usage
'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"), 'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
# Chained filters # Chained filters
'basic-syntax22': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"), 'basic-syntax22': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
# Raise TemplateSyntaxError for space between a variable and filter pipe # Raise TemplateSyntaxError for space between a variable and filter pipe
'basic-syntax23': ("{{ var |upper }}", {}, template.TemplateSyntaxError), 'basic-syntax23': ("{{ var |upper }}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError for space after a filter pipe # Raise TemplateSyntaxError for space after a filter pipe
'basic-syntax24': ("{{ var| upper }}", {}, template.TemplateSyntaxError), 'basic-syntax24': ("{{ var| upper }}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError for a nonexistent filter # Raise TemplateSyntaxError for a nonexistent filter
'basic-syntax25': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError), 'basic-syntax25': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError when trying to access a filter containing an illegal character # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
'basic-syntax26': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError), 'basic-syntax26': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError for invalid block tags # Raise TemplateSyntaxError for invalid block tags
'basic-syntax27': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError), 'basic-syntax27': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError),
# Raise TemplateSyntaxError for empty block tags # Raise TemplateSyntaxError for empty block tags
'basic-syntax28': ("{% %}", {}, template.TemplateSyntaxError), 'basic-syntax28': ("{% %}", {}, template.TemplateSyntaxError),
### INHERITANCE TESTS ##################################################### ### IF TAG ################################################################
'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
### COMMENT TAG ###########################################################
'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
### FOR TAG ###############################################################
'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
### IFEQUAL TAG ###########################################################
'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
### IFNOTEQUAL TAG ########################################################
'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
### INHERITANCE ###########################################################
# Standard template with no inheritance # Standard template with no inheritance
'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'), 'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'),
@ -151,7 +176,7 @@ TEMPLATE_TESTS = {
# {% load %} tag (within a child template) # {% load %} tag (within a child template)
'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'), 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
### EXCEPTION TESTS ####################################################### ### EXCEPTIONS ############################################################
# Raise exception for invalid template name # Raise exception for invalid template name
'exception01': ("{% extends 'nonexistent' %}", {}, template.TemplateSyntaxError), 'exception01': ("{% extends 'nonexistent' %}", {}, template.TemplateSyntaxError),
@ -198,12 +223,12 @@ def run_tests(verbosity=0, standalone=False):
print "Template test: %s -- FAILED. Expected %r, got %r" % (name, vals[2], output) print "Template test: %s -- FAILED. Expected %r, got %r" % (name, vals[2], output)
failed_tests.append(name) failed_tests.append(name)
template_loader.load_template_source = old_template_loader template_loader.load_template_source = old_template_loader
if failed_tests and not standalone: if failed_tests and not standalone:
msg = "Template tests %s failed." % failed_tests msg = "Template tests %s failed." % failed_tests
if not verbosity: if not verbosity:
msg += " Re-run tests with -v1 to see actual failures" msg += " Re-run tests with -v1 to see actual failures"
raise Exception, msg raise Exception, msg
if __name__ == "__main__": if __name__ == "__main__":
run_tests(1, True) run_tests(1, True)