中文 (简体)
Fork Me on GitHub

Internationalization Support

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

Create A Language Pack

You just need to create a .json 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 <SFNConfig>{
    // ...
    lang: "en-US",
    // ...
};

I18n in A Service

In a service (or extended services 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!");
    }
}

The framework will automatically check what language the client supports in a HttpController or WebSocketController.

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

In a WebSocketController, this 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

If the request statement doesn't exists in the language pack, it will be output as what it 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.