Ticket #2800: enhanced-ifchanged.patch

File enhanced-ifchanged.patch, 2.5 KB (added by anonymous, 18 years ago)
  • django/template/defaulttags.py

     
    120120        return nodelist.render(context)
    121121
    122122class IfChangedNode(Node):
    123     def __init__(self, nodelist):
     123    def __init__(self, nodelist, var1=None):
    124124        self.nodelist = nodelist
    125125        self._last_seen = None
     126        self._var1 = var1
    126127
    127128    def render(self, context):
    128         content = self.nodelist.render(context)
    129         if content != self._last_seen:
     129        try:
     130            if self._var1==None:
     131                compare_to = self.nodelist.render(context)
     132            else:
     133                compare_to = resolve_variable(self._var1, context)
     134        except VariableDoesNotExist:
     135            compare_to = None       
     136        if  compare_to != self._last_seen:
    130137            firstloop = (self._last_seen == None)
    131             self._last_seen = content
     138            self._last_seen = compare_to
    132139            context.push()
    133140            context['ifchanged'] = {'firstloop': firstloop}
    134141            content = self.nodelist.render(context)
     
    626633    """
    627634    Check if a value has changed from the last iteration of a loop.
    628635
    629     The 'ifchanged' block tag is used within a loop. It checks its own rendered
    630     contents against its previous state and only displays its content if the
    631     value has changed::
     636    The 'ifchanged' block tag is used within a loop. It has two possible uses.
     637    1) It checks its own rendered contents against its previous state and
     638    only displays its content if the value has changed.
     639    2) It checks if the given variable has changed. ::
    632640
    633641        <h1>Archive for {{ year }}</h1>
    634642
    635643        {% for date in days %}
    636644        {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
     645        {% ifchanged date %}date has changed{% endifchanged %}
    637646        <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
    638647        {% endfor %}
    639648    """
    640649    bits = token.contents.split()
    641     if len(bits) != 1:
    642         raise TemplateSyntaxError, "'ifchanged' tag takes no arguments"
     650    if len(bits) > 2:
     651        raise TemplateSyntaxError, "'ifchanged' tag takes either one or none argument"
     652    if len(bits) == 1:
     653        bits.append(None)
    643654    nodelist = parser.parse(('endifchanged',))
    644655    parser.delete_first_token()
    645     return IfChangedNode(nodelist)
     656    return IfChangedNode(nodelist, bits[1])
    646657ifchanged = register.tag(ifchanged)
    647658
    648659#@register.tag
Back to Top