i18n.md 8.73 KB
Newer Older
1 2 3 4 5 6 7
Internationalization
====================

Internationalization (I18N) refers to the process of designing a software application so that it can be adapted to
various languages and regions without engineering changes. For Web applications, this is of particular importance
because the potential users may be worldwide.

8 9
Locale and Language
-------------------
10

11 12
There are two languages defined in Yii application: [[\yii\base\Application::$sourceLanguage|source language]] and
[[\yii\base\Application::$language|target language]].
13

14
Source language is the language original application messages are written in such as:
15

16 17 18 19 20 21 22 23 24 25 26
```php
echo \Yii::t('app', 'I am a message!');
```

> **Tip**: Default is English and it's not recommended to change it. The reason is that it's easier to find people translating from
> English to any language than from non-English to non-English.

Target language is what's currently used. It's defined in application configuration like the following:

```php
// ...
Alexander Makarov committed
27
return [
28 29 30 31 32 33 34 35 36 37 38
	'id' => 'applicationID',
	'basePath' => dirname(__DIR__),
	'language' => 'ru_RU' // ← here!
```

Later you can easily change it in runtime:

```php
\Yii::$app->language = 'zh_CN';
```

39 40 41
> **Note**: please refer to [ICU documentation](http://userguide.icu-project.org/locale) in order to find out language
> and country codes for your case.

42 43 44
Basic message translation
-------------------------

45
Yii basic message translation in its basic variant works without additional PHP extension. What it does is finding a
Alexander Makarov committed
46
translation of the message from source language into target language. Message itself is specified as the second
47
`\Yii::t` method parameter:
Alexander Makarov committed
48 49 50 51

```php
echo \Yii::t('app', 'This is a string to translate!');
```
52

Qiang Xue committed
53
Yii tries to load appropriate translation from one of the message sources defined via `i18n` component configuration:
54

55
```php
Alexander Makarov committed
56
'components' => [
57
	// ...
Alexander Makarov committed
58 59 60
	'i18n' => [
		'translations' => [
			'app*' => [
61 62
				'class' => 'yii\i18n\PhpMessageSource',
				//'basePath' => '@app/messages',
63
				//'sourceLanguage' => 'en-US',
Alexander Makarov committed
64
				'fileMap' => [
65 66
					'app' => 'app.php',
					'app/error' => 'error.php',
Alexander Makarov committed
67 68 69 70 71
				],
			],
		],
	],
],
72 73 74 75 76
```

In the above `app*` is a pattern that specifies which categories are handled by the message source. In this case we're
handling everything that begins with `app`.

Alexander Makarov committed
77
`class` defines which message source is used. The following message sources are available:
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

- PhpMessageSource that uses PHP files.
- GettextMessageSource that uses GNU Gettext MO or PO files.
- DbMessageSource that uses database.

`basePath` defines where to store messages for the currently used message source. In this case it's `messages` directory
 in your application directory. In case of using database this option should be skipped.

`sourceLanguage` defines which language is used in `\Yii::t` second argument. If not specified, application's source
language is used.

`fileMap` specifies how message categories specified in the first argument of `\Yii::t()` are mapped to files when
`PhpMessageSource` is used. In the example we're defining two categories `app` and `app/error`.

Instead of configuring `fileMap` you can rely on convention which is `messages/BasePath/LanguageID/CategoryName.php`.
93 94 95

### Named placeholders

96 97 98
You can add parameters to a translation message that will be substituted with the corresponding value after translation.
The format for this is to use curly brackets around the parameter name as you can see in the following example:

99 100
```php
$username = 'Alexander';
Alexander Makarov committed
101
echo \Yii::t('app', 'Hello, {username}!', [
102
	'username' => $username,
Alexander Makarov committed
103
]);
104 105
```

106 107
Note that the parameter assignment is without the brackets.

108 109 110 111 112 113 114
### Positional placeholders

```php
$sum = 42;
echo \Yii::t('app', 'Balance: {0}', $sum);
```

Alexander Makarov committed
115 116
> **Tip**: Try keep message strings meaningful and avoid using too many positional parameters. Remember that
> translator has source string only so it should be obvious about what will replace each placeholder.
117 118 119 120 121 122 123 124 125 126

Advanced placeholder formatting
-------------------------------

In order to use advanced features you need to install and enable [intl](http://www.php.net/manual/en/intro.intl.php) PHP
extension. After installing and enabling it you will be able to use extended syntax for placeholders. Either short form
`{placeholderName, argumentType}` that means default setting or full form `{placeholderName, argumentType, argumentStyle}`
that allows you to specify formatting style.

Full reference is [available at ICU website](http://icu-project.org/apiref/icu4c/classMessageFormat.html) but since it's
Alexander Mohorev committed
127
a bit cryptic we have our own reference below.
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

### Numbers

```php
$sum = 42;
echo \Yii::t('app', 'Balance: {0, number}', $sum);
```

You can specify one of the built-in styles (`integer`, `currency`, `percent`):

```php
$sum = 42;
echo \Yii::t('app', 'Balance: {0, number, currency}', $sum);
```

Or specify custom pattern:

```php
$sum = 42;
echo \Yii::t('app', 'Balance: {0, number, ,000,000000}', $sum);
```

[Formatting reference](http://icu-project.org/apiref/icu4c/classicu_1_1DecimalFormat.html).

### Dates

```php
echo \Yii::t('app', 'Today is {0, date}', time());
```

Built in formats (`short`, `medium`, `long`, `full`):

```php
echo \Yii::t('app', 'Today is {0, date, short}', time());
```

Custom pattern:

```php
echo \Yii::t('app', 'Today is {0, date, YYYY-MM-dd}', time());
```

[Formatting reference](http://icu-project.org/apiref/icu4c/classicu_1_1SimpleDateFormat.html).

### Time

```php
echo \Yii::t('app', 'It is {0, time}', time());
```

Built in formats (`short`, `medium`, `long`, `full`):

```php
echo \Yii::t('app', 'It is {0, time, short}', time());
```

Custom pattern:

```php
echo \Yii::t('app', 'It is {0, date, HH:mm}', time());
```

[Formatting reference](http://icu-project.org/apiref/icu4c/classicu_1_1SimpleDateFormat.html).


### Spellout

```php
Alexander Makarov committed
196
echo \Yii::t('app', '{n,number} is spelled as {n, spellout}', ['n' => 42]);
197 198 199 200 201
```

### Ordinal

```php
Alexander Makarov committed
202
echo \Yii::t('app', 'You are {n, ordinal} visitor here!', ['n' => 42]);
203 204 205 206 207 208 209 210
```

Will produce "You are 42nd visitor here!".

### Duration


```php
Alexander Makarov committed
211
echo \Yii::t('app', 'You are here for {n, duration} already!', ['n' => 47]);
212 213 214 215 216 217 218 219 220 221 222
```

Will produce "You are here for 47 sec. already!".

### Plurals

Different languages have different ways to inflect plurals. Some rules are very complex so it's very handy that this
functionality is provided without the need to specify inflection rule. Instead it only requires your input of inflected
word in certain situations.

```php
Alexander Makarov committed
223
echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);
224 225 226 227 228 229 230 231 232 233 234 235 236 237
```

Will give us "There are no cats!".

In the plural rule arguments above `=0` means exactly zero, `=1` stands for exactly one `other` is for any other number.
`#` is replaced with the `n` argument value. It's not that simple for languages other than English. Here's an example
for Russian:

```
Здесь {n, plural, =0{котов нет} =1{есть один кот} one{# кот} few{# кота} many{# котов} other{# кота}}!
```

In the above it worth mentioning that `=1` matches exactly `n = 1` while `one` matches `21` or `101`.

238 239 240 241 242 243 244
Note that if you are using placeholder twice and one time it's used as plural another one should be used as number else
you'll get "Inconsistent types declared for an argument: U_ARGUMENT_TYPE_MISMATCH" error:

```
Total {count, number} {count, plural, one{item} other{items}}.
```

Qiang Xue committed
245
To learn which inflection forms you should specify for your language you can referrer to
246 247 248 249 250 251 252 253
[rules reference at unicode.org](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html).

### Selections

You can select phrases based on keywords. The pattern in this case specifies how to map keywords to phrases and
provides a default phrase.

```php
Alexander Makarov committed
254
echo \Yii::t('app', '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', [
255 256
	'name' => 'Snoopy',
	'gender' => 'dog',
Alexander Makarov committed
257
]);
258 259 260 261 262 263 264
```

Will produce "Snoopy is dog and it loves Yii!".

In the expression `female` and `male` are possible values. `other` handler values that do not match. Strings inside
brackets are sub-expressions so could be just a string or a string with more placeholders.

Mark committed
265 266 267 268 269
Views
-----

You can use i18n in your views to provide support for different languages. For example, if you have view `views/site/index.php` and
you want to create special case for russian language, you create `ru-RU` folder under the view path of current controller/widget and
Mark committed
270
put there file for russian language as follows `views/site/ru-RU/index.php`.
Mark committed
271

Mark committed
272
> **Note**: You should note that in **Yii2** language id style has changed, now it use dash **ru-RU, en-US, pl-PL** instead of underscore, because of
Mark committed
273 274
> php **intl** library.

275 276
Formatters
----------
277

278 279
In order to use formatters you need to install and enable [intl](http://www.php.net/manual/en/intro.intl.php) PHP
extension.
280

Qiang Xue committed
281
TBD: provided classes overview.