Ticket #919: random_tag.patch
File random_tag.patch, 2.1 KB (added by , 19 years ago) |
---|
-
core/template/defaulttags.py
178 178 return self.nodelist_true.render(context) 179 179 return self.nodelist_false.render(context) 180 180 181 class RandomNode(Node): 182 def __init__(self, nodelist_options): 183 self.nodelist_options = nodelist_options 184 185 def render(self, context): 186 from random import choice 187 return choice(self.nodelist_options).render(context) 188 181 189 class RegroupNode(Node): 182 190 def __init__(self, target_var, expression, var_name): 183 191 self.target_var, self.expression = target_var, expression … … 588 596 parser.delete_first_token() 589 597 return IfChangedNode(nodelist) 590 598 599 def do_random(parser, token): 600 """ 601 Output the contents of a random block. 602 603 The `random` block tag must contain one or more `or` tags, which separate 604 possible choices; a choice in this context is everything between a 605 `random` and `or` tag, between two `or` tags, or between an `or` and an 606 `endrandom` tag. 607 608 Sample usage:: 609 610 {% random %} 611 You will see me half the time. 612 {% or %} 613 You will see <em>me</em> the other half. 614 {% endrandom %} 615 """ 616 options = NodeList() 617 while True: 618 option = parser.parse(('or', 'endrandom')) 619 token = parser.next_token() 620 options.append(option) 621 if token.contents == 'or': 622 continue 623 parser.delete_first_token() 624 break 625 if len(options) < 2: 626 raise TemplateSyntaxError, "random must have at least two possibilities" 627 return RandomNode(options) 628 591 629 def do_ssi(parser, token): 592 630 """ 593 631 Output the contents of a given file into the page. … … 770 808 register_tag('if', do_if) 771 809 register_tag('ifchanged', do_ifchanged) 772 810 register_tag('regroup', do_regroup) 811 register_tag('random', do_random) 773 812 register_tag('ssi', do_ssi) 774 813 register_tag('load', do_load) 775 814 register_tag('now', do_now)