How to use Service Container Parameters in your Routes

Version: 2.1
Edit this page

Warning: You are browsing the documentation for Symfony 2.1, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

How to use Service Container Parameters in your Routes

New in version 2.1

The ability to use parameters in your routes was added in Symfony 2.1.

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 your 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:

  • YAML
  • XML
  • PHP
1
2
3
4
5
contact:
    pattern:  /{_locale}/contact
    defaults: { _controller: AcmeDemoBundle:Main:contact }
    requirements:
        _locale: %acme_demo.locales%

You can now control and set the acme_demo.locales parameter somewhere in your container:

  • YAML
  • XML
  • PHP
1
2
3
# app/config/config.yml
parameters:
    acme_demo.locales: en|es

You can also use a parameter to define your route pattern (or part of your pattern):

  • YAML
  • XML
  • PHP
1
2
3
some_route:
    pattern:  /%acme_demo.route_prefix%/contact
    defaults: { _controller: AcmeDemoBundle:Main:contact }

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%.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.