Php 变量重写为 Twig



我对Twig的重写不起作用。怎么了?

PHP源代码:

<?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 } ?>

重写为树枝:

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

尝试:

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

您只需要在将变量输出到页面时将其包装在{{ }}中。 不是在{% if %}声明的中间。

我也把{% for datas in data %}轮换成了{% for data in datas %}. 我假设datas是数组,data是每个单独的项目。

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

最新更新