Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack a list to cycle tag in django

I know, I can do something like

{% cycle "value1" "value2" %}

But what if I have all my input values in a list. Can I do something like?

{% cycle my_input_list %}
like image 227
Senthil Babu Avatar asked Oct 31 '22 07:10

Senthil Babu


1 Answers

The built in django cycle tag does not support passing in variables. You can make your own custom tag though. Something like this should work:

import itertools
from django import template
register = template.Library()


class CycleNode(template.Node):
    def __init__(self, cyclevars):
        self.cyclevars = template.Variable(cyclevars)

    def render(self, context):
        names = self.cyclevars.resolve(context)
        if self not in context.render_context:
            context.render_context[self] = itertools.cycle(names)
        cycle_iter = context.render_context[self]
        return next(cycle_iter)


@register.tag
def cycle_list(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError(
            "%r tag requires an argument" % token.contents.split()[0]
        )
    node = CycleNode(arg)
    return node

And then in the template:

{% cycle_list some_list %}
like image 131
laidibug Avatar answered Nov 10 '22 07:11

laidibug