Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generator method in django template?

Tags:

python

django

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.

like image 823
dhana Avatar asked Jan 07 '23 05:01

dhana


1 Answers

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 }}
like image 133
dhana Avatar answered Jan 18 '23 14:01

dhana