handlebars 6.4.0

Handlebars templating implemented in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Helpers for boolean operations

use std::cmp::Ordering;
use std::iter::Iterator;
use std::str::FromStr;

use num_order::NumOrd;
use serde_json::Value as Json;

use crate::json::value::JsonTruthy;
use crate::Renderable;

#[derive(Clone, Copy)]
pub struct BinaryBoolHelper {
    name: &'static str,
    op: fn(&Json, &Json) -> bool,
}

impl crate::HelperDef for BinaryBoolHelper {
    fn call<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        r: &'reg crate::registry::Registry<'reg>,
        ctx: &'rc crate::Context,
        rc: &mut crate::RenderContext<'reg, 'rc>,
        out: &mut dyn crate::Output,
    ) -> crate::HelperResult {
        let value = self.call_inner(h, r, ctx, rc)?;
        let value = value.as_json().as_bool().unwrap_or(false);

        if !(h.is_block()) {
            return out
                .write(value.to_string().as_str())
                .map_err(|e| crate::RenderErrorReason::Other(e.to_string()).into());
        }

        let tmpl = if value { h.template() } else { h.inverse() };
        match tmpl {
            Some(t) => t.render(r, ctx, rc, out),
            None => Ok(()),
        }
    }

    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        r: &'reg crate::registry::Registry<'reg>,
        _ctx: &'rc crate::Context,
        _rc: &mut crate::RenderContext<'reg, 'rc>,
    ) -> Result<crate::ScopedJson<'rc>, crate::RenderError> {
        let x = h
            .param(0)
            .and_then(|it| {
                if r.strict_mode() && it.is_value_missing() {
                    None
                } else {
                    Some(it.value())
                }
            })
            .ok_or_else(|| crate::RenderErrorReason::ParamNotFoundForIndex(self.name, 0))?;
        let y = h
            .param(1)
            .and_then(|it| {
                if r.strict_mode() && it.is_value_missing() {
                    None
                } else {
                    Some(it.value())
                }
            })
            .ok_or_else(|| crate::RenderErrorReason::ParamNotFoundForIndex(self.name, 1))?;

        Ok(crate::ScopedJson::Derived(Json::Bool((self.op)(x, y))))
    }
}

pub(crate) static EQ_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "eq",
    op: |x, y| x == y,
};
pub(crate) static NEQ_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "ne",
    op: |x, y| x != y,
};
pub(crate) static GT_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "gt",
    op: |x, y| compare_json(x, y) == Some(Ordering::Greater),
};
pub(crate) static GTE_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "gte",
    op: |x, y| compare_json(x, y).is_some_and(|ord| ord != Ordering::Less),
};
pub(crate) static LT_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "lt",
    op: |x, y| compare_json(x, y) == Some(Ordering::Less),
};
pub(crate) static LTE_HELPER: BinaryBoolHelper = BinaryBoolHelper {
    name: "lte",
    op: |x, y| compare_json(x, y).is_some_and(|ord| ord != Ordering::Greater),
};

#[derive(Clone, Copy)]
pub struct UnaryBoolHelper {
    name: &'static str,
    op: fn(&Json) -> bool,
}

impl crate::HelperDef for UnaryBoolHelper {
    fn call<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        r: &'reg crate::registry::Registry<'reg>,
        ctx: &'rc crate::Context,
        rc: &mut crate::RenderContext<'reg, 'rc>,
        out: &mut dyn crate::Output,
    ) -> crate::HelperResult {
        let value = self.call_inner(h, r, ctx, rc)?;
        let value = value.as_json().as_bool().unwrap_or(false);

        if !(h.is_block()) {
            return out
                .write(value.to_string().as_str())
                .map_err(|e| crate::RenderErrorReason::Other(e.to_string()).into());
        }

        let tmpl = if value { h.template() } else { h.inverse() };
        match tmpl {
            Some(t) => t.render(r, ctx, rc, out),
            None => Ok(()),
        }
    }

    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        r: &'reg crate::Handlebars<'reg>,
        _: &'rc crate::Context,
        _: &mut crate::RenderContext<'reg, 'rc>,
    ) -> std::result::Result<crate::ScopedJson<'rc>, crate::RenderError> {
        let arg = h
            .param(0)
            .and_then(|it| {
                if r.strict_mode() && it.is_value_missing() {
                    None
                } else {
                    Some(it.value())
                }
            })
            .ok_or_else(|| crate::RenderErrorReason::ParamNotFoundForIndex(self.name, 0))?;
        let result = (self.op)(arg);
        Ok(crate::ScopedJson::Derived(crate::JsonValue::from(result)))
    }
}

pub(crate) static NOT_HELPER: UnaryBoolHelper = UnaryBoolHelper {
    name: "not",
    op: |x| !x.is_truthy(false),
};

handlebars_helper!(len: |x: Json| {
    match x {
        Json::Array(a) => a.len(),
        Json::Object(m) => m.len(),
        Json::String(s) => s.len(),
        _ => 0
    }
});

fn compare_json(x: &Json, y: &Json) -> Option<Ordering> {
    fn cmp_num_str(a_num: &serde_json::Number, b_str: &str) -> Option<Ordering> {
        let b_num = serde_json::Number::from_str(b_str).ok()?;
        cmp_nums(a_num, &b_num)
    }

    // this function relies on serde_json::Numbers coerce logic
    // for number value between [0, u64::MAX], is_u64() returns true
    // for number value between [i64::MIN, i64::MAX], is_i64() returns true
    // for others, is_f64() returns true, note that this behaviour is not
    //  guaranteed according to serde_json docs
    fn cmp_nums(a_num: &serde_json::Number, b_num: &serde_json::Number) -> Option<Ordering> {
        if a_num.is_u64() {
            let a = a_num.as_u64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        } else if a_num.is_i64() {
            let a = a_num.as_i64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        } else {
            let a = a_num.as_f64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        }
    }

    match (x, y) {
        (Json::Number(a), Json::Number(b)) => cmp_nums(a, b),
        (Json::String(a), Json::String(b)) => Some(a.cmp(b)),
        (Json::Bool(a), Json::Bool(b)) => Some(a.cmp(b)),
        (Json::Number(a), Json::String(b)) => cmp_num_str(a, b),
        (Json::String(a), Json::Number(b)) => cmp_num_str(b, a).map(Ordering::reverse),
        _ => None,
    }
}

#[derive(Clone, Copy)]
pub struct ManyBoolHelper {
    name: &'static str,
    op: fn(&Vec<crate::PathAndJson<'_>>) -> bool,
}

impl crate::HelperDef for ManyBoolHelper {
    fn call<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        r: &'reg crate::registry::Registry<'reg>,
        ctx: &'rc crate::Context,
        rc: &mut crate::RenderContext<'reg, 'rc>,
        out: &mut dyn crate::Output,
    ) -> crate::HelperResult {
        let value = self.call_inner(h, r, ctx, rc)?;
        let value = value.as_json().as_bool().unwrap_or(false);

        if !(h.is_block()) {
            return out
                .write(value.to_string().as_str())
                .map_err(|e| crate::RenderErrorReason::Other(e.to_string()).into());
        }

        let tmpl = if value { h.template() } else { h.inverse() };
        match tmpl {
            Some(t) => t.render(r, ctx, rc, out),
            None => Ok(()),
        }
    }

    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        _r: &'reg crate::Handlebars<'reg>,
        _: &'rc crate::Context,
        _: &mut crate::RenderContext<'reg, 'rc>,
    ) -> std::result::Result<crate::ScopedJson<'rc>, crate::RenderError> {
        let result = (self.op)(h.params());
        Ok(crate::ScopedJson::Derived(crate::JsonValue::from(result)))
    }
}

pub(crate) static AND_HELPER: ManyBoolHelper = ManyBoolHelper {
    name: "and",
    op: |params| params.iter().all(|p| p.value().is_truthy(false)),
};

pub(crate) static OR_HELPER: ManyBoolHelper = ManyBoolHelper {
    name: "or",
    op: |params| params.iter().any(|p| p.value().is_truthy(false)),
};

#[cfg(test)]
mod test_conditions {
    fn test_condition(condition: &str, expected: bool) {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template(
                &format!("{{{{#if {condition}}}}}lorem{{{{else}}}}ipsum{{{{/if}}}}"),
                &json!({}),
            )
            .unwrap();
        assert_eq!(&result, if expected { "lorem" } else { "ipsum" });
    }

    #[test]
    fn test_and_or() {
        test_condition("(or (gt 3 5) (gt 5 3))", true);
        test_condition("(and null 4)", false);
        test_condition("(or null 4)", true);
        test_condition("(and null 4 5 6)", false);
        test_condition("(or null 4 5 6)", true);
        test_condition("(and 1 2 3 4)", true);
        test_condition("(or 1 2 3 4)", true);
        test_condition("(and 1 2 3 4 0)", false);
        test_condition("(or 1 2 3 4 0)", true);
        test_condition("(or null 2 3 4 0)", true);
        test_condition("(or [] [])", false);
        test_condition("(or [1] [])", true);
        test_condition("(or [1] [2])", true);
        test_condition("(or [1] [2] [3])", true);
        test_condition("(or [1] [2] [3] [4])", true);
        test_condition("(or [1] [2] [3] [4] [])", true);
    }

    #[test]
    fn test_cmp() {
        test_condition("(gt 5 3)", true);
        test_condition("(gt 3 5)", false);
        test_condition("(not [])", true);
    }

    #[test]
    fn test_eq() {
        test_condition("(eq 5 5)", true);
        test_condition("(eq 5 6)", false);
        test_condition(r#"(eq "foo" "foo")"#, true);
        test_condition(r#"(eq "foo" "Foo")"#, false);
        test_condition(r"(eq [5] [5])", true);
        test_condition(r"(eq [5] [4])", false);
        test_condition(r#"(eq 5 "5")"#, false);
        test_condition(r"(eq 5 [5])", false);
    }

    #[test]
    fn test_ne() {
        test_condition("(ne 5 6)", true);
        test_condition("(ne 5 5)", false);
        test_condition(r#"(ne "foo" "foo")"#, false);
        test_condition(r#"(ne "foo" "Foo")"#, true);
    }

    #[test]
    fn nested_conditions() {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template("{{#if (gt 5 3)}}lorem{{else}}ipsum{{/if}}", &json!({}))
            .unwrap();
        assert_eq!(&result, "lorem");

        let result = handlebars
            .render_template(
                "{{#if (not (gt 5 3))}}lorem{{else}}ipsum{{/if}}",
                &json!({}),
            )
            .unwrap();
        assert_eq!(&result, "ipsum");
    }

    #[test]
    fn test_len() {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": [1,2,3]}))
            .unwrap();
        assert_eq!(&result, "3");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": {"a" :1, "b": 2}}))
            .unwrap();
        assert_eq!(&result, "2");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": "tomcat"}))
            .unwrap();
        assert_eq!(&result, "6");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": 3}))
            .unwrap();
        assert_eq!(&result, "0");
    }

    #[test]
    fn test_comparisons() {
        // Integer comparisons
        test_condition("(gt 5 3)", true);
        test_condition("(gt 3 5)", false);
        test_condition("(gte 5 5)", true);
        test_condition("(lt 3 5)", true);
        test_condition("(lte 5 5)", true);
        test_condition("(lt 9007199254740992 9007199254740993)", true);

        // Float comparisons
        test_condition("(gt 5.5 3.3)", true);
        test_condition("(gt 3.3 5.5)", false);
        test_condition("(gte 5.5 5.5)", true);
        test_condition("(lt 3.3 5.5)", true);
        test_condition("(lte 5.5 5.5)", true);

        // String comparisons
        test_condition(r#"(gt "b" "a")"#, true);
        test_condition(r#"(lt "a" "b")"#, true);
        test_condition(r#"(gte "a" "a")"#, true);

        // Mixed type comparisons
        test_condition(r#"(gt 53 "35")"#, true);
        test_condition(r#"(lt 53 "35")"#, false);
        test_condition(r#"(lt "35" 53)"#, true);
        test_condition(r#"(gte "53" 53)"#, true);
        test_condition(r#"(lt -1 0)"#, true);
        test_condition(r#"(lt "-1" 0)"#, true);
        test_condition(r#"(lt "-1.00" 0)"#, true);
        test_condition(r#"(gt "1.00" 0)"#, true);
        test_condition(r#"(gt 0 -1)"#, true);
        test_condition(r#"(gt 0 "-1")"#, true);
        test_condition(r#"(gt 0 "-1.00")"#, true);
        test_condition(r#"(lt 0 "1.00")"#, true);
        // u64::MAX
        test_condition(r#"(gt 18446744073709551615 -1)"#, true);

        // Boolean comparisons
        test_condition("(gt true false)", true);
        test_condition("(lt false true)", true);
    }

    fn test_block(template: &str, expected: &str) {
        let handlebars = crate::Handlebars::new();

        let result = handlebars.render_template(template, &json!({})).unwrap();
        assert_eq!(&result, expected);
    }

    #[test]
    fn test_chained_else_support() {
        test_block("{{#eq 1 1}}OK{{else}}KO{{/eq}}", "OK");
        test_block("{{#eq 1 3}}OK{{else}}KO{{/eq}}", "KO");

        test_block("{{#ne 1 1}}OK{{else}}KO{{/ne}}", "KO");
        test_block("{{#ne 1 3}}OK{{else}}KO{{/ne}}", "OK");

        test_block("{{#gt 2 1}}OK{{else}}KO{{/gt}}", "OK");
        test_block("{{#gt 1 1}}OK{{else}}KO{{/gt}}", "KO");

        test_block("{{#gte 2 1}}OK{{else}}KO{{/gte}}", "OK");
        test_block("{{#gte 1 1}}OK{{else}}KO{{/gte}}", "OK");
        test_block("{{#gte 0 1}}OK{{else}}KO{{/gte}}", "KO");

        test_block("{{#lt 1 2}}OK{{else}}KO{{/lt}}", "OK");
        test_block("{{#lt 2 2}}OK{{else}}KO{{/lt}}", "KO");

        test_block("{{#lte 0 1}}OK{{else}}KO{{/lte}}", "OK");
        test_block("{{#lte 1 1}}OK{{else}}KO{{/lte}}", "OK");
        test_block("{{#lte 2 1}}OK{{else}}KO{{/lte}}", "KO");

        test_block("{{#and true}}OK{{else}}KO{{/and}}", "OK");
        test_block("{{#and true true}}OK{{else}}KO{{/and}}", "OK");
        test_block("{{#and true true true}}OK{{else}}KO{{/and}}", "OK");
        test_block("{{#and true true false}}OK{{else}}KO{{/and}}", "KO");
        test_block("{{#and true false true}}OK{{else}}KO{{/and}}", "KO");
        test_block("{{#and false false}}OK{{else}}KO{{/and}}", "KO");
        test_block("{{#and false}}OK{{else}}KO{{/and}}", "KO");

        test_block("{{#or true}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or true true}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or true true true}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or true true false}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or true false true}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or false true}}OK{{else}}KO{{/or}}", "OK");
        test_block("{{#or false false}}OK{{else}}KO{{/or}}", "KO");
        test_block("{{#or false}}OK{{else}}KO{{/or}}", "KO");

        test_block("{{#not false}}OK{{else}}KO{{/not}}", "OK");
        test_block("{{#not true}}OK{{else}}KO{{/not}}", "KO");
    }
}