From 976607faf73cc0eb6863cef704b1e99cb065e122 Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Wed, 4 Jan 2023 15:21:42 +0100 Subject: [PATCH] Callback for missing columns. --- examples/grid.rs | 8 ++++++++ src/lib.rs | 20 ++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/examples/grid.rs b/examples/grid.rs index 09dc5e9..0f776a2 100644 --- a/examples/grid.rs +++ b/examples/grid.rs @@ -43,6 +43,10 @@ struct AppState { settings: Settings, } +fn get_not_exists(value: &serde_json::Value) -> String { + String::from("not exists (returned by fn)") +} + async fn index( data: web::Data, ) -> Result { @@ -78,6 +82,10 @@ async fn index( col.set_align(zakgrid::Align::Right); grid.add_column(col); + let mut col = zakgrid::Column::new("not_exists"); + col.to_call = Some(get_not_exists); + grid.add_column(col); + let cols = grid.columns(); for (i, v) in cols.iter().enumerate() { diff --git a/src/lib.rs b/src/lib.rs index b161b66..c5bebac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,8 @@ use serde_json::Value; use serde_derive::Serialize; use tera::Tera; +pub type ToCall = fn(row: &serde_json::Value) -> String; + #[derive(Copy, Clone, Serialize)] pub enum Align { Left, @@ -14,6 +16,7 @@ pub struct Column { title: String, align: Align, hidden: bool, + pub to_call: Option, } impl Column { @@ -23,6 +26,7 @@ impl Column { title: String::from(name), align: Align::Left, hidden: false, + to_call: None, } } @@ -130,7 +134,7 @@ impl Grid { String::from(tera.render("header", &context).unwrap().as_str()) } - pub fn row_from_json(&self, value: &serde_json::Value) -> String { + pub fn row_from_json(&self, row: &serde_json::Value) -> String { let mut s = String::new(); let mut tera = Tera::default(); @@ -141,7 +145,19 @@ impl Grid { for c in &self.columns { if !c.hidden { let mut context = tera::Context::new(); - context.insert("value", &value[c.name.as_str()]); + match &row[c.name.as_str()] { + serde_json::Value::Null => { + match c.to_call { + None => context.insert("value", ""), + Some(call) => { + let v = (call)(&row); + context.insert("value", v.as_str()); + } + } + }, + _ => context.insert("value", &row[c.name.as_str()]) + } + context.insert("align", &c.align); s.push_str(tera.render("row_col", &context).unwrap().as_str()); } -- 2.49.0