Ticket #12199: firstof_as.diff
File firstof_as.diff, 3.3 KB (added by , 15 years ago) |
---|
-
django/template/defaulttags.py
86 86 return filtered 87 87 88 88 class FirstOfNode(Node): 89 def __init__(self, vars ):89 def __init__(self, vars, variable_name=None): 90 90 self.vars = vars 91 self.variable_name = variable_name 91 92 92 93 def render(self, context): 93 94 for var in self.vars: 94 95 value = var.resolve(context, True) 95 96 if value: 96 return smart_unicode(value) 97 if self.variable_name: 98 context[self.variable_name] = value 99 break 100 else: 101 return smart_unicode(value) 97 102 return u'' 98 103 99 104 class ForNode(Node): … … 614 619 615 620 {% filter force_escape %} 616 621 {% firstof var1 var2 var3 "fallback value" %} 617 622 {% endfilter %} 618 623 624 If you need to preserve the result instead of printing it to the output, 625 you may leverage the familiar Python keyword ``as``:: 626 627 {% firstof substitute teacher as teacher_for_today %} 628 629 Consider the following template code, which would prove unreliable if not 630 using the ``as`` syntax:: 631 632 Today the teacher is {% firstof substitute.name teacher.name %}, 633 and drives a {% firstof substitute.car teacher.car %} 634 635 If ``substitute`` doesn't have a car, the second tag would give incorrect 636 information about what ``substitute`` drives. Use the ``as`` syntax when 637 multiple fields should be tested on the single dominant object of a 638 ``{% firstof %}`` usage. 639 619 640 """ 620 641 bits = token.split_contents()[1:] 642 variable_name = None 643 expecting_save_as = bits[-2] == 'as' 644 if expecting_save_as: 645 variable_name = bits.pop(-1) 646 bits = bits[:-1] 621 647 if len(bits) < 1: 622 648 raise TemplateSyntaxError("'firstof' statement requires at least one" 623 649 " argument") 624 return FirstOfNode([parser.compile_filter(bit) for bit in bits] )650 return FirstOfNode([parser.compile_filter(bit) for bit in bits], variable_name) 625 651 firstof = register.tag(firstof) 626 652 627 653 #@register.tag(name="for") -
docs/ref/templates/builtins.txt
209 209 {% firstof var1 var2 var3 "fallback value" %} 210 210 {% endfilter %} 211 211 212 .. versionchanged:: 1.2 213 214 If you need to preserve the result instead of printing it to the output, 215 you may leverage the familiar Python keyword ``as``:: 216 217 {% firstof substitute teacher as teacher_for_today %} 218 219 Consider the following template code, which would prove unreliable if not 220 using the ``as`` syntax:: 221 222 Today the teacher is {% firstof substitute.name teacher.name %}, 223 and drives a {% firstof substitute.car teacher.car %} 224 225 If ``substitute`` doesn't have a car, the second tag would give incorrect 226 information about what ``substitute`` drives. Use the ``as`` syntax when 227 multiple fields should be tested on the single dominant object of a 228 ``{% firstof %}`` usage. 229 212 230 .. templatetag:: for 213 231 214 232 for