Search code examples
symfonytwigsymfony4drupal-8drupal-modules

Not able to print the key and values in twig files


I am not able to get the key and values in for loop My requirement should be like the Title - description

I am not able to get the value in title and description

                       (

                        [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>

Solution

  • The first issue you have is that your output is now substracting two strings, either switch to {{ foo }} - {{ bar}}or {{ foo ~'-'~ bar }}

    For reading out the data:

    • If you want to use the keys directly in your code then your 2nd for is obsolete.
    {% for row in product.product_description %}
        {{ row.title }} - {{ row.description }}
    {% endfor %}
    
    • If you want to keep the keys dynamic you'd need the 2nd for loop but you don't use the literals anymore
    {% for row in product.product_description %}
        {% for key, value in row %}
            {{ key }} = {{ value }}
        {% endfor %}
    {% endfor %}
    

    demo