nowiko
nowiko

Reputation: 2557

Output arrays in Twig

I created the array in Twig and tried to output its values:

 {% set comments = [
    {'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013'},
    {'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013'},
    {'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013' },
] %}

Loop to iterate:

{% for key,item in comments %}
    {% for comment in item %}
       {{ attribute(comment, key).author }}
    {% endfor %}
{% endfor %}

But I get a white screen. What I am doing wrong?

I tried to do it as described in Accessing array values using array key from Twig.

Upvotes: 0

Views: 1094

Answers (1)

Clarence
Clarence

Reputation: 2964

You don't have nearly the same data structure as in link you posted. All you want to do for each item in your array is to show one property of the object. So just a simple property fetch is enough:

{% set comments = [
{'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013'},
{'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013'},
{'author': 'Bhaumik Patel', 'comment_body': 'Test comment body', 'date': '2 Aug 2013' },
] %}

{% for key,item in comments %}
    {{ item.author }}
{% endfor %}

Upvotes: 1

Related Questions