2015-10-27 47 views
0

我有一個關於Python Django的問題。forloops裏面for循環在Django python

這是我的看法我們在PHP

for(k=0; k<3; k++){ 
some css class, i will add the K value eg:someclass_0 
echo threeboxs[k].title; 
echo threeboxs[k].description; 
} 

顯示我可以顯示Python代碼這樣

def index(request): 
    contacts = Contact.objects.all() 
    threeboxs = Threeboxes.objects.all() 
    return render(request, 'home/index.html', {'threeboxs': threeboxs, 'contacts': contacts}) 

方式。

{% for threebox in threeboxs%}  
    <h5>{{ threebox.title }}</h5> 
    <p>{{ threebox.description|linebreaks }}</p>     
{% endfor %} 

但這樣做,我不能更新循環的CSS類。然後我嘗試了這種方式,但沒有奏效。

{% context['loop_times'] = range(0, 3) 
    for n in loop_times: %} 
     {{ threebox[n].title }} 
{% endfor %} 

有人可以給我一個關於我該怎麼做的建議嗎?

+0

threeboxs = Threeboxes.objects.all()[3] ...這會給你前3結果.. – gamer

+0

tnx。但我想知道如何循環它並將值添加到CSS類。例如:'for(i = 0; i <2; i ++)',我想將'i'值添加到css類,然後顯示對象數組的值。 –

+0

循環的方式與上面所做的一樣...如果您想將值添加到css類,則嘗試在div外部循環並在css類中添加值。{%for threebox in threeboxes%}

Your code here
gamer

回答

1

您是通過一些指定的值試圖週期爲您在列表中,fortunately Django has you covered with the cycle templatetag迭代。

{% for threebox in threeboxs%}  
    <h5 style="{% cycle 'class_1' 'class_2' 'class_3' %}">{{ threebox.title }}</h5> 
    <p>{{ threebox.description|linebreaks }}</p>     
{% endfor %} 

這將使你:

<h5 style="class_1">Title 1</h5> 
<p>Body 1</p>     
<h5 style="class_2">Title 2</h5> 
<p>Body 2</p>     
<h5 style="class_3">Title 3</h5> 
<p>Body 3</p>     
<h5 style="class_1">Title 4</h5> 
<p>Body 4</p>     
<h5 style="class_2">Title 5</h5> 
<p>Body 5</p>     

等等......

+0

Tnx。解決了我的問題。 –