Skip to main content
replaced http://drupal.stackexchange.com/ with https://drupal.stackexchange.com/
Source Link

Follow thisthis 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:

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:

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:

Source Link
Ugy Astro
  • 119
  • 1
  • 6

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' => '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?