-
Notifications
You must be signed in to change notification settings - Fork 3
Using Twig template engine
Anatoly Nekhay edited this page Jan 7, 2019
·
1 revision
Learn more about Twig
composer require twig/twig
Adding the following code to
config/definitions.php
/**
* Twig template engine
*
* @link https://twig.symfony.com/
*/
Twig_Environment::class => function($container)
{
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../templates');
$debug = in_array($container->get('env'), ['local', 'development']);
$twig = new Twig_Environment($loader, [
'debug' => $debug,
'cache' => __DIR__ . '/../cache/twig',
]);
return $twig;
},
mkdir templates && mkdir -p cache && mkdir cache/twig
Create the following file:
touch templates/index.html
Add the following code to the file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Twig Example</title>
</head>
<body>
<table>
<thead>
<tr>
<td>Product</td>
<td>Description</td>
<td>Value</td>
<td>Date</td>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.value }}</td>
<td>{{ product.date_register|date("m/d/Y") }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
/**
* @Inject
*
* @var \Twig_Environment
*/
protected $twig;
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
*
* @return ResponseInterface
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler) : ResponseInterface
{
$products = [
[
'name' => 'Notebook',
'description' => 'Core i7',
'value' => 800.00,
'date_register' => '2017-06-22',
],
[
'name' => 'Mouse',
'description' => 'Razer',
'value' => 125.00,
'date_register' => '2017-10-25',
],
[
'name' => 'Keyboard',
'description' => 'Mechanical Keyboard',
'value' => 250.00,
'date_register' => '2017-06-23',
],
];
$content = $this->twig->render('index.html', ['products' => $products]);
$response = $handler->handle($request);
$response->getBody()->write($content);
return $response;
}
Have questions?
Ask your questions in our chat:
Get more features for your application using Awesome PSR-15 Middleware