Ticket #919: random_tag.patch

File random_tag.patch, 2.1 KB (added by Tom Tobin <korpios@…>, 19 years ago)

Implements random template tag

  • core/template/defaulttags.py

     
    178178                return self.nodelist_true.render(context)
    179179        return self.nodelist_false.render(context)
    180180
     181class 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
    181189class RegroupNode(Node):
    182190    def __init__(self, target_var, expression, var_name):
    183191        self.target_var, self.expression = target_var, expression
     
    588596    parser.delete_first_token()
    589597    return IfChangedNode(nodelist)
    590598
     599def 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
    591629def do_ssi(parser, token):
    592630    """
    593631    Output the contents of a given file into the page.
     
    770808register_tag('if', do_if)
    771809register_tag('ifchanged', do_ifchanged)
    772810register_tag('regroup', do_regroup)
     811register_tag('random', do_random)
    773812register_tag('ssi', do_ssi)
    774813register_tag('load', do_load)
    775814register_tag('now', do_now)
Back to Top