Skip to content

Commit 3b5354c

Browse files
authored
Implement i18n_args(...) function (#12)
1 parent cbc389e commit 3b5354c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

i18n/src/i18n.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ static mut JSON_DATA_GUARD: Option<Mutex<()>> = None;
1414
static DICTIONARY: ArcSwapOption<Dictionary> = ArcSwapOption::const_empty();
1515

1616
pub type StoreFn = dyn Send + Sync + Fn(&str) -> Result<()> + 'static;
17+
pub type DictionaryArgs<'a> = Vec<(&'static str, &'a str)>;
1718

1819
pub struct Builder {
1920
current_code: String,
@@ -272,6 +273,21 @@ pub fn i18n(text: &str) -> &str {
272273
}
273274
}
274275

276+
/// Translate a string to the currently user-selected language
277+
/// and replace given placeholders with given values.
278+
/// Parameter 'replacements' is a vector consisting of key value pairs,
279+
/// where the key is the placeholder within 'text'.
280+
pub fn i18n_args(text: &str, replacements: DictionaryArgs) -> String {
281+
let mut translated = String::from(i18n(text));
282+
283+
for (key, value) in replacements {
284+
let placeholder = format!("{{{}}}", key);
285+
translated = str::replace(&translated, &placeholder, value);
286+
}
287+
288+
translated
289+
}
290+
275291
/// Dictionary structure containing all translations and related data.
276292
pub struct Dictionary {
277293
/// list of languages {"en": "English", "ja": "日本語", ..."}

i18n/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub mod json;
1414
pub mod result;
1515

1616
pub use i18n::i18n;
17+
pub use i18n::i18n_args;
1718

1819
pub mod prelude {
1920
pub use crate::i18n;

0 commit comments

Comments
 (0)