69 lines
1.9 KiB
Markdown
Raw Normal View History

2017-10-11 17:06:45 +02:00
# Internationalization
2018-12-23 13:14:13 +02:00
See the [internationalization' concepts](../concepts/concepts.md#internationalization-and-localization) for details.
2017-10-11 17:06:45 +02:00
Because an API may need to send different data based on the language of the user, Strapi provides a built-in strategy to handle the internationalization (i18n).
## Usage
The `i18n` method that will allow you to retrieve the right string based on the language is accessible through the request's context.
2017-10-11 17:06:45 +02:00
There are many strategies to define the language that the server should use to return the correct translation. It can be based on the `locale` query parameter, the `cookie` or the `Accept-Language` header.
- Query: Add the `locale` parameter in the URL `GET /hello/John?locale=en_US`.
- Cookie: Set the `locale` field in the cookie `locale=en\-US;`.
- Header: Set the `Accept-Language` header with the value `en_US`.
2019-11-07 12:05:39 +01:00
::: tip
2018-12-14 11:31:41 +01:00
Please refer to the [language configuration](../configurations/configurations.md#language)
:::
2017-10-11 17:06:45 +02:00
#### Example
Let's say we want to say `Hello John` in english and `Bonjour Tom` in french. We need to use the built-in `i18n` feature and replace the string based on the received name.
2017-10-11 17:06:45 +02:00
**Path —** `./api/hello/config/routes.json`.
2019-07-24 16:28:38 +02:00
2017-10-11 17:06:45 +02:00
```json
{
"routes": [
{
"method": "GET",
"path": "/hello/:name",
"handler": "Hello.sayHello"
}
]
}
```
**Path —** `./api/hello/controllers/Hello.js`.
2019-07-24 16:28:38 +02:00
2017-10-11 17:06:45 +02:00
```js
module.exports = {
// GET /hello/:name
2019-07-24 16:28:38 +02:00
sayHello: async ctx => {
2017-10-11 17:06:45 +02:00
ctx.send(ctx.i18n.__('Hello %s', ctx.params.name));
2019-07-24 16:28:38 +02:00
},
2017-10-11 17:06:45 +02:00
};
```
You need to define the english and french translation for this key.
**Path —** `./config/locales/en_US.json`.
2019-07-24 16:28:38 +02:00
2017-10-11 17:06:45 +02:00
```json
{
2018-01-22 11:08:05 +07:00
"Hello %s": "Hello %s"
2017-10-11 17:06:45 +02:00
}
```
**Path —** `./config/locales/fr_FR.json`.
2019-07-24 16:28:38 +02:00
2017-10-11 17:06:45 +02:00
```json
{
2018-01-22 11:08:05 +07:00
"Hello %s": "Bonjour %s"
2017-10-11 17:06:45 +02:00
}
```
That's all! The request `GET /hello/John?locale=en_US` will return `Hello John` and `GET /hello/Tom?locale=fr_FR` will return `Bonjour Tom`.