#i18n #rocket #gettext #internationalization #localization

rocket_i18n

Rocket fairing for easy internationalization with gettext (also supports Actix web)

5 unstable releases

0.4.1 Jun 15, 2019
0.4.0 Jan 20, 2019
0.3.1 Nov 30, 2018
0.3.0 Nov 29, 2018
0.1.0 Jun 17, 2018

#44 in Internationalization (i18n)

Download history 55/week @ 2019-07-06 2/week @ 2019-07-13 5/week @ 2019-07-27 19/week @ 2019-08-03 7/week @ 2019-08-10 10/week @ 2019-08-17 97/week @ 2019-08-24 13/week @ 2019-08-31 16/week @ 2019-09-07 20/week @ 2019-09-14 18/week @ 2019-09-21 20/week @ 2019-09-28 5/week @ 2019-10-05 4/week @ 2019-10-12

289 downloads per month

GPL-3.0 license

16KB
116 lines

Rocket I18N Build Status

A crate to help you internationalize your Rocket or Actix Web applications.

It just selects the correct locale for each request, and return the corresponding gettext::Catalog.

Usage

First add it to your Cargo.toml:

[dependencies]
rocket_i18n = "0.4"
gettext-macros = "0.1" # Provides proc-macros to manage translations

Then, in your main.rs:

# use rocket;
use gettext_macros::{compile_i18n, include_i18n, init_i18n};

init_i18n!("my_web_app", en, eo, it, pl);

fn main() {
    rocket::ignite()
        // Make Rocket manage your translations.
        .manage(include_i18n!());
        // Register routes, etc
}

compile_i18n!();

Then in all your requests you'll be able to use the i18n macro to translate anything. It takes a gettext::Catalog and a string to translate as argument.

use gettext_macros::i18n;
use rocket_i18n::I18n;

#[get("/")]
fn route(i18n: I18n) -> &str {
    i18n!(i18n.catalog, "Hello, world!")
}

For a detailed explanation about i18n!, see its documentation.

You can also use the t macro in your templates, as long as they have a field called catalog to store your catalog. This is especially useful for Askama templates.

Using with Actix Web

First, disable the default features so it doesn't pull in all of Rocket.

[dependencies.rocket_i18n]
version = "0.4"
default-features = false
features = ["actix-web"]

Then add it to your application.

use gettext_macros::*;
use rocket_i18n::{I18n, Internationalized, Translations};

fn route_handler(i18n: I18n) -> &str {
    i18n!(i18n.catalog, "Hello, world!")
}

#[derive(Clone)]
struct MyState {
    translations: Translations,
}

impl Internationalized for MyState {
    fn get(&self) -> Translations {
        self.translations.clone()
    }
}

fn main() {
    let state = MyState {
        translations: rocket_i18n::i18n("your-domain", vec![ "en", "fr", "de", "ja" ]);
    };

    App::with_state(state)
        .resource("", |r| r.with(route_handler))
        .finish();
}

Dependencies

~8MB
~158K SLoC