Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig render array key with a dash in it

Tags:

php

twig

How do you render a value of the value of an array key when it has a dash in the name?

I have this snippet:

$snippet = "
    {{ one }}
    {{ four['five-six'] }}
    {{ ['two-three'] }}
";

$data = [
    'one' => 1,
    'two-three' => '2-3',
    'four' => [
        'five-six' => '5-6',
    ],
];

$twig = new \Twig_Environment(new \Twig_Loader_String());
echo $twig->render($snippet, $data);

The output is

1
5-6
Notice: Array to string conversion in path/twig/twig/lib/Twig/Environment.php(320) : eval()'d code on line 34

And it renders four['five-six'] fine. But throws an error on ['two-three'].

like image 355
Petah Avatar asked May 06 '13 22:05

Petah


2 Answers

This cannot work, since you shouldn't be using native operators in variable names - Twig internally compiles to PHP so it cannot handle this.

For attributes (methods or properties of a PHP object, or items of a PHP array) there is a workaround, from the documentation:

When the attribute contains special characters (like - that would be interpreted as the minus operator), use the attribute function instead to access the variable attribute:

{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
like image 141
Niels Keurentjes Avatar answered Sep 25 '22 06:09

Niels Keurentjes


Actually this can work, and it works:

        $data = [
            "list" => [
                "one" => [
                    "title" => "Hello world"
                ],
                "one-two" => [
                    "title" => "Hello world 2"
                ],
                "one-three" => [
                    "title" => "Hello world 3"
                ]
            ]
        ];
        $theme = new Twig_Loader_Filesystem("path_to_your_theme_directory");
        $twig = new Twig_Environment($theme, array("debug" => true));
        $index = "index.tmpl"; // your index template file
        echo $this->twig->render($index, $data);

And snippets to use inside template file:

{{ list["one-two"]}} - Returns: Array
{{ list["one-two"].title }} - Returns: "Hello world 2"
like image 42
Playnox Avatar answered Sep 24 '22 06:09

Playnox