nowiko
nowiko

Reputation: 2557

Set default locale with routing in Symfony 2

I configure my main route in routing.yml like this:

geekhub_main:
resource: "@GeekhubMainBundle/Resources/config/routing.yml"
prefix:   /{_locale}
defaults: { _locale: en }
requirements:
    _locale: en|uk

As described here Symfony2 docs, but when I go do the some page without locale, like example.com/posts instead of example.com/en/posts I get an error about No route found for ...

So what I am doing wrong?

There is a related post here stackoverflow post, but I suppose defaults way better than _locale: |en|uk ?

Upvotes: 1

Views: 980

Answers (1)

acontell
acontell

Reputation: 6922

As you can read in the documentation:

Of course, you can have more than one optional placeholder (e.g. /blog/{slug}/{page}), but everything after an optional placeholder must be optional. For example, /{page}/blog is a valid path, but page will always be required (i.e. simply /blog will not match this route).

If you have _locale as a prefix, the router will require that you add it always (even though you added a default value).

If instead of a prefix, your route looked like this:

_test:
    path: /test/{_locale}
    defaults: { _controller: AcmeDemoBundle:Demo:contact, _locale: en }
    requirements:
        _locale: en|uk

/test would work and /test/en would work.

So, using prefixes, I think that the better and more elegant approach would be defining multiple patterns:

_test:
  path:   /test
  defaults: { _controller: AcmeDemoBundle:Demo:contact, _locale: en }

_test_:
  path:   /{_locale}/test
  defaults:  { _controller: AcmeDemoBundle:Demo:contact}
  requirements:
      _locale:  en|uk

test would work and /en/test too.

The solution of:

requirements:
   _locale:  |en|uk

is not a good option due to the fact that //test would be a valid URL.

Upvotes: 2

Related Questions