15
votes

Here's what I want to achieve, followed by a compilation of the knowledge I acquired, with no solution.

In a Symfony2 project, without using a dedicated bundle, I want the first directory in path to define the locale. It must be optional:

As I will have over 100 routes at the end of the project, and considering that locales can be added any time, i need all the locale routing to be written only once.

No chance to achieve that with one routing file. An interesting solution from SF2.1 was the chained routing files, explained by Fabien Potencier himself: one file prefixes the locales and chains to the normal routing. Here we are:

The first file, lists non-locale-aware routes and chains to the locale-aware routing file for all other, normal routes.

-- routing.yml:

sys_ajax:
  resource: "@SystemAjax/InternalAjax/get"
  prefix:   /sysajax

locale_routing:
  resource: base_routing.yml
  prefix: /{_locale}
  defaults:
    _locale: fr

-- base_routing.yml:

user:
  resource: "@UserBundle/Resources/config/routing.yml"
  prefix:   /user

@BTUserBundle/Resources/config/routing.yml is a normal bundle routing file.

Ok, so that works for URLs with locale in path (examples 2 and 3), but no route is found if i remove the optional locale part (example 1). It's easy to guess that the problem comes from the {_locale} token capturing the "user" part of the URL as a locale when there is no locale string in URL. But then how can i tell it to let the URL untouch and chain it to the next file if the first part of the URL is not en|fr|it|de for example?

A solution from a forum was to make 2 routes:

-- routing.yml:

sys_ajax:
  resource: "@SystemAjax/InternalAjax/get"
  prefix:   /sysajax

locale_routing:
  resource: base_routing.yml
  prefix: /{_locale}
  requirements:
    _locale: fr|en

locale_routing2:
  resource: base_routing.yml
  prefix: /
  defaults:
    _locale: fr

One rule has the locale part, one has not. Unfortunately that doesn't work because there's twice the line resource: base_routing.yml (one for each rule), the later overriding the former.

Here i am, no good solution...

I love Symfony (since 2008) but sometimes I'm just amazed how simple problems can require very complex solution with this framework.

1
Regardless that having multiple urls with the same content is bad for SEO, i'm interested in this question too :)alex88
I'm also looking for a solution to this problem and can't believe no one has come up with anything so far.Tom

1 Answers

-1
votes

You could always tackle it from the other direction and use a decent editor with macros to write the routing files. Hardly any manual labor and you will achieve what you want. Modifying it will be simple with regex replace and/or a macro.