如何周期性改变adiv每一行中两个元素的顺序

How to periodically change the order of two elements in each row of a div

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

我从数据库中读取了 titledescription 以及 cover

我想定期更改每行中 imagetext 的顺序。

我不知道该怎么做。我对 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变量是True(或设置为任何非空值),它将显示右边有图像的行。

如果 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,因此它将在左侧显示图像。

希望对您有所帮助。不过,这可能需要一些调整。