我在Django视图中的汽车对象如下:显示标题里面只有一次Django的if语句
'damages': [
{
"location": "Voorbumper",
"type": "Kras(10 cm, leger)",
"severity": "Light damage",
'comment': "This is some comment.",
"images": [
'http://pathtophoto.jpg',
'http://pathtophoto.jpg'
]
},
{
"location": "Vleugel rechts voor",
"type": "Deuk (Licht)",
"severity": "",
'comment': "",
"images": [
'http://pathtophoto.jpg',
'http://pathtophoto.jpg',
'http://pathtophoto.jpg'
]
},
{
"location": "Deur links voor",
"type": "Kras (5 cm, leger)",
"severity": "",
'comment': "",
"images": [
'http://pathtophoto.jpg'
]
},
{
"location": "Waterlijst",
"type": "Beschadigd",
"severity": "",
'comment': "",
"images": []
},
{
"location": "Antenne",
"type": "Ontbreekt",
"severity": "",
'comment': "",
"images": [
'http://pathtophoto.jpg'
]
},
{
"location": "Antenne",
"type": "Ontbreekt",
"severity": "",
'comment': "",
"images": []
}
]
我想通过对象循环和显示损害的图像。但我首先要用图像来显示损害,以及没有适当标题的图像损坏。
在Django模板我尝试d,如下所示:
{% for damage in car.damages %}
{% if damage.images|length > 0 %}
<div class="width-100 pad text-left primary-bg">{% trans "Shades met foto's" %}</div>
<div class="width-100 mar-top clear-float">
<div class="width-30 bord-my-way pad-half damage-info">
<div class="mar-btm-half"><b>{{ damage.location }}</b></div>
<div class="mar-btm-half">{{ damage.type }}</div>
<div class="mar-btm-half">{{ damage.severity }}</div>
<div class="mar-btm-half">{{ damage.comment }}</div>
</div>
<div class="width-70 pad-lft damage-photos">
{% for image in damage.images|slice:"3" %}
<div class="width-33 pad-rgh">
<img src="{{ image }}" class="width-100"/>
</div>
{% endfor %}
</div>
<div class="clear-float"></div>
{% if forloop.counter == 7 or forloop.counter == 14 or forloop.counter == 21 %}
<p style="page-break-before: always"></p> {% endif %}
</div>
{% endif %}
{% endfor %}
{% for damage in car.damages %}
{% if damage.images|length == 0 %}
<div class="width-100 pad text-left primary-bg mar-top">{% trans "Shades zonder foto's" %}</div>
<div class="green-bg">{{ damage.location }}</div>
{% endif %}
{% endfor %}
因此,我通过损害第一回路,其中damage.images|length > 0
,然后在第二对我检查是否存在与damage.images|length == 0
没有图像。但标题显示为每个for loop
迭代。
我可以放置标题的for loop
。喜欢的东西:
<div> Damages with photos </div>
{% for damage in car.damages %}
{% if damage.images|length > 0 %}
// Show it
{% endif %}
{% endfor %
而且
<div> Damages without photos </div>
{% for damage in car.damages %}
{% if damage.images|length == 0 %}
// Show it
{% endif %}
{% endfor %
但有时候我只有用图片或不仅损害赔偿没有图像,然后我看到标题,虽然我没有任何损害显现。
有什么办法给if statement
里面做一些事情只有一次,是这样的:
{% for damage in car.damages %}
{% if damage.images|length > 0 %}
<div>Damages with the photos</div> // Show it only once when it comes here
// Show the damages with photos
{% endif %}
{% endfor %}
{% for damage in car.damages %}
{% if damage.images|length == 0 %}
<div>Damages without the photos</div> // Show it only once when it comes here
// Show the damages without photos
{% endif %}
{% endfor %}
任何想法如何解决呢?
这是一个很好的参考。 – Boky