【问题标题】:Display different <div> depending on arrays length根据数组长度显示不同的 <div>
【发布时间】:2017-06-25 18:53:34
【问题描述】:

我正在进行我的第一个 JinJa2 项目。 我想展示汽车。一辆车可以有一个或多个选项。 如果一辆车有一个选择,请展示出来。如果有更多,暂时隐藏它。 这是我的代码:

//...
{% set products = ['Audi', 'BMW', 'Mercedes', 'Porsche'] %}
{% set options = ['Small', 'Sport', 'Coupe', 'Jeep'] %}

{% for product in products %}
    {% include '../car-product-item.html' with context %}
{% endfor %}

{% if options|length > 1 %}
    //If a car has more options, hide this options for the moment
    <div class="order-more-options" style="display: none; background: green">
        {% for product in options %}
        {% include '../car-product-item.html' with context %}
        {% endfor %}
    </div>

{% elif  options|length == 1 %}
    //If a car has one option, show this option
    <div class="order-more-options" style="display: block; background: orange">
        {% for product in options %}
        {% include '../car-product-item.html' with context %}
        {% endfor %}
    </div>
{% endif %}
//...

由于某种原因它不起作用。选项总是隐藏的。 我做错了什么?

我检查了TutorialDocu 和另一个SO-Question,但没有任何帮助。

【问题讨论】:

  • 对我来说看起来不错,您应该打印选项/产品以确保它不为空(如果实际情况更复杂)。还要检查include 是否将您的代码添加到循环/if 之外,以确保它不为空。
  • 数组中有项目,我查过了

标签: python html python-2.7 jinja2 lektor


【解决方案1】:

对我来说效果很好,当我跳过

{% include ...

使用以下代码的命令:

{% set products = ['Audi', 'BMW', 'Mercedes', 'Porsche'] %}
{% set options = ['Small', 'Sport', 'Coupe', 'Jeep'] %}

{% if options|length > 1 %}
    <div>more than one options</div>
    <div class="order-more-options" style="display: none; background: green">
        {% for product in options %}
        {{product}}
        {% endfor %}
    </div>
{% elif  options|length == 1 %}
    <div>exactly one option</div>
    <div class="order-more-options" style="display: block; background: orange">
        {% for product in options %}
        {{product}}
        {% endfor %}
    </div>
{% endif %}

您是否使用了正确的 car-product-item.html 路径?尝试将文件 car-product-item.html 放入模板文件夹并将包含行更改为 {% include '/car-product-item.html' ...%}。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多