John Davidson

php - Cannot assign twig parameters from middleware in Slim v4

0 comments
Message:


I'm trying to upgrade my website's code from Slim v2 to v4. I'm not a hardcore programmer so I'm facing issues. In Slim v2 I had some middleware where I was able to assign parameters to the Twig view before the route code executed. Now I'm trying to manage the same with Slim v4 but without success.


So this is a test code:


use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Routing\RouteContext;

require 'vendor/autoload.php';
require 'config.php';
lib\Cookie::init();

$container = new \DI\Container();

$container->set('view', function($container) {
return Twig::create(__DIR__ . '/views');
});

$container->set('flash', function ($container) {
return new \Slim\Flash\Messages();
});

$container->get('view')->getEnvironment()->addGlobal('flash', $container->get('flash'));

AppFactory::setContainer($container);

$app = AppFactory::create();

$app->addErrorMiddleware(true, false, false);

$fb = new Facebook\Facebook([
'app_id' => '...',
'app_secret' => '...',
'default_graph_version' => '...',
]);

$beforeMiddleware = function (Request $request, RequestHandler $handler) use ($fb) {
$response = $handler->handle($request);
if (!isset($_SESSION['fbuser'])) {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl('...', $permissions);
$this->get('view')->offsetSet('fbloginurl', $loginUrl);
}
else {
$this->get('view')->offsetSet('fbuser', $_SESSION['fbuser']);
}
$uri = $request->getUri();

$this->get('view')->offsetSet('currenturl', $uri);

return $response;
};


$app->add($beforeMiddleware);

$app->get('/test', function (Request $request, Response $response, $args) {
$oViewParams = new \lib\ViewParams("home", "", "", "", "");
$oProfession = new \models\Profession();
$oBlogPost = new models\BlogPost();
$oBlogTopic = new models\BlogTopic();
$professions = $oProfession->getProfessionsWithLimit(14);
$posts = $oBlogPost->getMainPagePosts();

echo $this->get('view')->offsetGet('fbloginurl');
$params = array('professions' => $professions,
'posts' => $posts,
'viewp' => $oViewParams->getMassParams());
return $this->get('view')->render($response, 'index.html', $params);
});

$app->run();

When I use echo $this->get('view')->offsetGet('fbloginurl'); within the middleware it shows up. When I use the same within the route there is nothing show up...



My Answer:
> In Slim v4, you can no longer directly assign parameters to the Twig view from middleware. Instead, you can use the request attribute to pass data from middleware to the route handler, which can then assign the parameters to the Twig view.

Here's an example of how you can achieve this:

php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Routing\RouteContext;

require 'vendor/autoload.php';
require 'config.php';
lib\Cookie::init();

$container = new \DI\Container();

$app = AppFactory::create();
$app->add(function (Request $request, RequestHandler $handler) use ($container) {
$response = $handler->handle($request);

// Assign parameters to the request attribute
$request = $request->withAttribute('foo', 'bar');

return $response;
});

$app->get('/', function (Request $request, Response $response) {
$routeContext = RouteContext::fromRequest($request);
$twig = $routeContext->getRouteParser()->getRouteParser()->getTwig();

// Get parameters from the request attribute
$foo = $request->getAttribute('foo');

// Assign parameters to the Twig view
$twig->getEnvironment()->addGlobal('foo', $foo);

return $twig->render($response, 'index.twig');
});

$app->run();


In this example, we use middleware to assign parameters to the request attribute, and then retrieve and assign those parameters to the Twig view in the route handler. This way, you can achieve the same functionality as in Slim v2.

Rate this post

5 of 5 based on 8894 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us