Passing an array of object from custom module to template in drupal 8 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' =&gt; 'my_page', 
        '#text' =&gt; "Lorem Ipsum",       
        '#myvariable' =&gt; array('key' =&gt; $myArrayofObjects),
      );
  } 


mymodule.module

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


my-page.html.twig

&lt;p&gt;Test twig template!&lt;/p&gt;    
&lt;p&gt;{{text}}&lt;/p&gt;

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


This is the array :

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

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

        [2] =&gt; stdClass Object
            (
                [name] =&gt; User3
                [user_id] =&gt; 3
                [email] =&gt; 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?
In your controller why you are using like this

'#myvariable' =&gt; array('key' =&gt; $myArrayofObjects),


Change it as

'#myvariable' =&gt; $myArrayofObjects,


and in my-page.html.twig

&lt;p&gt;Test twig template!&lt;/p&gt;    
&lt;p&gt;{{text}}&lt;/p&gt;

{% for key, value in myvariable %}
  Key : {{ key }}
  Name : {{ value.name }}
  User ID : {{ value.user_id }}
  Email : {{ value.email }}
{% endfor %}