| 1 | extern crate env_logger; |
| 2 | extern crate handlebars; |
| 3 | #[macro_use] |
| 4 | extern crate serde_derive; |
| 5 | extern crate serde_json; |
| 6 | use std::error::Error; |
| 7 | |
| 8 | use serde_json::value::{Map, Value as Json}; |
| 9 | |
| 10 | use handlebars::{ |
| 11 | to_json, Context, Decorator, Handlebars, Helper, JsonRender, Output, RenderContext, |
| 12 | RenderError, RenderErrorReason, |
| 13 | }; |
| 14 | |
| 15 | // default format helper |
| 16 | fn format_helper( |
| 17 | h: &Helper, |
| 18 | _: &Handlebars, |
| 19 | _: &Context, |
| 20 | _: &mut RenderContext, |
| 21 | out: &mut dyn Output, |
| 22 | ) -> Result<(), RenderError> { |
| 23 | // get parameter from helper or throw an error |
| 24 | let param = h |
| 25 | .param(0) |
| 26 | .ok_or(RenderErrorReason::ParamNotFoundForIndex("format", 0))?; |
| 27 | write!(out, "{} pts", param.value().render())?; |
| 28 | Ok(()) |
| 29 | } |
| 30 | |
| 31 | // a decorator registers helpers |
| 32 | fn format_decorator( |
| 33 | d: &Decorator, |
| 34 | _: &Handlebars, |
| 35 | _: &Context, |
| 36 | rc: &mut RenderContext, |
| 37 | ) -> Result<(), RenderError> { |
| 38 | let suffix = d |
| 39 | .param(0) |
| 40 | .map(|v| v.value().render()) |
| 41 | .unwrap_or("".to_owned()); |
| 42 | rc.register_local_helper( |
| 43 | "format", |
| 44 | Box::new( |
| 45 | move |h: &Helper, |
| 46 | _: &Handlebars, |
| 47 | _: &Context, |
| 48 | _: &mut RenderContext, |
| 49 | out: &mut dyn Output| { |
| 50 | // get parameter from helper or throw an error |
| 51 | let param = h |
| 52 | .param(0) |
| 53 | .ok_or(RenderErrorReason::ParamNotFoundForIndex("format", 0))?; |
| 54 | write!(out, "{} {}", param.value().render(), suffix)?; |
| 55 | Ok(()) |
| 56 | }, |
| 57 | ), |
| 58 | ); |
| 59 | Ok(()) |
| 60 | } |
| 61 | |
| 62 | // a decorator mutates current context data |
| 63 | fn set_decorator( |
| 64 | d: &Decorator, |
| 65 | _: &Handlebars, |
| 66 | ctx: &Context, |
| 67 | rc: &mut RenderContext, |
| 68 | ) -> Result<(), RenderError> { |
| 69 | // get the input of decorator |
| 70 | let data_to_set = d.hash(); |
| 71 | // retrieve the json value in current context |
| 72 | let ctx_data = ctx.data(); |
| 73 | |
| 74 | if let Json::Object(m) = ctx_data { |
| 75 | let mut new_ctx_data = m.clone(); |
| 76 | |
| 77 | for (k, v) in data_to_set { |
| 78 | new_ctx_data.insert(k.to_string(), v.value().clone()); |
| 79 | } |
| 80 | |
| 81 | rc.set_context(Context::wraps(new_ctx_data)?); |
| 82 | Ok(()) |
| 83 | } else { |
| 84 | Err(RenderErrorReason::Other("Cannot extend non-object data".to_owned()).into()) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // another custom helper |
| 89 | fn rank_helper( |
| 90 | h: &Helper, |
| 91 | _: &Handlebars, |
| 92 | _: &Context, |
| 93 | _: &mut RenderContext, |
| 94 | out: &mut dyn Output, |
| 95 | ) -> Result<(), RenderError> { |
| 96 | let rank = h.param(0).and_then(|v| v.value().as_u64()).ok_or( |
| 97 | RenderErrorReason::ParamTypeMismatchForName("rank", "0".to_string(), "u64".to_string()), |
| 98 | )? as usize; |
| 99 | let total = h |
| 100 | .param(1) |
| 101 | .as_ref() |
| 102 | .and_then(|v| v.value().as_array()) |
| 103 | .map(|arr| arr.len()) |
| 104 | .ok_or(RenderErrorReason::ParamTypeMismatchForName( |
| 105 | "rank", |
| 106 | "1".to_string(), |
| 107 | "array".to_string(), |
| 108 | ))?; |
| 109 | if rank == 0 { |
| 110 | out.write("champion")?; |
| 111 | } else if rank >= total - 2 { |
| 112 | out.write("relegation")?; |
| 113 | } else if rank <= 2 { |
| 114 | out.write("acl")?; |
| 115 | } |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | static TYPES: &'static str = "serde_json"; |
| 120 | |
| 121 | // define some data |
| 122 | #[derive(Serialize)] |
| 123 | pub struct Team { |
| 124 | name: String, |
| 125 | pts: u16, |
| 126 | } |
| 127 | |
| 128 | // produce some data |
| 129 | pub fn make_data() -> Map<String, Json> { |
| 130 | let mut data = Map::new(); |
| 131 | |
| 132 | data.insert("year".to_string(), to_json("2015")); |
| 133 | |
| 134 | let teams = vec![ |
| 135 | Team { |
| 136 | name: "Jiangsu Suning".to_string(), |
| 137 | pts: 43u16, |
| 138 | }, |
| 139 | Team { |
| 140 | name: "Shanghai SIPG".to_string(), |
| 141 | pts: 39u16, |
| 142 | }, |
| 143 | Team { |
| 144 | name: "Hebei CFFC".to_string(), |
| 145 | pts: 27u16, |
| 146 | }, |
| 147 | Team { |
| 148 | name: "Guangzhou Evergrand".to_string(), |
| 149 | pts: 22u16, |
| 150 | }, |
| 151 | Team { |
| 152 | name: "Shandong Luneng".to_string(), |
| 153 | pts: 12u16, |
| 154 | }, |
| 155 | Team { |
| 156 | name: "Beijing Guoan".to_string(), |
| 157 | pts: 7u16, |
| 158 | }, |
| 159 | Team { |
| 160 | name: "Hangzhou Greentown".to_string(), |
| 161 | pts: 7u16, |
| 162 | }, |
| 163 | Team { |
| 164 | name: "Shanghai Shenhua".to_string(), |
| 165 | pts: 4u16, |
| 166 | }, |
| 167 | ]; |
| 168 | |
| 169 | data.insert("teams".to_string(), to_json(&teams)); |
| 170 | data.insert("engine".to_string(), to_json(TYPES)); |
| 171 | data |
| 172 | } |
| 173 | |
| 174 | fn main() -> Result<(), Box<dyn Error>> { |
| 175 | env_logger::init(); |
| 176 | // create the handlebars registry |
| 177 | let mut handlebars = Handlebars::new(); |
| 178 | |
| 179 | // register template from a file and assign a name to it |
| 180 | // deal with errors |
| 181 | handlebars.register_template_file("table", "./examples/decorator/template.hbs")?; |
| 182 | |
| 183 | // register some custom helpers |
| 184 | handlebars.register_helper("format", Box::new(format_helper)); |
| 185 | handlebars.register_helper("ranking_label", Box::new(rank_helper)); |
| 186 | handlebars.register_decorator("format_suffix", Box::new(format_decorator)); |
| 187 | handlebars.register_decorator("set", Box::new(set_decorator)); |
| 188 | |
| 189 | // make data and render it |
| 190 | let data = make_data(); |
| 191 | println!("{}", handlebars.render("table", &data)?); |
| 192 | Ok(()) |
| 193 | } |