Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current page name in Silex

I'm wondering how to get the current page name, basically 'just' the last parameter in the route (i.e. /news or /about). I'm doing this because I want to be able to have the current page in the navigation highlighted.

Ideally, I'd like to store the current page name in a global variable so that in Twig I can just compare the current page name against the link and add a class accordingly.

I can't figure out how to add the current page name to a global variable though. I've tried using something like this:

$app['twig']->addGlobal('current_page_name', $app['request']->getRequestUri());

at the top of my app.php file, but an 'outside of request scope' error. But I wouldn't like to have to include this in every route.

What's the best way to do this?

like image 648
Pete Avatar asked Jan 18 '13 20:01

Pete


1 Answers

If you put it into an app-level before middleware like this, that'll work:

$app->before(function (Request $request) use ($app) {
    $app['twig']->addGlobal('current_page_name', $request->getRequestUri());
});

The "page name" part of your question is unclear, are you looking for the current route's name? You can access that via $request->get("_route") even in the before middleware, as it gets called when routing is already done.

like image 137
Maerlyn Avatar answered Sep 28 '22 16:09

Maerlyn