A
A
Alexander Vladimirovich2020-04-22 01:56:56
PHP
Alexander Vladimirovich, 2020-04-22 01:56:56

How to properly render a template from a string?

Greetings!
There is a line containing a Twig template:
$template = 'Hello {{ name|capitalize }}!';
And there is an array of data to substitute into the template
$data = ['name' => 'world']
How to get the template rendered by twig into a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Fedorov, 2020-04-22
@polyanin

$loader = new \Twig\Loader\ArrayLoader([
    'you_name.html' => 'Hello {{ name }}!',
]);
$twig = new \Twig\Environment($loader);

echo $twig->render('you_name.html', ['name' => 'Fabien']);

Source: Built-in Loaders¶
Well, of course, you can create a proxy service in a container so that you don’t have to worry about it every time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question