codegenr_lib/helpers/
json.rs

1use crate::helpers::handlebars_ext::HandlebarsExt;
2use handlebars::HelperDef;
3use serde_json::Value;
4
5pub const JSON_HELPER: &str = "json";
6
7/// Get the json representation of the first argument passed.
8/// If a second argument is true, the json is beautyfied
9///```
10/// # use codegenr_lib::helpers::*;
11/// # use serde_json::json;
12/// assert_eq!(
13///   exec_template(json!(42), r#"{{json this}}"#),
14///   "42"
15/// );
16/// assert_eq!(
17///   exec_template(json!({"a": "42"}), r#"{{json this}}"#),
18///   "{\"a\":\"42\"}"
19/// );
20/// assert_eq!(
21///   exec_template(json!({"a": "42"}), r#"{{json this true}}"#),
22///   "{\n  \"a\": \"42\"\n}"
23/// );
24/// assert_eq!(
25///   exec_template(json!(42), r#"{{json (json this)}}"#),
26///   "\"42\""
27/// );
28///```
29pub struct JsonHelper;
30
31impl HelperDef for JsonHelper {
32  fn call_inner<'reg: 'rc, 'rc>(
33    &self,
34    h: &handlebars::Helper<'reg, 'rc>,
35    _: &'reg handlebars::Handlebars<'reg>,
36    _: &'rc handlebars::Context,
37    _: &mut handlebars::RenderContext<'reg, 'rc>,
38  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
39    h.ensure_arguments_count_min(1, JSON_HELPER)?;
40    h.ensure_arguments_count_max(2, JSON_HELPER)?;
41    let arg = h.get_param_as_json_or_fail(0, JSON_HELPER)?;
42    let beautified = h.get_param_as_bool(1).unwrap_or_default();
43    let json = if beautified { format!("{:#}", arg) } else { format!("{}", arg) };
44    Ok(handlebars::ScopedJson::Derived(Value::String(json)))
45  }
46}