Ticket #398: define-tag.diff
File define-tag.diff, 2.7 KB (added by , 19 years ago) |
---|
-
django-trunk/django/core/defaulttags.py
25 25 output.append(pformat(sys.modules)) 26 26 return ''.join(output) 27 27 28 class DefineNode(template.Node): 29 def __init__(self, name, value, body): 30 self.name = name 31 self.value = value 32 self.body = body 33 34 def render(self, context): 35 value = self.value.render(context) 36 context.push() 37 context[self.name] = value 38 rendering = self.body.render(context) 39 context.pop() 40 return rendering 41 28 42 class FilterNode(template.Node): 29 43 def __init__(self, filters, nodelist): 30 44 self.filters, self.nodelist = filters, nodelist … … 359 373 "Print a whole load of debugging information, including the context and imported modules" 360 374 return DebugNode() 361 375 376 def do_define(parser, token, parse_until): 377 """Sets variable until the end of the template or enclosing scope. 378 379 Usage:: 380 381 {% define VAR as %} 382 VALUE 383 {% in %} 384 BODY ... 385 386 Example:: 387 388 {% define title_var as%} 389 {% block title %}The default title{% endblock %} 390 {% in %} 391 <html> 392 <head> 393 <title>{{title_var}}</title> 394 </head> 395 <body> 396 <h1>{{title_var}}</h1> 397 ... 398 399 In this example, block title is evaluated once and the result is 400 assigned to the variable title_var, which is used twice. 401 402 If the definition is enclosed by a for-, if- or else-block, it lasts 403 ONLY to the END of the enclosing block. 404 """ 405 bits = token.contents.split() 406 if len(bits) != 3: 407 raise template.TemplateSyntaxError, "'define' statements should have three words" 408 if bits[2] != 'as': 409 raise template.TemplateSyntaxError, "third word of 'define' statement should be '%s'" % bits[2] 410 name = bits[1] 411 # parse the value 412 value = parser.parse(('in',)) 413 parser.delete_first_token() 414 # parse up to the end of the enclosing block 415 body = parser.parse(parse_until) 416 return DefineNode(name, value, body) 417 418 419 420 421 362 422 def do_filter(parser, token): 363 423 """ 364 424 Filter the contents of the blog through variable filters. … … 733 793 template.register_tag('comment', do_comment) 734 794 template.register_tag('cycle', do_cycle) 735 795 template.register_tag('debug', do_debug) 796 template.register_tag('define', do_define) 736 797 template.register_tag('filter', do_filter) 737 798 template.register_tag('firstof', do_firstof) 738 799 template.register_tag('for', do_for)