Warm tip: This article is reproduced from serverfault.com, please click

html-如何定期更改div每行中两个元素的顺序

(html - How to periodically change the order of two elements in each row of a div)

发布于 2020-12-03 08:17:05

在我的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 %}

我读titledescriptioncover从数据库。

我想定期更改每行图像文本的顺序

我不知道该怎么做。而且我对js或jquery不太了解。

任何帮助表示赞赏。

Questioner
Shahriar.M
Viewed
11
Miles Davis 2020-12-03 16:52:14

你可以使用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_rightvariable为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,因此它将在左侧显示图像。

希望能帮助到你。不过,这可能需要一些调整。