# tinyi18n-rs

tinyi18n-rs is a tiny i18n library for Rust that loads `{langKey: langValue}` style JSON language maps. It is modeled after [vue-i18n](https://kazupon.github.io/vue-i18n/), enabling interoperability of the same language files in Rust backends and Vue frontends. It is a port of [go-i18n](https://github.com/knadh/go-i18n).

## Usage

### Sample JSON language file

A JSON language file is a simple map of `key: value` pairs. Singular/plural terms are represented as `Singular|Plural`. `_.code` and `_.name` are optional metadata fields. Check [listmonk translations](https://github.com/knadh/listmonk/tree/master/i18n) for complex examples.

```json
{
    "_.code": "en",
    "_.name": "English",

    "pageTitle": "Welcome to the page",
    "page": "Single page|Many pages",
    "greeting": "Hi {name}. Your age is {age}."
}
```

### Example

```rust
use tinyi18n_rs::I18n;

fn main() -> Result<(), tinyi18n_rs::Error> {
    // If name and code args aren't passed, they're infered from _.code and _.name fields in JSON.
    let i = I18n::from_file("en.json", None, None)?;

    // Simple translation.
    println!("{}", i.t("pageTitle")); // Welcome to the page

    // Singular/plural.
    println!("{}", i.t("page"));      // Single page
    println!("{}", i.s("page"));      // Single page
    println!("{}", i.p("page"));      // Many pages
    println!("{}", i.tc("page", 1));  // Single page
    println!("{}", i.tc("page", 2));  // Many pages

    // Parameter substitution with any type via .to_string().
    println!("{}", i.ts("greeting", &[
        ("name", "Alice".into()),
        ("age", 30.to_string())
    ]));
    // Hi Alice. Your age is 30.

    Ok(())
}
```

### Nested translations

Param values can reference other translation keys using the `{key}` syntax:

```json
{
    "app.name": "MyApp",
    "welcome": "Welcome to {appName}"
}
```

```rust
i.ts("welcome", &[("appName", "{app.name}".into())]);
// Welcome to MyApp
```

## License

Licensed under the MIT license.
