Search code examples
phptwigsymfony5

Twig Variable in Array


AuthContoller:

   return $this->render('pages/login.html.twig', [
        '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.


Solution

  • 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.