Macbernie Macbernie - 4 months ago 130
PHP Question

Silex v1.3 to Silex v2: Twig_Error_Runtime

I recently migrated my Silex v1.3 project where everything is worked fine, to the Silex v2. I get a twig error where I don't understand the cause

Twig_Error_Runtime in Template.php line 590:

Neither the property "request" nor one of the methods "request()", "getrequest()"/"isrequest()" or "__call()" exist and have public access in class "Silex\Application" in "index.twig" at line 5


Here is the 5 first lines of my index.twig file

{% extends "layout.twig" %}


{% block stylsheets %}
<link rel="stylesheet" type="text/css" href="{{ app.request.basepath }}/public/libs/odometer/themes/odometer-theme-minimal.css" />


And of course in the layout, I call the

{% block stylsheets %}{% endblock %}


But I'm not sure at all, the problem is on the twig file...
Is something has to be change ?

Here is an extract of the controller:

$app->get('/', function () use ($app) {

return $app['twig']->render('index.twig', [
...
]);
})->bind('homepage');


Thanks for help

Answer

As I know request was removed from application in silex2.

Transmit request to twig manually

use Symfony\Component\HttpFoundation\Request;

$app->get('/', function (Request $request) use ($app) {
    $app['twig']->addGlobal('request', $request);

    return $app['twig']->render('index.twig', [
        ...
    ]);
})->bind('homepage');

href="{{ request.basepath }}

or add it to application without changing templates

use Symfony\Component\HttpFoundation\Request;

$app->get('/', function (Request $request) use ($app) {
    $app['request'] = $request;

    return $app['twig']->render('index.twig', [
        ...
    ]);
})->bind('homepage');

Also you can include twig asset extension, but it will require some manipulations http://symfony.com/doc/current/book/templating.html#linking-to-assets