1

Follow this about passing an array to template. But my array is array of object so I'm getting some errors on the page, this is the one of them:

User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php)

This is my code :

Controller

  public function content() {
      return array(
        '#theme' => 'my_page', 
        '#text' => "Lorem Ipsum",       
        '#myvariable' => array('key' => $myArrayofObjects),
      );
  } 

mymodule.module

function my_page($existing, $type, $theme, $path) {
  return array(
    'my_page' => array(
        'variables' => array(
            'text' => NULL,
            'myvariable' => array(),
        ),
    ),
  );
}

my-page.html.twig

<p>Test twig template!</p>    
<p>{{text}}</p>

{% for key, value in myvariable %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

This is the array :

Array
    (
        [0] => stdClass Object
            (
                [name] => User1
                [user_id] => 1
                [email] => user1@website.com
            )

        [1] => stdClass Object
            (
                [name] => User2
                [user_id] => 2
                [email] => user2@website.com
            )

        [2] => stdClass Object
            (
                [name] => User3
                [user_id] => 3
                [email] => user3@website.com
            )
     )

How the best way to pass an array of object from module to template and render or loop it using twig engine?

1

In your controller why you are using like this

'#myvariable' => array('key' => $myArrayofObjects),

Change it as

'#myvariable' => $myArrayofObjects,

and in my-page.html.twig

<p>Test twig template!</p>    
<p>{{text}}</p>

{% for key, value in myvariable %}
  Key : {{ key }}
  Name : {{ value.name }}
  User ID : {{ value.user_id }}
  Email : {{ value.email }}
{% endfor %}
  • Thank's @AAjay Reddy, finally it works. If you are willing, can you give an explain why #myvariable => array('key' => $myArrayofObjects), changed to #myvariable => $myArrayofObjects ? For my knowladge. Thanks – Ugy Astro Apr 4 '17 at 12:57
  • @UgyAstro - You don't need 'key' because when you do the for loop in the Twig, it will automatically associate the index with key and each element in the array with value. In your example, the key index variable will be the 'key' string and the value will be the actual array of objects. – edwardchiapet Apr 4 '17 at 14:00
  • @edwardchiapet given correct explanation, thanks edwardchiapet – Ajay Reddy Apr 4 '17 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.