0

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()->getStorage('taxonomy_term')- 
 >loadTree($vid);
    foreach ($terms as $term) {
     $term_data[] = array(
      'id' => $term->tid,
      'name' => $term->name
     );
    }
    // echo "<pre>";
    //  print_r($term_data);
    //  die;
    // return $vid;

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


  }

My array:

Array (
       [0] =>
          Array (
               [id] => 1 
               [name] => Climate Change 
           )
        [1] =>
           Array (
                [id] => 5
                [name] => Ecotourism
          )
    )

.module file:

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

Twig file:

<!-- dump(content) --> // 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.

1 Answer 1

5

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' => [
      'variables' => [
        'title' => NULL,
        'testmenu' => [],
      ],
    ],
  ];
}

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

return array(
  '#theme' => 'mdoner_custom_block',
  '#title' => 'MDoNER custom Block',
  '#testmenu' => $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 %}
0

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.