This is a library for getting text from JSON usually for internationalization.
```rust
let ctx = staticjsongettextbuild!( "enUS", "enUS", "langs/enUS.json", "zhTW", "langs/zhTW.json" ).unwrap();
asserteq!("Hello, world!", gettext!(ctx, "hello").unwrap()); asserteq!("哈囉,世界!", gettext!(ctx, "zh_TW", "hello").unwrap()); ```
This crate supports the Rocket framework. In order to reload changed json files instead of recompiling the program you have to enable the rocketly
feature for this crate.
toml
[dependencies.json-gettext]
version = "*"
features = ["rocketly"]
Then, use the static_json_gettext_build_rocketly
macro instead of the static_json_gettext_build
macro to build a JSONGetText
(JSONGetTextManager
).
```rust
use rocket::State; use rocket::response::Redirect;
use json_gettext::JSONGetTextManager;
fn index(ctx: State
fn hello(ctx: State
fn main() { rocket::ignite() .attach(JSONGetTextManager::fairing(|| { staticjsongettextbuildrocketly!("enUS", "enUS", "langs/enUS.json", "zhTW", "langs/zh_TW.json" ) })) .mount("/", routes![index, hello]) .launch(); } ```
If you are not using the release
profile, JSONGetTextManager
can reload the json files automatically if needed.
unic-langid
SupportSince string comparison could be slow, the language_region_pair
feature, the language
feature or the region
feature can be enabled to change key's type to (Language, Option<Region>)
, Language
or Region
respectively where Language
and Region
structs are in the unic-langid
crate.
In this case, the key!
macro would be useful for generating a Key
instance from a literal string.
For example,
toml
[dependencies.json-gettext]
version = "*"
features = ["language_region_pair", "rocketly"]
```rust
extern crate rocket;
extern crate rocketacceptlanguage;
extern crate json_gettext;
use rocket::State;
use rocketacceptlanguage::uniclangid::subtags::Language; use rocketaccept_language::AcceptLanguage;
use json_gettext::{JSONGetTextManager, Key};
const LANGUAGE_EN: Language = language!("en");
fn index(ctx: State
format!("Ron: {}", get_text!(ctx, Key(language, region), "hello").unwrap().as_str().unwrap())
}
fn main() { rocket::ignite() .attach(JSONGetTextManager::fairing(|| { staticjsongettextbuildrocketly!( key!("en"), key!("en"), "langs/enUS.json", key!("zhTW"), "langs/zh_TW.json" ) })) .mount("/", routes![index]) .launch(); } ```
https://crates.io/crates/json-gettext
https://docs.rs/json-gettext