forloops在Django python中的for循环中


forloops inside for loops in Django python

我有一个关于Python Django的问题。

这是我的观点

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

我们在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代码。

{% 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 %}

有人能给我一个建议吗?

在遍历列表时,您正试图循环使用一些指定的值,幸运的是Django为您提供了cycle模板。

{% 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>                

等等…

尝试:

{% for iter,threebox in threeboxs.items%} 

如果你需要的话,这将使你能够访问密钥。。。甚至更好:

forloop.counter

查看此文档:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for

你想用css类做什么?