简体   繁体   中英

How to pass a variable to routing defaults in Symfony?

I have a Symfony2 project with multiple brandings (subdomains). Each subdomain should use the same site functions and the same routes (with different hostname). Therefor I want to make the subdomain in the route path to a variable. Now it looks like:

mybundle_route:
    resource: "@MyProjectBundle/Controller/"
    type:     annotation
    prefix:   /
    host:     "{subdomain}.%base_host%"
    requirements:
        subdomain: sub1|sub2

and the routing itself works. But if I try to generate some routes (eg in twig), I get following error because no subdomain variable is set:

Some mandatory parameters are missing ("subdomain") to generate a URL for route "company_route".

I don't want to add the parameter to each path() function in the project. It works perfekt for one subdomain if I add the defaults like this:

defaults:
    subdomain: sub1

but the routes are wrong for the other subdomains. Also it doesn't work with

defaults:
    subdomain: "%subdomain%"

All I need is to pass the %subdomain% variable to the defaults or to set it somewhere in the controller constructor. But I can't find the way how it is going. I would appreciate any help.

If there is no better solution you could try to set %subdomain% parameter inside configuration file:

  1. Create subdomain_parameter.php inside config folder.
  2. Inside this file you have access to ther $container so you can manually retrieve current subdomain from the url and pass it to the container.
  3. Import subdomain_parameter.php in the config.yml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM