Twig Variable in Array

2020-02-15 php twig symfony5

IndexContoller:

   return $this->render('pages/login.html.twig', TwigHelper::mergeDefault([
        'LoginForm'  => $form->createView(),
        'lang'       => self::getStrings('en-en') // Returns an array,
        'message'    => $verify['string'],
    ]));

Normally I call a string in a twig template with {{ lang.stringname }}. In this case I want to call a string with the value, which was submitted via 'message'.

I tried this:

{{ lang.[message] }}

and

{{ lang.{{ message }} }}.

The error message is:

Expected name or number.

Does anyone have an idea? Thank you.

Answers

The dot notation is a shortcut for an array[] - particularly useful for named arrays, but can also be used for numeric-indexes as well as. Use of the regular array is still possible, and that can take an independent variable as the key.

{{ lang[message] }}

There is a TwigFiddle, based on one in @DarkBee's link to show it in use.

Related