I will create a simple multilingual website using the RainLab.Translate plugin. The plugin allows you to translate text lines, fields in the admin panel, email templates, theme settings, and more. All this is described in the plugin documentation.
The main language is English, the secondary language is Ukrainian. The main version will have no prefix in the URL, and the pages of the Ukrainian version will have the uk prefix (for example, web-tip.top/uk
).
1) Install the RainLab.Translate plugin and add English (en
, default language) and Ukrainian (uk
) to the settings.
2) Include the [localePicker]
and [alternateHrefLangElements]
components to the layout, and mark forceUrl
so that the Translate plugin adds a prefix to the URL:
[localePicker]
forceUrl = 1
[alternateHrefLangElements]
3) In the place where you want to display the language picker, insert:
<a href="#" data-request="onSwitchLocale" data-request-data="locale: 'en'" class="{{ activeLocale == 'en' ? 'css class for active switch' : '' } }">EN</a>
<a href="#" data-request="onSwitchLocale" data-request-data="locale: 'uk'" class="{{ activeLocale == 'uk' ? 'css class for active switch' : '' } }">UA</a>
4) Add the locale to the html tag:
<html lang="{{ activeLocale ?: 'en' }}" translate="no" dir="ltr">
5) In the head, we display the alternate links:
{% component 'alternateHrefLangElements' %}
6) In .env, add TRANSLATE_PREFIX_LOCALE (disable the forced addition of a prefix for the default language):
TRANSLATE_PREFIX_LOCALE=false
In the old version of RainLab.Translate, this option is not included in .env, so you need to set prefixDefaultLocale in the plugin configuration (plugins/rainlab/translate/config/config.php) to false.
7) In php code section add code that will remove prefix from url (301 redirect to url without prefix), if someone will add it manually:
function onStart(){
if($this->removeDefaultLocalePrefixFromUrl()){
return Redirect::to($this->removeDefaultLocalePrefixFromUrl(), 301);
}
}
function removeDefaultLocalePrefixFromUrl(){
$translator = \RainLab\Translate\Classes\Translator::instance();
$defaultLocale = $translator->getDefaultLocale();
$url = \Request::getUri();
$root = \Request::root();
if(strpos($url, '/'.$defaultLocale.'/') !== FALSE or $url == $root.'/'.$defaultLocale){
return str_replace('/'.$defaultLocale, "", $url);
}
return false;
}
That's all!