У меня есть вопрос о 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
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>
И так далее…
Пытаться:
{% for iter,threebox in threeboxs.items%}
Это даст вам доступ к ключу, если вам нужно … Или даже лучше:
forloop.counter
Проверьте эту документацию: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for
Что вы пытаетесь сделать с классом CSS?