中文 (简体)
Fork Me on GitHub

I18n Support

You have learned that there is an src/locales/ directory that stores language packs, here I will give you more details about locales and show you how to use it.

Create Language Pack

You just need to create a .json or .jsonc file in src/locale/, the file is named according to RFC 1766 standard, e.g. en-US, zh-CN, ko, and contains statements and translations.

Language Pack Example

// en-US.json
{
    "Hello, World!": "Hello, World!",
    "This is my first sfn application.": "This is my first sfn application."
}

As for default language, it's not necessary to translate.

// en-US.json
{
    "Hello, World!": "",
    "This is my first sfn application.": ""
}

Setting Up Default Language

In file config.ts, setting config.lang to change the default language that the application uses:

export default <app.Config>{
    // ...
    lang: "en-US",
    // ...
};

I18n in Service

In a service that extends the base Service class (like HttpController, WebSocketController, etc), you can use the method i18n() to load the proper translation according to the statement.

Example of Using i18n()

import { HttpController, route } from "sfn";

export default class extends HttpController {
    @route.get("/")
    index() {
        return this.i18n("Hello, World!");
    }
}

In an HttpController or WebSocketController, the framework will automatically check what language the client supports.

In a HttpController, these fields will be checked in the following sequence:

In a WebSocketController, these fields will be checked in the following sequence:

Apart from auto-checking, you can always set a specified language name in the service definition.

import { HttpController, route } from "sfn";

export default class extends HttpController {
    lang = "ko";

    @route.get("/")
    index() {
        return this.i18n("Hello, World!"); // => 안녕, 세상!
    }
}

If none of these properties are set, the default language will be used.

I18n in Templates

In a template (a.k.a view file), you can use the function i18n() to get translations instead.

<p>
    <%= i18n("This is an example"); %>
</p>

Other Details

Formating Output

If the request statement doesn't exist in the language pack, it will be output as-is. Like console.log(), you can set placeholders like %s, %d, etc. in the statement, and pass replacements to the rest arguments of i18n().

i18n("This is an %s.", "example"); // => This is an example.

Language Alias

Different clients may send different language symbols, for instance, MacOS will send zh for Chinese, however, most of the times we use zh-CN (including the language pack filename). To solve this problem, SFN v0.6 introduced language alias support, or you need to do is just add an $alias property to the language pack.

// locales/zh-CN.json
{
    "$alias": "zh,zh-hans,chinese-simplified"
}