Search code examples
phpinternationalizationlithiumphp-5.5

Lithium routes with different locales


I have a i18n route in Li3 that looks like:

Router::connect('/{:locale:[a-z]{2}/{:args}', [], [
    'continue' => true,
    'persist' => ['locale'],
]);

This way, when a user (or a crawler) enters my site with a language prefix, the locale is used to generate every link on the site.

For SEO purposes, I need to generate URLs in other locales such as:

GET /en/profile/john-doe
Canonical URL: https://www.example.com/en/profile/john-doe
Link hreflang for es: https://www.example.com/es/profile/john-doe
Link hreflang for pt: https://www.example.com/pt/profile/john-doe

My currency approach is cloning the current request, changing the locale, removing locale from the persist array, and using $request->to('url', ['absolute' => true]);.

But I can't get rid of the locale.

Any suggestions on how to address this?


Solution

  • I finally solved it extending HTML helper class:

    use lithium\template\helper\Html as BaseHtml;
    
    class Html extends BaseHtml
    {
        /**
         * Returns href lang link for a locale for the current request.
         *
         * @param string $locale
         * @return string <link />
         */
        public function getHrefLinkForLocale($locale)
        {
            return $this->link(
                'Canonical URL for ' . $locale,
                compact('locale') + $this->getRequest()->params,
                [
                    'absolute' => true,
                    'rel' => 'alternate',
                    'type' => 'alternate',
                    'hreflang' => $locale,
                ]
            );
        }
    }