|
| 1 | +.. index:: |
| 2 | + single: Routing; Extra Information |
| 3 | + |
| 4 | +How to Pass Extra Information from a Route to a Controller |
| 5 | +========================================================== |
| 6 | + |
| 7 | +Parameters inside the ``defaults`` collection don't necessarily have to |
| 8 | +match a placeholder in the route ``path``. In fact, you can use the |
| 9 | +``defaults`` array to specify extra parameters that will then be accessible as |
| 10 | +arguments to your controller: |
| 11 | + |
| 12 | +.. configuration-block:: |
| 13 | + |
| 14 | + .. code-block:: yaml |
| 15 | +
|
| 16 | + # app/config/routing.yml |
| 17 | + blog: |
| 18 | + path: /blog/{page} |
| 19 | + defaults: |
| 20 | + _controller: AcmeBlogBundle:Blog:index |
| 21 | + page: 1 |
| 22 | + title: "Hello world!" |
| 23 | +
|
| 24 | + .. code-block:: xml |
| 25 | +
|
| 26 | + <!-- app/config/routing.xml --> |
| 27 | + <?xml version="1.0" encoding="UTF-8" ?> |
| 28 | + <routes xmlns="http://symfony.com/schema/routing" |
| 29 | + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 30 | + xsi:schemaLocation="http://symfony.com/schema/routing |
| 31 | + http://symfony.com/schema/routing/routing-1.0.xsd"> |
| 32 | +
|
| 33 | + <route id="blog" path="/blog/{page}"> |
| 34 | + <default key="_controller">AcmeBlogBundle:Blog:index</default> |
| 35 | + <default key="page">1</default> |
| 36 | + <default key="title">Hello world!</default> |
| 37 | + </route> |
| 38 | + </routes> |
| 39 | +
|
| 40 | + .. code-block:: php |
| 41 | +
|
| 42 | + // app/config/routing.php |
| 43 | + use Symfony\Component\Routing\RouteCollection; |
| 44 | + use Symfony\Component\Routing\Route; |
| 45 | +
|
| 46 | + $collection = new RouteCollection(); |
| 47 | + $collection->add('blog', new Route('/blog/{page}', array( |
| 48 | + '_controller' => 'AcmeBlogBundle:Blog:index', |
| 49 | + 'page' => 1, |
| 50 | + 'title' => 'Hello world!', |
| 51 | + ))); |
| 52 | +
|
| 53 | + return $collection; |
| 54 | +
|
| 55 | +Now, you can access this extra parameter in your controller:: |
| 56 | + |
| 57 | + public function indexAction($page, $title) |
| 58 | + { |
| 59 | + // ... |
| 60 | + } |
| 61 | + |
| 62 | +As you can see, the ``$title`` variable was never defined inside the route path, |
| 63 | +but you can still access its value from inside your controller. |
0 commit comments