Easy to use I18n for Rust
Go to file
franklinblanco 2a79df726c Update 'build.rs' 2023-04-26 22:31:03 +00:00
.github/workflows Create rust.yml 2020-07-07 07:39:52 +02:00
locales Add vars interpolation 2019-10-09 17:34:37 +02:00
src Update README 2019-11-14 15:40:52 +01:00
.gitignore Base files 2019-10-03 10:56:22 +02:00
.travis.yml Config Travis 2019-10-09 05:00:00 +02:00
Cargo.toml Update 'Cargo.toml' 2023-04-26 22:26:25 +00:00
LICENSE-APACHE Base files 2019-10-03 10:56:22 +02:00
LICENSE-MIT Base files 2019-10-03 10:56:22 +02:00
README.md Update README 2019-11-14 15:40:52 +01:00
build.rs Update 'build.rs' 2023-04-26 22:31:03 +00:00

README.md

Locales

Crates.io Version LICENSE Coverage Status Build Status

A simple compile time i18n implementation in Rust. It throws a compilation error if the translation key is not present, but since the lang argument is dynamic it will panic if the language has not been added for the matching key.

API documentation https://crates.io/crates/locales

Usage

Have a locales/ folder somewhere in your app, root, src, anywhere. with .json files, nested in folders or not. It uses a glob pattern: **/locales/**/*.json to match your translation files. the files must look like this:

{
  "err.user.not_found": {
    "fr": "Utilisateur introuvable: $email, $id",
    "en": "User not found: $email, $id"
  },
  "err.answer.all": {
    "fr": "Échec lors de la récupération des réponses",
    "en": "Failed to retrieve answers"
  },
  "err.answer.delete.failed": {
    "fr": "Échec lors de la suppression de la réponse",
    "en": "Failed to delete answer"
  }
}

Any number of languages can be added, but you should provide them for everything since it will panic if a language is not found when queried for a key. In your app, just call the t! macro

use locales::t;

fn main() {
    let lang = "en";
    let res = t!("err.not_allowed", lang);
    assert_eq!("You are not allowed to do this", res);
}

If the key is missing, your code will not compile

use locales::t;

fn main() {
    let lang = "en";
    let res = t!("missing key", lang);
    // Code will not compile
}

You can use interpolation, any number of argument is OK but you should note that they have to be sorted alphabetically. To use variables, call the t! macro like this:

use locales::t;

fn main() {
    let lang = "en";
    let res = t!("err.user.not_found", email: "me@localhost", id: "1", lang);

    assert_eq!("User not found: me@localhost, ID: 1", res);
}

Installation

Locales is available on crates.io, include it in your Cargo.toml:

[dependencies]
locales = "0.1.0"

Then include it in your code like this:

#[macro_use]
extern crate locales;

Or use the macro where you want to use it:

use locales::t;

Note

Locales will not work if no PWD env var is set at compile time. It should work out of the box though

License: MIT/Apache-2.0