How can I pass an array from a controller to a template? I want to render array to twig file I am able to render variables but not array.

My php file : 

  public function build() {

    $vid = 'Sectors';
    $terms =\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')- 
 &gt;loadTree($vid);
    foreach ($terms as $term) {
     $term_data[] = array(
      'id' =&gt; $term-&gt;tid,
      'name' =&gt; $term-&gt;name
     );
    }
    // echo "&lt;pre&gt;";
    //  print_r($term_data);
    //  die;
    // return $vid;

  // do something
    return array(
      '#theme' =&gt; 'mdoner_custom_block',
      'title' =&gt; 'MDoNER custom Block',
      //'#test' =&gt; array('key'=&gt;$term_data),
       'testmenu' =&gt; $term_data,
    );


  }


My array:

Array (
       [0] =&gt;
          Array (
               [id] =&gt; 1 
               [name] =&gt; Climate Change 
           )
        [1] =&gt;
           Array (
                [id] =&gt; 5
                [name] =&gt; Ecotourism
          )
    )


.module file:

function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' =&gt; [
      'variables' =&gt; ['title' =&gt; NULL],
      'test' =&gt; array(),
    ],
  ];
}


Twig file: 

&lt;!-- dump(content) --&gt; // get array of all the content
{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}


How can I pass the testmenu variable to twig.
You have to add the testmenu variable to the hook_theme implementation, like this:

function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' =&gt; [
      'variables' =&gt; [
        'title' =&gt; NULL,
        'testmenu' =&gt; [],
      ],
    ],
  ];
}


Then you have to pass it to the render array in your build() function like this:

return array(
  '#theme' =&gt; 'mdoner_custom_block',
  '#title' =&gt; 'MDoNER custom Block',
  '#testmenu' =&gt; $term_data, // #testmenu refers to the testmenu variable you set in hook_theme().
);


Now you should be able to iterate over the items in the testmenu variable like this:

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