Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a list in Django templates

With this code:

{% for o in [1,2,3] %}     <div class="{% cycle 'row1' 'row2' %}">         {% cycle 'row1' 'row2' %}     </div> {% endfor %} 

I get a TemplateSyntaxError:

Could not parse the remainder: '[1,2,3]' from '[1,2,3]' 

Is there a way of building a list in a template?

like image 937
zjm1126 Avatar asked Dec 09 '10 05:12

zjm1126


2 Answers

We can use split method on str object :

page.html :

{% with '1 2 3' as list %}   {% for i in list.split %}     {{ i }}<br>   {% endfor %} {% endwith %} 

Results :

1 2 3 
like image 117
Zulu Avatar answered Oct 25 '22 17:10

Zulu


You can do it via cunning use of the make_list filter, but it's probably a bad idea:

{% for o in "123"|make_list %}     <div class="{% cycle 'row1' 'row2' %}">         {% cycle 'row1' 'row2' %}     </div> {% endfor %} 

p.s. You don't seem to be using o anywhere, so I'm not sure what you're trying to do.

like image 33
Dominic Rodger Avatar answered Oct 25 '22 16:10

Dominic Rodger