Search code examples
symfonysonatasymfony-2.7

Is it possible to add custom global Symfony2 route variables like _format and _locale?


In my Symfony2 project, I have a news site which has posts. Those posts can be published in different regions. The current region (user choice) has to be part of the url. So the URLs should look like this:

/mag => main news site, no region selection
/mag/region1/ => posts for region 1
/mag/region2/ => ...
/mag/region1/my-news-post-slug => detail view of one post

For the news posts, I used the Sonata News Bundle.

Now my question is, how do I add the region choice of the user to the route system without having to change each controller and template of the bundles I use? When I just add it to the routing config like

magazin:
    resource:   '@SonataNewsBundle/Resources/config/routing/news.xml'
    prefix:     /mag/{region}

I get a errors because this parameter is not set when generating the route in the controllers and templates of the news bundle (and others). I need something like the {_format} or {_locale} route variables which are already added by routing component obviously. Is it possible to add "global" values like that?


Solution

  • Take a look at how Symfony does this with locale.

    https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/HttpKernel/EventListener/LocaleListener.php

    They use an event listener to capture the locale from the request parameters and add it to the router's context parameters.