In this example, the default language of the website is English (en), and we will add some French (fr) components.
1. In your application configuration (protected/config/main.php), set the sourceLanguage parameter to English:
return array(
...
, 'sourceLanguage'=>'en'
...
)
2. In a view, use the
Yii::t()
function to translate strings:
echo Yii::t('strings','the quick brown fox jumped over the lazy dog').'<br/>';
echo Yii::t('strings','you have {count} new emails', array('{count}'=>5)).'<br/>';
echo Yii::t('strings','n==1#one book|n>1#many books', array(2)).'<br/>';
The return value will default to the English value in the quotes, but if the appropriate translation file is found, then the translated value will be returned. Note the use of {parameters}. You can also format dates and numbers:
echo Yii::app()->dateFormatter->formatDateTime(time()).'<br/>';
echo Yii::app()->numberFormatter->formatDecimal(3.14);
3. Add a folder "fr" under /protected/messages, and a file called "strings.php". The content of strings.php should be this:
<?php
return array(
'the quick brown fox jumped over the lazy dog' => 'le renard marron agile saute par dessus le chien paresseux'
, 'you have {count} new emails' => 'vous avez {count} nouveaux e-mails'
, 'n==1#one book|n>1#many books '=> 'n==1#un livre|n>1#de nombreux livres'
);
?>
It's an associative array where the first value is the key, and the second value is the translated version. It's easier just to use the English value as the key than to use a numbering system.
Then, you can set the language. This is best done in the beginRequest event handler based on user preferences, but here's how to do it manually:
Yii::app()->language='fr';
Here are the results in 'en':
the quick brown fox jumped over the lazy dog
you have 5 new emails
many books
Dec 17, 2010 11:27:23 PM
3.14
and 'fr':
le renard marron agile saute par dessus le chien paresseux
vous avez 5 nouveaux e-mails
de nombreux livres
17 déc. 2010 23:24:12
3,14
4. You can also create views specific to a language. Under protected/views/site/, create a 'fr' folder, and add a page index.php . This will be the French index page for the site, and can be entirely different from the English index page if you desire.