2

How do you simply loop x times within a template (Django)?

I know that when I'm looping over a list I can do...

{% for i in list %}

But I have a variable called 'count_val' all I want to do is loop the value of count_val...

Can someone help make the following work...

count_val = 5
{{ loop count_val }}
   I'm {{ forloop.counter }}!

{{ endfor }}

Thanks

GrantU
  • 6,325
  • 16
  • 59
  • 89
  • o my bad, I did search oops. what about the whole forloop.counter thing? – GrantU Apr 23 '13 at 16:10
  • {% for i in range(my_count) %} is that correct? I get int' object is not iterable – GrantU Apr 23 '13 at 16:12
  • If the loop limit is constant, you can do `{% for i in "12345" %}`, but there's no built-in way to do this if the loop limit is a variable, so you'll have to use either a custom template tag or filter. See the first answer of the [Numeric for loop in Django templates](http://stackoverflow.com/questions/1107737/numeric-for-loop-in-django-templates) question for some examples. – Aya Apr 23 '13 at 16:19
  • Really? The way I see it at the moment is I could create a list from the number 1,2,3 etc and then do the for loop. but that just seems mad, right? – GrantU Apr 23 '13 at 16:22
  • Well, you could instead pass `range(count_val)` into the context instead of `count_val`, but that's not what your question asks. – Aya Apr 23 '13 at 16:25
  • Why can't you create a list in the view and send to template? – Akshar Raaj Apr 23 '13 at 16:27
  • I found this snippet: http://djangosnippets.org/snippets/2147/ is this how I would use: mkrange(my_count) as it state it requires two arguments? – GrantU Apr 23 '13 at 16:34

1 Answers1

1

A good way to deal with this is to limit the object to 5 rows in your views.py file and send that object over to your template, so your template doesn't have to deal with the count. (This kind of logic should be handled by the views.py file anyway, not the template). Since I don't know what kind of object you're using, I'll just show you a "Books" example to get the last five rows:

Book.objects.all()[:5]

jball037
  • 1,780
  • 1
  • 14
  • 18