I want to use python generators in django template, Is it possible?
For example, I have model and it contains generator object as shown bellow,
class TestMe(models.Model):
@property
def gen(self):
yield 1
yield 2
context['gen'] = gen
then in template,
{{ gen }} # it should be print 1
{{ gen }} # it should be print 2
Without using for loop
I have tried this way but it returns the python generator not 1. Any one have idea about this.
I have used the custom filter,
@register.filter(name='dj_iter')
def dj_iter(gen):
try:
return next(gen)
except StopIteration:
return 'Completed Iteration'
In django template, I used the filter
{{ gen|dj_iter }}
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