Translatable Controller URLs

You can easily translate CMS content with translatable or fluent, but what if you have an url that is just grabbed by a controller?

In my case i show the weather forecast from a controller which should serve English translation when called through /weatherforecast and German when called through /wetter. Setting up the routes is easy, and there you can pass additional parameters to the controller:

      Controller: 'WeatherForecastController'
      Locale: en_US
      Controller: 'WeatherForecastController'
      Locale: de_DE

But how can i access this values in my controller? It's in the routeParams data of the current request which you get via $this->request->routeParams().

For some historical reasons my WeatherForecastController is a subclass of Page_Controller, so it has a SiteTree object with ID -1 attached, which defaults to one locale. So let's check for that in Page_Controller::init() and set the values we need:

public function init()

    $routeParams = $this->request->routeParams();
    $locale = ($this->dataRecord->ID < 1 && array_key_exists('Locale', $routeParams))
        ? $routeParams['Locale']
        : $this->dataRecord->Locale;
    Translatable::set_current_locale($locale); //we use translatable extension...
    setlocale(LC_TIME, i18n::get_locale() . ".utf8");

    //other stuff

With this settings all templates are translated accordingly and we have a param for the current locale somehow "hidden" in the URL.

To see this in action you can visit this two URLS:

Rate this post

Post your comment


No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments