Page::url() should return translated url?

Page::url() should return translated url? If not, how can I get the page url by name in the desired locale?

Hi @Cryden

Do you mean RainLab.Pages Page or a CMS module Page?

CMS module Page. there Page - October CMS

No, this won’t translate the URL since it accesses the router directly.

The CMS is unaware of the translation feature since it is introduced by the RainLab.Translate plugin. This works by hooking the Page object and changing its URL – something unrelated to the router.

The Translate plugin will need to provide an interface for this. Something like this

// RainLab\Translate\Classes\Locale

public static function transUrl($name, $params = [], $locale = null)
{
    if (empty($name) || !$page = \Cms\Classes\Page::find($name)) {
        return null;
    }

    if (!$locale) {
        $locale = static::getSiteLocaleFromContext();
    }

    $url = array_get($this->model->attributes, 'viewBag.localeUrl.'.$locale, $page->url);

    $router = new \October\Rain\Router\Router;

    $path = $router->urlFromPattern($urlPattern, $params);

    return \Cms::url($path);
}

I don’t know if it works, but its a start…

We’ve added this in RainLab Translate v2.2

Translator::instance()->getPageInLocale($name, $locale, $params);

Along with updates to the README:

Translating URLs in Twig

The localeUrl method will replace the route prefix on a URL from one locale to another. For example, converting the current request URL from en to de.

{{ this.request.url|localeUrl('de') }}

The localePage will return a translated URL for a CMS page. It takes a locale (first argument) and page parameters (second argument).

{{ 'blog/post'|localePage('de', { slug: 'foobar' }) }}
1 Like