3

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?

fedeisas
  • 1,991
  • 2
  • 22
  • 34
  • I'm pretty sure you need to do `'persist' => ['locale']`, then just override the locale in the params you pass to `$this->url()` in the view. You probably shouldn't need to re-pass all your params like you're doing in your helper. – Nate Abele Apr 28 '15 at 13:51
  • Thanks again! Yes, I'm already doing `persist => ['locale']`. This was just bad copy/paste. – fedeisas Apr 28 '15 at 17:47

1 Answers1

1

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,
            ]
        );
    }
}
fedeisas
  • 1,991
  • 2
  • 22
  • 34
  • 1
    I think in this case a helper was probably the right way to go, though I would have made a separate helper, rather than extending `Html`. – Nate Abele Apr 28 '15 at 13:40
  • Thanks @NateAbele. At first, I didn't realize I could include a `locale` along with request params. That was the trick. – fedeisas Apr 28 '15 at 13:45