Score:0

Pass a PHP array to Twig?

ph flag

I want to be able to access an array in my Twig template that is built in PHP but it always appears blank, am I missing something?

mytheme.theme

function mytheme_preprocess_page(array &$variables) {
  $variables['myvar'] = 'foo';
}

page.html.twig

{{ myvar }}

works as expected but if I pass an array this doesn't work:

$variables['myvar'] = ['foo', 'bar'];

just outputs nothing

Score:1
cn flag

There are two possible answers depending on what you are trying to achieve. You can loop over arrays in Twig like in any programming language, see the other answer.

Specific to Drupal's template engine is that if you want Twig to render an array recursively it has to be a renderable array. This means that each element which has no children has to be a render element (#markup, #plain_text, #type or #theme):

$variables['myvar'] = [
  0 => ['#plain_text' => 'foo'],
  1 => ['#plain_text' => 'bar'],
];

Then

{{ myvar }}

renders the entire array.

See https://www.drupal.org/docs/drupal-apis/render-api/render-arrays.

Score:1
us flag

To print all the items contained in that array without assuming how many items it contains, you can use the following code.

{% for key, var in myvar %}
  {{ myvar[key] }}
{% endfor %}  

Otherwise, you can simply use the following code.

{{ myvar[0] }} {{ myvar[1] }}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.