Skip to content
Advertisement

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 TwigErrorSyntaxError: 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 SlimFactoryContainer();
SlimFactoryAppFactory::setContainer($container);

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

$app = SlimFactoryAppFactory::create();
$app->add(SlimViewsTwigMiddleware::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?

Advertisement

Answer

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 = SlimViewsTwig::create(__DIR__ . '/views', [
    'cache' => false,
]);

$container->add('view', function () use (&$twig) {
    return $twig;
});

// Or this instead
$container->add(
    'view', 
    SlimViewsTwig::create(__DIR__ . '/views', [
        'cache' => false,
    ])
);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement