Skip to main content

handlebars_fluent/
helper.rs

1use handlebars::{
2    Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderErrorReason,
3    Renderable,
4};
5
6use fluent_bundle::{FluentArgs, FluentValue};
7use handlebars::template::{Parameter, TemplateElement};
8use serde_json::Value as Json;
9use std::io;
10
11use crate::Loader;
12
13pub struct FluentHelper<L> {
14    loader: L,
15}
16
17impl<L> FluentHelper<L> {
18    pub fn new(loader: L) -> Self {
19        Self { loader }
20    }
21}
22
23#[derive(Default)]
24struct StringOutput {
25    pub s: String,
26}
27
28impl Output for StringOutput {
29    fn write(&mut self, seg: &str) -> Result<(), io::Error> {
30        self.s.push_str(seg);
31        Ok(())
32    }
33}
34
35impl<L: Loader + Send + Sync> HelperDef for FluentHelper<L> {
36    fn call<'reg: 'rc, 'rc>(
37        &self,
38        h: &Helper<'rc>,
39        reg: &'reg Handlebars,
40        context: &'rc Context,
41        rcx: &mut RenderContext<'reg, 'rc>,
42        out: &mut dyn Output,
43    ) -> HelperResult {
44        let id = if let Some(id) = h.param(0) {
45            id
46        } else {
47            return Err(RenderErrorReason::ParamNotFoundForIndex("fluent", 0).into());
48        };
49
50        if id.relative_path().is_some() {
51            return Err(RenderErrorReason::ParamTypeMismatchForName(
52                "fluent",
53                "0".into(),
54                "string with no path".into(),
55            )
56            .into());
57        }
58
59        let id = if let Json::String(ref s) = *id.value() {
60            s
61        } else {
62            return Err(RenderErrorReason::ParamTypeMismatchForName(
63                "fluent",
64                "0".into(),
65                "string".into(),
66            )
67            .into());
68        };
69
70        let mut args = if h.hash().is_empty() {
71            None
72        } else {
73            let mut fluent_args = FluentArgs::new();
74            for (k, v) in h.hash() {
75                let k = k.to_owned();
76                match v.value() {
77                    // `Number::as_f64` can't fail here because we haven't
78                    // enabled `arbitrary_precision` feature in `serde_json`.
79                    Json::Number(n) => fluent_args.set(k, n.as_f64().unwrap()),
80                    Json::String(s) => fluent_args.set(k, s.to_owned()),
81                    _ => continue,
82                }
83            }
84            Some(fluent_args)
85        };
86
87        if let Some(tpl) = h.template() {
88            if args.is_none() {
89                args = Some(FluentArgs::new());
90            }
91            let args = args.as_mut().unwrap();
92            for element in &tpl.elements {
93                if let TemplateElement::HelperBlock(ref block) = element {
94                    if block.name != Parameter::Name("fluentparam".into()) {
95                        return Err(RenderErrorReason::Other(format!(
96                            "{{{{fluent}}}} can only contain {{{{fluentparam}}}} elements, not {}",
97                            block.name.expand_as_name(reg, context, rcx).unwrap()
98                        ))
99                        .into());
100                    }
101                    let id = if let Some(el) = block.params.first() {
102                        if let Parameter::Literal(Json::String(ref s)) = *el {
103                            s
104                        } else {
105                            return Err(RenderErrorReason::ParamTypeMismatchForName(
106                                "fluentparam",
107                                "0".into(),
108                                "string".into(),
109                            )
110                            .into());
111                        }
112                    } else {
113                        return Err(
114                            RenderErrorReason::ParamNotFoundForIndex("fluentparam", 0).into()
115                        );
116                    };
117                    if let Some(ref tpl) = block.template {
118                        let mut s = StringOutput::default();
119                        tpl.render(reg, context, rcx, &mut s)?;
120                        args.set(id, FluentValue::String(s.s.into()));
121                    }
122                }
123            }
124        }
125        let lang = context
126            .data()
127            .get("lang")
128            .expect("Language not set in context")
129            .as_str()
130            .expect("Language must be string")
131            .parse()
132            .expect("Language not valid identifier");
133
134        let response = self.loader.lookup(&lang, id, args.as_ref());
135        out.write(&response)
136            .map_err(|e| RenderErrorReason::NestedError(Box::new(e)).into())
137    }
138}