I created a custom form, a custom twig template, and I 'linked' both with a theme hook.

From my buildForm method of Form Class, I defined a variable like this :

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#foo'] = array("key_a"=>"value_a", "key_b"=>"value_b", "key_c"=>"value_c");
  // do some work ...
  return $form;

From my twig template, when I dump or sho all availables variables with :

{{ dump() }}
{# or with kint #}
{{ kint() }}

I see my array '#foo' is present in variables availables from my custom twig template. The "#foo" array is in a 'element' array. My question is, how can I get and print the content ?

If I do a sample :

{{ #foo }}

I get a syntax error because there is a 'sharp' (#) character. I tried :

{{ element.#foo }}
{{ element.'#foo' }}
{{ 'element.#foo' }}
{{ foo }}

Sometimes I get an error, sometimes a NULL printed result..How can I print my array, get keys and values ?

Thanks you !


Like javascript you need to use bracket notation to get hash key variables:

{{ element['#foo'].key_a }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.