Display different <div> depending on arrays length

259 Views Asked by At

I'm on my first JinJa2 project. I want to display cars. A car can have one or more options. If a car has one option, show that. If it has more, hide it for the moment. Here's my code:

//...
{% 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 %}
//...

For some reason its not working. The options are always hidden. What am I doing wrong?

I checked a Tutorial, the Docu and another SO-Question but nothing helped.

1

There are 1 best solutions below

0
On

For me it works fine, when I skip the

{% include ...

commands using the following code:

{% 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 %}

Do you use the correct path to car-product-item.html? Try to put the file car-product-item.html to the templates folder and change your include-lines to {% include '/car-product-item.html' ...%}.