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] => [email protected]
            )

        [1] => stdClass Object
            (
                [name] => User2
                [user_id] => 2
                [email] => [email protected]
            )

        [2] => stdClass Object
            (
                [name] => User3
                [user_id] => 3
                [email] => [email protected]
            )
     )

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

1 Answer 1

4

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 %}
3
  • 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
    Commented Apr 4, 2017 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. Commented Apr 4, 2017 at 14:00
  • @edwardchiapet given correct explanation, thanks edwardchiapet
    – Ajay Reddy
    Commented Apr 4, 2017 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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