简体   繁体   中英

Php variable rewrite to Twig

My rewrite to Twig does not work. What is wrong?

PHP source:

<?php foreach ($datas as $data) { ?>
          <?php if ($data['information_id'] == $info_id)  { ?>
                <a href="<?php echo $data['href']; ?>" class="list-group active"><?php echo $data['title']; ?></a>              
             <?php } else { ?>
             <a href="<?php echo $data['href']; ?>" class="list-group"><?php echo $data['title']; ?></a> 
             <?php } ?> 
             <?php } ?>

Rewrite to Twig:

    {% for datas in data %}
            {% if {{ attribute(data,information_id) }} == info_id %}
             <a href="{{ data.href }}" class="list-group active">{{ data.title }}</a>
             {% else %}
             <a href="{{ data.href }}" class="list-group">{{ data.title }}</a>  
             {% endif %}           
        {% endfor %}

Try:

{% for data in datas %}
        {% if attribute(data,information_id) == info_id %}
             <a href="{{ data.href }}" class="list-group active">{{ data.title }}</a>
        {% else %}
             <a href="{{ data.href }}" class="list-group">{{ data.title }}</a>  
        {% endif %}           
{% endfor %}

You only need to wrap variables in {{ }} when you're outputting them to the page. Not in the middle of an {% if %} statement.

Also I've swapped round {% for datas in data %} to {% for data in datas %} . I'm assuming datas is the array, and data is each individual item.

https://twig.symfony.com/doc/2.x/tags/for.html

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