Open jameswilson opened 4 months ago
Thinking through this a bit more, maybe the template engine approach should be generalized to support any kind of PHP template engine such as Laravel Blade (here is a Blade template engine standalone package) or the Crow template engine .
For example have a special app setting register a mapping mechanism from file extension to render callback function. That way you don't have to build in 3rd party tools into your codebase.
Something like:
$app = new \PhpExpress\Application();
$app->set('views', 'path/to/views');
$app->set('template_engines', [
'twig' => function(string $view, array $locals = null): void {
$loader = new \Twig\Loader\FilesystemLoader('path/to/views');
$twig = new \Twig\Environment($loader, [
'cache' => 'path/to/twig_cache',
// Uncomment for local development only.
'debug' => true,
'auto_reload' => true,
]);
echo $twig->render($template, $locals);
}
]);
Or maybe a way to completely override the render function via callback without needing to subclass \PhpExpress\Application ?
$app->set('renderer', function(string $view, array $locals = null): void {
$loader = new \Twig\Loader\FilesystemLoader('path/to/views');
$twig = new \Twig\Environment($loader, [
'cache' => 'path/to/twig_cache',
// Uncomment for local development only.
'debug' => true,
'auto_reload' => true,
]);
echo $twig->render($view, $locals);
});
$app->get('/', function ($req, $res) {
$res->render('base.html.twig', [
'title' => 'Home page',
'content' => 'This is the home page.',
]);
});
Thanks for your work on this project. I'm planning on using it to put together a simple HTMX example app.
It would be interesting to add in optional support for the Twig template engine. Regardless of anyone's stance on Symfony, it is a fantastic template language and doesn't even require the entire Symfony package ecosystem to use it standalone.
Something like this would be cool:
Then in template folder we have:
views/base.twig:
views/about.html.twig:
In
Application::render()
we can hand down local variables into the Twig template if a matching view filename with extension.twig
is found.Then we can check if Twig FilesystemLoader class exists. The following is working for me: