jasenmichael
jasenmichael

Reputation: 428

php combine variables into array for twig

so I have some php variables, some are form an array. I can print them like this

echo $arr->title;
echo $arr->date;
echo $xml;
echo $cover;

I am using twig. I think I need to combine specific php variables into one array(say book) so I can render my twig template with

echo $template->render(['book' => $book]);

then in my twig template be able to use

{{ title }}
{{ date }}
{{ xml }}
{{ cover }}

any tips on how to achieve this would be greatly appreciated .

Upvotes: 1

Views: 144

Answers (2)

localheinz
localheinz

Reputation: 9582

If you want to be able to use the data in your twig template like this:

{{ title }}
{{ date }}
{{ xml }}
{{ cover }}

then you need to pass on the data to the view like that:

echo $template->render([
    'title' => $arr->title,
    'date' => $arr->date,
    'xml' => $xml,
    'cover' => $cover,
]);

Upvotes: 0

odan
odan

Reputation: 4952

Just create the array for your needs:

$viewData = [
    'book' => [
        'title' => $arr->title,
        'date' => $arr->date,
        'xml' => $xml,
        'cover' => $cover,
    ]
];

echo $template->render($viewData);

Template

{{ book.title }}
{{ book.date }}
{{ book.xml }}
{{ book.cover }}

Upvotes: 2

Related Questions