首页 > 解决方案 > 无法在树枝文件中打印键和值

问题描述

我无法在 for 循环中获取键和值我的要求应该类似于标题 - 描述

我无法获得标题和描述中的值

                       (

                        [product_benefit] => Array(
                        [0] => Array
                            (
                                [description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                [title] => Ipsum Lorem 
                            )
                        [1] => Array
                            (
                                [description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                [title] => Ipsum Lorem 
                            )

                        [2] => Array
                            (
                                [description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                                [title] => Ipsum Lorem
                            )
                        [3] => Array
                            (
                                [description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                                [title] => Entertainment
                            )
                    )


                     {% if product.product_benefit is not null %}
  <ul class="manual-list">
    {% for row in product.product_benefit %}
        {% for slug, item in row %}
                <li><b>{{ item.title - item.description }}</b></li>
        {% endfor %}
    {% endfor %}
   </ul>

标签: symfonytwigsymfony4drupal-8drupal-modules

解决方案


您遇到的第一个问题是您的输出现在减去两个字符串,切换到{{ foo }} - {{ bar}}{{ foo ~'-'~ bar }}

读取数据:

  • 如果你想keys直接在你的代码中使用,那么你的第二个for已经过时了。
{% for row in product.product_description %}
    {{ row.title }} - {{ row.description }}
{% endfor %}
  • 如果要保持键动态,则需要第二个 for 循环,但不再使用文字
{% for row in product.product_description %}
    {% for key, value in row %}
        {{ key }} = {{ value }}
    {% endfor %}
{% endfor %}

演示


推荐阅读