Rust I18n is use Rust codegen for load YAML file storage translations on compile time, and give you a t! macro for simply get translation texts.

Overview

Rust I18n

CI Docs Crates.io

Rust I18n is use Rust codegen for load YAML file storage translations on compile time, and give you a t! macro for simply get translation texts.

Inspired by ruby-i18n and Rails I18n.

Usage

Load macro in your lib.rs

// Load I18n macro, for allow you use `t!` macro in anywhere.
#[macro_use]
extern crate rust_i18n;

You must put I18n YAML files in locales/ folder.

locales/
├── en.yml
├── zh-CN.yml

For example of en.yml:

en:
  hello: Hello world
  messages:
    hello: Hello, %{name}

Now you can use t! macro in anywhere.

t!("hello");
// => "Hello world"

t!("hello", locale = "zh-CN");
// => "你好世界"

t!("messages.hello", name = "world");
// => "Hello, world"

t!("messages.hello", locale = "zh-CN", name = "Jason");
// => "你好, Jason"

You can use rust_i18n::set_locale to change the current locale in runtime.

rust_i18n::set_locale("zh-CN");
rust_i18n::locale();
// => "zh-CN"

Debug codegen

Use RUST_I18N_DEBUG environment variable to run cargo build, Rust I18n will just print the codegen result.

$ RUST_I18N_DEBUG=1 cargo build

License

MIT

Comments
  • How to set the locale

    How to set the locale

    I've

    available-locales = ["en", "de"]

    Setting a locale should be possible via autodetect - did I miss something here?

    I tried if let Ok(lang) = env::var("LANG") { rust_i18n::set_locale(&lang); }

    However that won't work on windows. How is the recommended way of setting a locale to the system setting?

    But ended up with:

    image

    enhancement 
    opened by mkrueger 3
  • Loading the translation fails with  version 1.0.1

    Loading the translation fails with version 1.0.1

    In my project, I use your package which displayed the translated texts until yesterday. Maybe there is another configuration setting missing ?

    For discovering the issue I created a separate most simple project: https://github.com/liquidnight2/test-cases/tree/main/translationtest

    
    # cat locales/en.yml
    en:
      hello : Hello_World-English!
      
      
    #  cargo run
       Compiling translationtest v0.1.0 (/mnt/stripe/workspace1/test-cases/translationtest)
        Finished dev [unoptimized + debuginfo] target(s) in 34.39s
         Running `target/debug/translationtest`
    translated=en.hello
    thread 'main' panicked at 'assertion failed: `(left == right)`
      left: `"en.hello"`,
     right: `"Hello_World-English!"`', src/main.rs:8:5
    
    
    opened by liquidnight2 2
  • Language code inference doesn't work

    Language code inference doesn't work

    Hi, I updated my project to v1.0.1 of rust-i18n and I have a problem after removing the locale code from the files.

    Here's a sample file, located at locales/en.yml:

    run:
      script-not-found: "the script `%{name}` was not found."
    

    However, when I use:

    t!("run.script-not-found", name = "hi")
    

    It comes out as en.run.script-not-found.

    I have to put:

    en:
      run:
        script-not-found: "the script `%{name}` was not found."
    

    In order to make it work properly.

    opened by SkyfallWasTaken 1
  • [BUG] Error while trying to cross compile

    [BUG] Error while trying to cross compile

    I am using this crate in my project, and when trying to cross compile with cross I get the following error: error: failed to run custom build command for rust-i18n v1.0.1

    Caused by: process didn't exit successfully: /target/release/build/rust-i18n-5c11b3d47303e377/build-script-build (exit status: 101) --- stdout cargo:rerun-if-changed=/cargo/git/checkouts/bifrost-2b7c66c891beea9d/0aeeb1e/crates/bifrost_cli/locales/en.yml cargo:rerun-if-changed=/cargo/git/checkouts/bifrost-2b7c66c891beea9d/0aeeb1e/crates/bifrost_cli/locales/es.yml cargo:rerun-if-changed=/cargo/git/checkouts/bifrost-2b7c66c891beea9d/af52f60/crates/bifrost_cli/locales/en.yml cargo:rerun-if-changed=/cargo/git/checkouts/bifrost-2b7c66c891beea9d/af52f60/crates/bifrost_cli/locales/es.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-0.6.1/examples/app/locales/en.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-0.6.1/examples/app/locales/fr.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-0.6.1/examples/app/locales/view.en.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-0.6.1/examples/app/locales/view.fr.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-1.0.1/examples/app/locales/en.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-1.0.1/examples/app/locales/fr.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-1.0.1/examples/app/locales/view.en.yml cargo:rerun-if-changed=/cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-1.0.1/examples/app/locales/view.fr.yml

    --- stderr thread 'main' panicked at 'called Result::unwrap() on an Err value: GlobError { path: "/etc/ssl/private", error: Os { code: 13, kind: PermissionDenied, message: "Permission denied" } }', /cargo/registry/src/github.com-1ecc6299db9ec823/rust-i18n-1.0.1/build.rs:33:27

    opened by MJoaaquin 0
  • Method to retrieve available languages

    Method to retrieve available languages

    A method to retrieve the available languages is needed. This is needed when displaying the language dropdown on the UI. The current workaround is to manually look inside the locales folder, but this feels like a hack.

    opened by vbocan 0
  • Take language code from filename instead of `.yml` files

    Take language code from filename instead of `.yml` files

    Before

    en: # The language code of this mapping file
      hello: Hello world # A simple key -> value mapping
      messages:
        hello: Hello, %{name} # A nested key.sub_key -> value mapping, in this case "messages.hello" maps to "Hello, %{name}"
    

    After that, there is no need to add a first-level language code to the .yml file

    hello: Hello world # A simple key -> value mapping
    messages:
      hello: Hello, %{name} # A nested key.sub_key -> value mapping, in this case "messages.hello" maps to "Hello, %{name}"
    

    This modification makes the locales .yml file more standardized, and some vscode plugins can be used directly, such as i18n-ally

    .vscode/i18n-ally-custom-framework.yml

    languageIds:
      - rust
    
    usageMatchRegex:
      - "[^\\w\\d]t!\\(['\"]({key})['\"]"
    
    monopoly: true
    

    Work for rust now!

    opened by Pure-Peace 0
  • Load locales by manually

    Load locales by manually

    For fix use I18n in deep dependencies

    rust-i18n
      Cargo.toml
      src/lib.rs
      build.rs
    
    // deps: rust-i18n
    foo
      Cargo.toml
      src/lib.rs
    
    // deps: rust-i18n, foo
    bar
      Cargo.toml
      src/lib.rs
    

    Usage:

    [dependencies]
    lazy_static = "1.4.0"
    rust-i18n = "0"
    

    Load macro and init translations in lib.rs

    // Load I18n macro, for allow you use `t!` macro in anywhere.
    #[macro_use]
    extern crate rust_i18n;
    
    // Init translations for current crate.
    i18n!("./locales");
    
    opened by huacnlee 0
  • Missing directories in examples/ in the crate.io release

    Missing directories in examples/ in the crate.io release

    Hi! Some of the directories in the examples folder are excluded from the crate.io release of the library. This reflects in the test test_load failing not finding the required files (examples/foo/Cargo.toml)

    opened by bertof 0
  • Error while trying to cross compile

    Error while trying to cross compile

    opened by MJoaaquin 3
  • [BUG] cannot find function `translate` in the crate root

    [BUG] cannot find function `translate` in the crate root

    Hello, i am trying to use this crate, but when i use the macro t, i have this error:

    error[E0425]: cannot find function `translate` in the crate root
      --> src\libs\i18n.rs:13:9
       |
    13 |   dbg!(&t!("hello"));
       |         ^^^^^^^^^^^ not found in the crate root
       |
       = note: this error originates in the macro `t` (in Nightly builds, run with -Z macro-backtrace for more info)
    help: consider importing this function
       |
    1  | use crate::i18n::translate;
       |
    
    error[E0425]: cannot find function `translate` in the crate root
      --> src\libs\i18n.rs:14:9
       |
    14 |   dbg!(&t!("hello"));
       |         ^^^^^^^^^^^ not found in the crate root
       |
       = note: this error originates in the macro `t` (in Nightly builds, run with -Z macro-backtrace for more info)
    help: consider importing this function
       |
    1  | use crate::i18n::translate;
       |
    
    

    even if the compiler tells me to import the function, it doesn't exist ! My code:

    use rust_i18n::{ i18n, t };
    use crate::utils;
    
    
    pub fn load(logs: bool){
      i18n!("locales");
      if logs {
        utils::success("i18n", "Language modules ready to use")
      }
    }
    
    pub fn test(){
      dbg!(&t!("hello"));
      dbg!(&t!("hello"));
    }
    
    opened by Sedorikku1949 8
  • Seems the `load-path`is not working properly in workspace context

    Seems the `load-path`is not working properly in workspace context

    Hi,

    My current setup is myworkspace where I an run myserver, myclient and mylib I set it in my sub project myclient but it point to myworkspce folder locales I tried to set load-path in myworkspace toml as "myclient/locales" but no avail. It still point to myworkspace folder locales

    edit: I manage to make it work if I put full absolute path into i18n!()

    Thanks

    opened by git2013vb 3
  • allow for a fallback of missing translations

    allow for a fallback of missing translations

    I might have missed it but it seems that the behaviour of missing keys is to simply show the key? Could it be possible to customize this such that we can default to another language? Might be the default language, but could also be suitable to be able to setup a chain fo fallbacks such that for example pt-BR falls back to pt which falls back to en?

    enhancement 
    opened by GlenDC 0
  • allow for value processor

    allow for value processor

    Not sure how or where I would implement it, but it would be nice if we could process our values prior to being stored in our in-memory hashmap. This could allow translators to use a minimal formatting language (e.g. markdown) so that I can store it as html snippets rather than still having to do this on the fly. I guess I could also do it manually of course, but that would mean I have the data twice.

    opened by GlenDC 0
Releases(v1.1.0)
  • v1.1.0(Jan 4, 2023)

    What's Changed

    • Add more examples. by @huacnlee in https://github.com/longbridgeapp/rust-i18n/pull/15
    • Try fix #17, when workdir can't get from OUT_DIR, fallback to CARGO_MANIFEST_DIR env. by @huacnlee in https://github.com/longbridgeapp/rust-i18n/pull/19
    • Add available_locales method to get all available locales by @huacnlee in https://github.com/longbridgeapp/rust-i18n/pull/20

    Full Changelog: https://github.com/longbridgeapp/rust-i18n/compare/v1.0.1...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Nov 18, 2022)

    Break Change

    • Take language code from filename instead of .yml files by @Pure-Peace in https://github.com/longbridgeapp/rust-i18n/pull/10

    Upgrade Guides

    $ cargo install rust-i18n --force
    

    New version of rust-i18n has not need add language code in YAML file:

    Before

    locales/en.yml

    en:
      hello: Hello world
      messages:
        hello: Hello, %{name}
    

    After

    locales/en.yml

    hello: Hello world 
    messages:
      hello: Hello, %{name}
    

    You must remove change the exist locale files.

    VS Code I18n Ally guide

    I18n Ally is a VS Code extension for helping you translate your Rust project.

    You can add i18n-ally-custom-framework.yml to your project .vscode directory, and then use I18n Ally can parse t! marco to show translate text in VS Code editor.

    SCR-20221118-lzz

    New Contributors

    • @Pure-Peace made their first contribution in https://github.com/longbridgeapp/rust-i18n/pull/10
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Nov 18, 2022)

  • v0.5.2(Apr 2, 2022)

  • v0.5.1(Dec 10, 2021)

    • Add i18n config support in Cargo.toml, now cargo i18n will use that.
    • cargo i18n has removed --locale, --output flags, instead to use I18n config.

    In your Cargo.toml:

    You can change the I18n settings.

    [package.metadata.i18n]
    # The available locales for your application, default: ["en"].
    available-locales = ["en", "zh-CN"]
    
    # The default locale, default: "en".
    default-locale = "en"
    
    # Path for your translations YAML file, default: "locales".
    load-path = "locales"
    

    After that, cargo i18n will use these settings for check and generate.

    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Dec 9, 2021)

    • Rename Command line tool as cargo i18n.
    $ cargo i18n -h
    cargo-i18n 0.4.0
    ---------------------------------------
    Rust I18n command for help you simply to extract all untranslated texts from soruce code.
    
    It will iter all Rust files in and extract all untranslated texts that used `t!` macro.
    And then generate a YAML file and merge for existing texts.
    
    https://github.com/longbridgeapp/rust-i18n
    
    USAGE:
        cargo i18n [OPTIONS] [--] [source]
    
    FLAGS:
        -h, --help       Prints help information
        -V, --version    Prints version information
    
    OPTIONS:
        -l <locale>...        Source locale [default: en]
        -o <output>           Path for output locales YAML files. [default: ./locales]
    
    ARGS:
        <source>    Path of your Rust crate root [default: ./]
    
    Source code(tar.gz)
    Source code(zip)
  • v0.3.4(Dec 9, 2021)

    • Improve t! macro for support expr arguments.
    let name = "Jason Lee";
    let locale = "en";
    
    t!("hello, %{name}", name = name);
    t!("hello, %{name}", name = &format!("{}", name));
    t!("hello, %{name}", locale = locale, name = name);
    
    Source code(tar.gz)
    Source code(zip)
  • v0.3.3(Dec 9, 2021)

    Rust I18n Cli

    Add i18n cli command for extract untranslated texts into YAML.

    Use cargo install rust-i18n to installation.

    $ cargo install rust-i18n
    $ i18n -h
    i18n 0.3.3
    Jason Lee <[email protected]>
    Rust I18n is a crate for loading localized text from a set of YAML mapping files. The mappings are converted into data
    readable by Rust programs at compile time, and then localized text can be loaded by simply calling the provided `t!`
    macro.
    
    USAGE:
        i18n [SUBCOMMAND]
    
    FLAGS:
        -h, --help       Prints help information
        -V, --version    Prints version information
    
    SUBCOMMANDS:
        extract    Extracts strings from source files
        help       Prints this message or the help of the given subcommand(s)
    

    Extract all untranslated texts

    $ cd your-project
    $ i18n extract -l en fr zh-CN zh-HK
    
    Checking [en] and generating untranslated texts...
    Found 1 new texts need to translate.
    ----------------------------------------
    Writing to TODO.en.yml
    
    Checking [fr] and generating untranslated texts...
    Found 11 new texts need to translate.
    ----------------------------------------
    Writing to TODO.fr.yml
    
    Checking [zh-CN] and generating untranslated texts...
    All thing done.
    
    Checking [zh-HK] and generating untranslated texts...
    Found 11 new texts need to translate.
    ----------------------------------------
    Writing to TODO.zh-HK.yml
    

    Now, 4 YAML files named TODO.*.yml are created into locales/ path.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Dec 6, 2021)

  • v0.2.0(Dec 6, 2021)

    BRAKE CHANGES

    Rust I18n API has rewrite, now you need use i18n! macro to load locales file by manually.

    This changes for allow I18n to support load translations from difference sub project.

    For example:

    // deps: rust-i18n
    foo
      Cargo.toml
      locales
      src/lib.rs
    
    // deps:  rust-i18n, foo
    bar
      Cargo.toml
      locales
      src/lib.rs
    
    // deps:  rust-i18n, foo and bar
    your-project:
      Cargo.toml
      locales
      src/lib.rs
    

    Is this case, Rust I18n allows foo, bar and your-project use i18n! macro to load itself's translations.

    Usage:

    // Load I18n macro, for allow you use `t!` macro in anywhere.
    #[macro_use]
    extern crate rust_i18n;
    
    // Init translations for current crate.
    i18n!("./locales");
    
    fn main() {
      println!(t!("hello"))
    }
    
    • Add i18n! macro to load translations and required this.
    • Add for support merge multiple YAML files.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.6(Dec 6, 2021)

    • Search translation resources recursively in workdir

    This is to support use cases like a crate using rust-i18n is being usedby another crate.

    Source code(tar.gz)
    Source code(zip)
  • v0.1.5(Dec 3, 2021)

  • v0.1.2(Dec 2, 2021)

  • v0.1.1(Dec 2, 2021)

  • v0.1.0(Dec 2, 2021)

Owner
Longbridge
Long Bridge Securities
Longbridge
Diana is a GraphQL system for Rust that's designed to work as simply as possible out of the box

Diana is a GraphQL system for Rust that's designed to work as simply as possible out of the box, without sacrificing configuration ability. Unlike other GraphQL systems, Diana fully supports serverless functions and automatically integrates them with a serverful subscriptions system as needed, and over an authenticated channel. GraphQL subscriptions are stateful, and so have to be run in a serverful way. Diana makes this process as simple as possible.

null 0 Aug 3, 2021
The [cain!] macro is a macro that rewrites sequential Rust branch statements into nested branches

Note! This crate is experimental and under development. It may include bugs that alter the behavior of your code in unexpected ways. You should review

Fredrik Østrem 2 Jan 19, 2022
A pure Rust implementation of the Web Local Storage API, for use in non-browser contexts

Rust Web Local Storage API A Rust implementation of the Web LocalStorage API, for use in non-browser contexts About the Web Local Storage API MDN docs

RICHΛRD ΛNΛYΛ 10 Nov 28, 2022
A secure and efficient gateway for interacting with OpenAI's API, featuring load balancing, user request handling without individual API keys, and global access control.

OpenAI Hub OpenAI Hub is a comprehensive and robust tool designed to streamline and enhance your interaction with OpenAI's API. It features an innovat

Akase Cho 30 Jun 16, 2023
lispr is a Rust macro that tries to implement a small subset of LISPs syntax in Rust

lispr lispr is a Rust macro that tries to implement a small subset of LISPs syntax in Rust. It is neither especially beautiful or efficient since it i

Jan Vaorin 0 Feb 4, 2022
Attribute macro that generates negated versions of`is_something` functions

negate negate is a simple attribute macro that negates a given function. Usage #[negate] Given a function of the form is_* that returns a boolean valu

Vinícius Miguel 9 Mar 4, 2022
Proxies all incoming connections to a minecraft server of your choosing, while also logging all ping and login requests to a json file and discord webhook.

minecraft-honeypot Proxies all incoming connections to a minecraft server of your choosing, while also logging all ping and login requests to a json f

Cleo 19 Jan 4, 2023
The simplest build-time framework for writing web apps with html templates and typescript

Encoped A build-time fast af tool to write static apps with html and TypeScript Features Template-based ESLint, Prettier and Rollup integration No ext

null 1 Dec 11, 2021
HTTP Proxy based solution for real-time interception and prioritization of SQL queries.

starproxy ⚠️ starproxy is a prototype: Not currently used in production, but will likely be some day. Table of Contents starproxy Table of Contents Ba

Will Eaton 5 Mar 6, 2023
☁ file.AsyncWrite - because THEY wont do it!!!!!! and its in RUST

☁ gm_async_write Simple module that adds file.AsyncWrite and file.AsyncAppend to Garry's Mod. These functions are mostly based off file.AsyncRead and

William 18 Dec 24, 2022
Real-time bidding API scaffold for MevWallet transactions

MevWallet RTB API This repo provides a standard interface for a real-time bidding API. Searchers run the API to provide bids to users. The bid represe

Blunt Instruments 17 Mar 23, 2023
A html document syntax and operation library written in Rust, use APIs similar to jQuery.

Visdom A server-side html document syntax and operation library written in Rust, it uses apis similar to jQuery, left off the parts thoes only worked

轩子 80 Dec 21, 2022
A full-featured and easy-to-use web framework with the Rust programming language.

Poem Framework A program is like a poem, you cannot write a poem without writing it. --- Dijkstra A full-featured and easy-to-use web framework with t

Poem Web 2.2k Jan 6, 2023
Trulang is an interpreted language that is designed to be a simple, easy to learn, and easy to use programming language.

Trulang is an interpreted language that is designed to be a simple, easy to learn, and easy to use programming language.

Bunch-of-cells 2 Nov 23, 2022
A customizable, simple and easy to use json REST API consumer

JACK is a generic JSON API client. It is useful to interact with APIs from multiple services such as Google and Twitter

Mente Binária 6 May 22, 2022
Starter template for use with the Leptos web framework and Axum.

Leptos Axum Starter Template This is a template for use with the Leptos web framework and the cargo-leptos tool using Axum. Creating your template rep

Leptos 10 Mar 4, 2023
Discover GitHub token scope permission and return you an easy interface for checking token permission before querying GitHub.

github-scopes-rs Discover GitHub token scope permission and return you an easy interface for checking token permission before querying GitHub. In many

null 8 Sep 15, 2022
Rustypaste is a minimal file upload/pastebin service.

Rustypaste is a minimal file upload/pastebin service.

Orhun Parmaksız 169 Jan 1, 2023
Magnesium-Oxide (MGO) a secure file uploader with support for ShareX.

A blazingly fast, ShareX uploader coded in Rust (using actix web) which utilizes AES-256-GCM-SIV to securely store uploaded content.

Magnesium 26 Nov 25, 2022