简体   繁体   中英

how to convert php to twig syntax

Does anyone know how to covert this to twig?

        <?php for ($i = 0; $i < count($discounts); $i++) { ?>
        <?php if ($i == (count($discounts) - 1)) { ?>
<?php echo $discounts[$i]['quantity']; ?> - <?php echo ($discounts[$i + 1]['quantity'] - 1); ?><br><?php echo $discounts[$i]['price']; ?> 
        
        <?php } ?>
        <?php } ?>

Tried something like this but couldn't get it to work

        {% for discount in discounts %}
    {% set next_item = discounts[loop.index0 + 1] %}
{{ discount.quantity }} - {{ next_item.quantity }}{{ text_discount }}<br>{{ discount.price }}

Here is a working snippet. I'm guessing your twig code just didn't ran because u didn't account for the "missing" discount when u go out-of-bounds. In twig you can use the default filter to catch this.

Also notice I'm using the special var loop.index which is 1-indexed, so there is no need to "calculate" the next index with loop.index0 + 1

{% for discount in discounts %}
    From {{ discount.quantity }} To {{ discounts[loop.index].quantity|default('+') }}: {{ discount.price }}
{% endfor %}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM