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']
.
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') }}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With