php - Symfony wildcard host route with no named parameter
I want to host 2 different domains inside a single Symfony 4 application, so I'm using@Route
'shost
parameter to declare the domain each page belongs to:
/**
* @Route("/foo", name="foo", host="example.com")
*/
This works fine; however, for my local dev server, I will typically use a domain likeexample.dev
instead. So the route needs to match multiple extensions. I tried using a named placeholder for this purpose:
/**
* @Route("/foo", name="foo", host="example.{ext}")
*/
This works fine for routing, but not for URL generation. For example, if a Twig template attempts to use{{ path('foo') }}
, I now get the following error:
Some mandatory parameters are missing ("ext") to generate a URL for route "foo".
Is there a way to add a wildcard for the host, while still allowing route generation without passing a parameter?
I know the question sounds odd, as routing must be bi-directional, but how is this typically handled when one needs to have a dev environment with different domains?
Is there maybe a way to provide a global, default value for theext
parameter?
Answer
Solution:
Found it:
And configure the default value in
config/services.yaml
:Or better yet, use a constant:
And define it in your
.env
and/or.env.local
as needed:Alternative
It may be even better to allow the whole host to be configurable. In this case, it looks like:
And as above, configure the domain name in
config/services.yaml
, with or without a constant: