From d97d413d7aaea5df6b1cddcef89c35bdb244b363 Mon Sep 17 00:00:00 2001 From: Hannaeko Date: Tue, 10 Jun 2025 14:24:46 +0100 Subject: [PATCH] soft fail when key doesn't exist --- src/localization.rs | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/localization.rs b/src/localization.rs index a30a1df..a9667a6 100644 --- a/src/localization.rs +++ b/src/localization.rs @@ -78,14 +78,24 @@ impl tera::Function for Localization { let bundle = self.bundles.get(&locale) .ok_or_else(|| tera::Error::msg(format!("localize: Could not find locale {locale}")))?; - let message = bundle.get_message(msg) - .ok_or_else(|| tera::Error::msg(format!("localize: Could not find message {msg}")))?; + let message = if let Some(message) = bundle.get_message(msg) { + message + } else { + eprintln!("[warn] localize: could not find message '{msg}'"); + return Ok(tera::Value::from(format!("{{{msg}}}"))); + }; let pattern = if let Some(attribute) = attribute { - message.get_attribute(attribute) - .map(|attribute| attribute.value()) - .ok_or_else(|| tera::Error::msg(format!("localize: Attribute {msg}.{attribute} has no value")))? + let pattern = message.get_attribute(attribute) + .map(|attribute| attribute.value()); + + if let Some(pattern) = pattern { + pattern + } else { + eprintln!("[warn] localize: could not find message '{msg}.{attribute}'"); + return Ok(tera::Value::from(format!("{{{msg}.{attribute}}}"))); + } } else { message.value() .ok_or_else(|| tera::Error::msg(format!("localize: Message {msg} has no value")))? @@ -93,8 +103,17 @@ impl tera::Function for Localization { let mut msg_args = FluentArgs::new(); + let extra_args = args.get("extra_args") + .and_then(|extra_args| extra_args.as_object()); + + if let Some(extra_args) = extra_args { + for (key, value) in extra_args { + msg_args.set(key, fluent_value_from_tera(value, key)?); + } + } + for (key, value) in args { - if key != "msg" && key != "lang" && key != "attr" { + if key != "msg" && key != "lang" && key != "attr" && key != "extra_args" { msg_args.set(key, fluent_value_from_tera(value, key)?); } }