3

I am trying to get my first module to work which is supposed to render an array in his own template file.

1) I got an array of variables and return it in my controller

 array( '#theme' => 'myTheme', '#test_var' => $this->t('Test Value'), '#array' => array('key'=>$myArray), ); 

2) in my .module I declare the hook_theme()

 return array( 'myTheme' => array( 'variables' => array( 'test_var' => '', 'array' => array(), ), ), 

);

3) Then I would like to print the variables I am sure I missing something, and if I'm missing basic knowledge please let me know. I'm sure something is wrong in the hook_theme since I don't know how to iterate my array in the template file.

<p>test_var: {{ test_var }}</p> <p>{{ array }}</p> 

If somebody could point me in the right direction, that would be nice :)

edit: the "Test Value" is rendering just fine

1 Answer 1

6

The variable names in the render array and theme hook need to match:

array( '#theme' => 'myTheme', '#test_var' => $this->t('Test Value'), '#doubles' => array('key'=>$myArray), ); 

Iterating an array in Twig is pretty straightforward:

{% for key,value in doubles %} Key : {{ key }} Value : {{ value }} {% endfor %} 
5
  • wow that was quick, thank you. the variables name match, that was a mistake i edited. i will try that solution Commented Nov 22, 2016 at 12:54
  • Unfortunately that was not the solution i also got an error message for each of my array keys User error: "46" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of /homepages/17/d628339351/htdocs/thesis/Drupal822/core/lib/Drupal/Core/Render/Element.php) Commented Nov 22, 2016 at 12:59
  • If you print an array Drupal will try to render it as a render array, so you just need do something with the nested array. Might be getting a value like value.foo, or looping over it to get at the values and so on Commented Nov 22, 2016 at 13:07
  • just as a follow up, your answer was totally correct, and the final solution was that since my array wasnt associative but rather a simple array and therefor the controller return looked even simplier: '#array' => $myArray. thats it ;) Commented Nov 22, 2016 at 21:07
  • @GinTonic What was the code in .module file. Commented Dec 28, 2016 at 12:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.