[英]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
's host
parameter to declare the domain each page belongs to:我想在一个 Symfony 4 应用程序中托管 2 个不同的域,所以我使用@Route
的host
参数来声明每个页面所属的域:
/**
* @Route("/foo", name="foo", host="example.com")
*/
This works fine;这很好用; however, for my local dev server, I will typically use a domain like example.dev
instead.但是,对于我的本地开发服务器,我通常会使用example.dev
类的域。 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.这适用于路由,但不适用于 URL 生成。 For example, if a Twig template attempts to use {{ path('foo') }}
, I now get the following error:例如,如果 Twig 模板尝试使用{{ path('foo') }}
,我现在会收到以下错误:
Some mandatory parameters are missing ("ext") to generate a URL for route "foo".缺少一些必需参数(“ext”)来为路由“foo”生成 URL。
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 the ext
parameter?有没有办法为ext
参数提供全局默认值?
Found it:找到了:
/**
* @Route("/foo", name="foo", host="example.{ext}", defaults={"ext": "%ext%"})
*/
And configure the default value in config/services.yaml
:并在config/services.yaml
中config/services.yaml
默认值:
parameters:
ext: 'com'
Or better yet, use a constant:或者更好的是,使用常量:
parameters:
ext: '%env(DOMAIN_EXT)%'
And define it in your .env
and/or .env.local
as needed:并根据需要在.env
和/或.env.local
定义它:
DOMAIN_EXT=com
It may be even better to allow the whole host to be configurable.允许整个主机可配置可能会更好。 In this case, it looks like:在这种情况下,它看起来像:
/**
* @Route("/foo", name="foo", host="%domain.name%")
*/
And as above, configure the domain name in config/services.yaml
, with or without a constant:和上面一样,在config/services.yaml
配置域名,有或没有常量:
parameters:
domain.name: '%env(DOMAIN_NAME)%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.