【问题标题】:How to periodically change the order of two elements in each row of a div如何定期更改div每行中两个元素的顺序
【发布时间】:2021-03-15 05:46:24
【问题描述】:

在我的 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了解不多。

感谢任何帮助。

【问题讨论】:

    标签: html django jinja2


    【解决方案1】:

    您可以使用 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 循环的索引(如果你想要一个从 0 开始的计数器,它从 1 开始,用户 forloop.counter0)。

    forloop.counter 为偶数时,部分模板中的image_right 将是True,因此它会在右侧显示图像。

    forloop.counter 为奇数时,部分模板中的image_right 将是False,因此它会在左侧显示图像。

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

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 1970-01-01
      • 2015-08-28
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多