How to Use Service Container Parameters in your Routes
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
Sometimes you may find it useful to make some parts of your routes globally configurable. For instance, if you build an internationalized site, you'll probably start with one or two locales. Surely you'll add a requirement to your routes to prevent a user from matching a locale other than the locales you support.
You could hardcode your _locale
requirement in all your routes, but
a better solution is to use a configurable service container parameter right
inside your routing configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// src/AppBundle/Controller/MainController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
class MainController extends Controller
{
/**
* @Route("/{_locale}/contact", name="contact", requirements={
* "_locale"="%app.locales%"
* })
*/
public function contactAction()
{
// ...
}
}
You can now control and set the app.locales
parameter somewhere
in your container:
1 2 3
# app/config/config.yml
parameters:
app.locales: en|es
You can also use a parameter to define your route path (or part of your path):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// src/AppBundle/Controller/MainController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
class MainController extends Controller
{
/**
* @Route("/%app.route_prefix%/contact", name="contact")
*/
public function contactAction()
{
// ...
}
}
Now make sure that the app.route_prefix
parameter is set somewhere in your
container:
1 2 3
# app/config/config.yml
parameters:
app.route_prefix: 'foo'
Note
Just like in normal service container configuration files, if you actually
need a %
in your route, you can escape the percent sign by doubling
it, e.g. /score-50%%
, which would resolve to /score-50%
.
However, as the %
characters included in any URL are automatically encoded,
the resulting URL of this example would be /score-50%25
(%25
is the
result of encoding the %
character).
See also
For parameter handling within a Dependency Injection Class see Using Parameters within a Dependency Injection Class.