Using Latte with Slim 4
This article written by Daniel Opitz describes how to use Latte with the Slim Framework.
First, install the Slim Framework and then Latte using Composer:
Configuration
Create a new directory templates
in your project root directory. All templates will be placed there later.
Add a new template
configuration key in your config/defaults.php
file:
Latte compiles the templates to native PHP code and stores them in a cache on the disk. So they are as fast as if they had been written in native PHP.
Add a new template_temp
configuration key in your config/defaults.php
file: Make sure the directory
{project}/tmp/templates
exists and has read and write access permissions.
Latte automatically regenerates the cache every time you change the template, which can be turned off in the production environment to save a little performance:
Next, add a DI container definitions for the Latte\Engine
class.
This alone would technically work to render a Latte template, but we also need to make it work with the PSR-7 response object.
For this purpose we create a special TemplateRenderer
class which does this work for us.
So next create a file in src/Renderer/TemplateRenderer.php
and copy/paste this code:
Usage
Instead of using the Latte Engine object directly we use the TemplateRenderer
object to render the template into a
PSR-7 compatible object.
A typical Action handler class might look like this to render a template with the name home.latte
:
To make it work, create a template file in templates/home.latte
with this content:
If everything is configured correctly you should see the following output: