phptwigslimtwig-extensionslim-4

slim/twig-view - TwigExtension template functions not indetified and working


I'm following the steps described here to use twig-view within Slim https://github.com/slimphp/Twig-View/tree/3.1.0#usage but I'm getting the following error on my screen when I try to use anyof the template functions used in TwigExtension

Fatal error: Uncaught Twig\Error\SyntaxError: Unknown "url_for" function.

I have run $ composer require slim/twig-view:^3.0 successfully, my composer.json file looks like this

"require": {
        "slim/slim": "4.*",
        "slim/psr7": "^1.2",
        "league/container": "^3.3",
        "slim/twig-view": "^3.0"
    },

and this is my code

require_once __DIR__ . '/../vendor/autoload.php';

$container = new \Slim\Factory\Container();
\Slim\Factory\AppFactory::setContainer($container);

$container->add('view', function () {
    return \Slim\Views\Twig::create(__DIR__ . '/views', [
        'cache' => false,
    ]);
});

$app = \Slim\Factory\AppFactory::create();
$app->add(\Slim\Views\TwigMiddleware::createFromContainer($app));

require_once __DIR__ . '/../routes.php';


// routes.php
$app->get('/', function ($request, $response, $args) use ($container) {
    return $container->get('view')->render($response, 'home.twig', ['foo' => 'test']);
})->setName('home');

// home.twig
...
<body>
    Home {{ foo }}
    <br>
    <a href="{{ url_for('about') }}">About</a>
</body>
...

If I remove the url_for from the twig template the page loads fine on the browser. I tried to search for TwigExtension in my codebase and the vendor folder, but can't find any file like that. Am I doing something wrong here?


Solution

  • Looks like it's because of League container. It seems to be creating a new instance of Twig every time the function gets called $container->get('view') returns a new instance every time instead of referencing the same one. So a workaround would be

    $twig = \Slim\Views\Twig::create(__DIR__ . '/views', [
        'cache' => false,
    ]);
    
    $container->add('view', function () use (&$twig) {
        return $twig;
    });
    
    // Or this instead
    $container->add(
        'view', 
        \Slim\Views\Twig::create(__DIR__ . '/views', [
            'cache' => false,
        ])
    );