在我的Django项目的HTML文件之一中,我有一个div
,其中包含col-6
用于图像和col-6
文本的。
{% if automotives %}
{% for automotive in automotives %}
<div class="row">
<div class="col-6 mb-4 mb-md-0 my-5 pl-5">
<h3 class="font-weight-bold">{{ automotive.title }}</h3>
<p class="text-muted">{{ automotive.description|safe }}</p>
</div>
<div class="col-6 mb-4 mb-md-0 my-5 pr-5">
<div class=" overlay z-depth-1-half">
<img src="{{ automotive.cover.url }}" class="img-fluid" alt="cover">
</div>
</div>
</div>
{% endfor %}
{% endif %}
我读title
和description
和cover
从数据库。
我想定期更改每行中图像和文本的顺序。
我不知道该怎么做。而且我对js或jquery不太了解。
任何帮助表示赞赏。
你可以使用flex来实现,但是我看到你的问题与django / jinja2有关,因此,这就是我要解决的问题:
建立像这样的部分模板
{% if image_right %}
<div class="row">
<div class="col-6 mb-4 mb-md-0 my-5 pl-5">
<h3 class="font-weight-bold">{{ automotive.title }}</h3>
<p class="text-muted">{{ automotive.description|safe }}</p>
</div>
<div class="col-6 mb-4 mb-md-0 my-5 pr-5">
<div class=" overlay z-depth-1-half">
<img src="{{ automotive.cover.url }}" class="img-fluid" alt="cover">
</div>
</div>
</div>
{% else %}
<div class="row">
<div class="col-6 mb-4 mb-md-0 my-5 pr-5">
<div class=" overlay z-depth-1-half">
<img src="{{ automotive.cover.url }}" class="img-fluid" alt="cover">
</div>
</div>
<div class="col-6 mb-4 mb-md-0 my-5 pl-5">
<h3 class="font-weight-bold">{{ automotive.title }}</h3>
<p class="text-muted">{{ automotive.description|safe }}</p>
</div>
</div>
{% endif %}
你可以将其命名为image_text.html
。该模板包含一些重复的代码,但是很容易理解。
如果image_right
variable为True
(或设置为任何非null值),它将在右侧显示带有图像的行。
如果image_right
变量是False
,(或0或任何其他空值),它将显示左侧的图像(因此,在这种情况下,左侧的图像是默认行为)。
然后,在主模板中,image_text.html
例如,如果要在每行左右切换图像,则可以使用刚刚构建的部分模板(),例如:
{% if automotives %}
{% for automotive in automotives %}
{% include 'image_text.html' with automotive=automotive image_right=forloop.counter|divisibleby:2 %}
{% endfor %}
{% endif %}
forloop.counter
是for循环的索引(从1开始,forloop.counter0
如果要从0开始的计数器,则为用户)。
当forloop.counter
为偶数时,image_right
你的部分模板中将为True
,因此它将在右侧显示图像。
当forloop.counter
为奇数时,image_right
你的部分模板中将为False
,因此它将在左侧显示图像。
希望能帮助到你。不过,这可能需要一些调整。
伟大的。它工作得很好。