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 %}
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With