TwigTrait
Provides seamless integration of the **Twig** templating engine into controllers using the **Slim Framework**.
This trait offers:
- Automatic initialization of a
Twig
instance from a provided configuration array or via a PSR-11 dependency injection container. - A simplified
render()
method for rendering Twig templates into a PSR-7ResponseInterface
. - Error handling through Twig's native exceptions for better debugging.
Typical usage within a Slim controller:
use oihana\controllers\traits\TwigTrait;
class MyController {
use TwigTrait;
public function __construct(ContainerInterface $container) {
$this->initializeTwig([], $container);
}
public function home($request, $response) {
return $this->render($response, 'home.twig', [
'title' => 'Welcome!',
'user' => 'Marc'
]);
}
}
Tags
Table of Contents
Constants
- TWIG = 'twig'
- The container key used to retrieve the Twig instance.
Properties
- $twig : Twig
- The Twig view renderer instance.
Methods
- initializeTwig() : static
- Initializes the Twig environment for rendering templates.
- render() : ResponseInterface|null
- Renders a Twig template into a PSR-7 response.
Constants
TWIG
The container key used to retrieve the Twig instance.
public
string
TWIG
= 'twig'
Properties
$twig
The Twig view renderer instance.
public
Twig
$twig
Methods
initializeTwig()
Initializes the Twig environment for rendering templates.
public
initializeTwig([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
This method first checks if a Twig instance is provided in the $init
array.
If not, and a PSR-11 container is available, it attempts to fetch the Twig instance using the self::TWIG
key.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array (e.g.,
['twig' => Twig $instance]
). - $container : ContainerInterface|null = null
-
Optional PSR-11 container for retrieving the Twig instance.
Tags
Return values
static —Returns the current instance for method chaining.
render()
Renders a Twig template into a PSR-7 response.
public
render(ResponseInterface|null $response, string $template[, array<string|int, mixed> $args = [] ]) : ResponseInterface|null
Parameters
- $response : ResponseInterface|null
-
The PSR-7 response instance.
- $template : string
-
The name of the Twig template to render.
- $args : array<string|int, mixed> = []
-
Optional array of parameters passed to the template.
Tags
Return values
ResponseInterface|null —The modified response instance, or null
if $response
is not provided.