我正在尝试创建一个带有路由注释的 url。
问题是我可以编写任何大小或不同的 URL。
@Route("/{staat}/", name="showStaats",requirements={"location" = "berlin|bayern|brandenburg"})
此 URL 可以从www.example.com/berlin
和 下访问www.example.com/Berlin
。
但是,我希望它只能在www.example.com/berlin
.
我正在尝试创建一个带有路由注释的 url。
问题是我可以编写任何大小或不同的 URL。
@Route("/{staat}/", name="showStaats",requirements={"location" = "berlin|bayern|brandenburg"})
此 URL 可以从www.example.com/berlin
和 下访问www.example.com/Berlin
。
但是,我希望它只能在www.example.com/berlin
.
回答“如何制定不区分大小写的路由要求”的问题:
您可以将不区分大小写的修饰符添加到需求正则表达式,如下所示:
(?i:berlin|bayern|brandenburg)
You have "/{staat}/"
, but your requirements set "location" = ...
, these should match, so maybe that's the cause of your problem.
If you don't want to hardcode the list of states in your route, you could inject a service containter parameter with a list of states. Just see How to use Service Container Parameters in your Routes in the documentation for how to do that.
If you just want to check, whether that state is all lower-cased you could try the following requirement:
staat: "[a-z-]+"
This should match only lowercase characters and dash (e.g. for "sachsen-anhalt"). But I'm not entirely sure if this will work as the router's regex-detection is a bit quirky.
You could also create a custom Router Loader which will create routes programmatically, e.g. by fetching the list of states from a database or file.
edit:
As I wrote in my comment I would add the list of params as a Service Container parameter, e.g. %my_demo.states%
containing a list of states. I'm not sure however if this will work with annotations. So here is a quick workaround how to get it working.
In your app/config/config.yml
you append the %my_demo.states%
parameter:
my_demo:
states: ["berlin", "brandenburg", "sachsen-anhalt", ... ]
In your app/config/routing.yml
there should be something like this:
my_demobundle:
resource: "@MyDemoBundle/Controller/"
prefix: /
type: annotation
The type: annotation
and @MyDemoBundle
is the relevant part. Add the following route before this one, to make sure it takes precedence:
showStaats:
path: /{state}
defaults: { _controller: MyDemoBundle:State:index }
requirements:
state: %my_demo.states%
This will add a route which will apply before your annotations using the list of states as parameters. This is a bit crude, as you are mixing yml/annotation-based routing, but it's imo still better than cramming a list of 16 states in the annotation, not to mention its easier to maintain.