From: Andrea Zagli Date: Mon, 2 Jan 2023 15:08:07 +0000 (+0100) Subject: Rendering header. X-Git-Url: https://saetta.ns0.it/gitweb?a=commitdiff_plain;h=79006a987ce56a18726e9aab9c5d24c217b543fd;p=rust%2Fzakgrid Rendering header. --- diff --git a/Cargo.toml b/Cargo.toml index 4c5e1b8..036a3f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,11 +7,12 @@ edition = "2021" [dependencies] +serde = "1" +serde_derive = "1" +tera = "1.8.0" [dev-dependencies] -serde = "1" -serde_derive = "1" config = "0.13" actix-web = "4" diff --git a/examples/grid.rs b/examples/grid.rs index 4e470fb..683deac 100644 --- a/examples/grid.rs +++ b/examples/grid.rs @@ -45,11 +45,7 @@ async fn index( let mut grid = zakgrid::Grid::new(); - let mut s = format!("before: {}\n", grid.header_tmpl); - - grid.header_tmpl = String::from("new header"); - - s.push_str(format!("after: {}\n", grid.header_tmpl).as_str()); + let mut s = String::new(); let mut col = zakgrid::Column::new("col name"); s.push_str(format!("column added: {}\n", col.name()).as_str()); @@ -67,6 +63,9 @@ async fn index( s.push_str(format!("col {} title {}\n", i, v.title()).as_str()); } + let header = grid.header(); + s.push_str(header.as_str()); + Ok(HttpResponse::Ok().body(s)) } diff --git a/src/lib.rs b/src/lib.rs index 93e0582..7033e55 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,7 @@ +use serde_derive::Serialize; +use tera::Tera; + +#[derive(Debug, Serialize)] pub enum Align { Left, Center, @@ -35,7 +39,7 @@ impl Column { } pub struct Grid { - pub header_tmpl: String, + header_tmpl: String, header_row_tmpl: String, row_tmpl: String, row_col_tmpl: String, @@ -45,8 +49,8 @@ pub struct Grid { impl Grid { pub fn new() -> Grid { Grid { - header_tmpl: String::new(), - header_row_tmpl: String::new(), + header_tmpl: String::from("\n{{ row }}\n"), + header_row_tmpl: String::from("\t{{ title }}\n"), row_tmpl: String::new(), row_col_tmpl: String::new(), columns: vec![] @@ -60,4 +64,26 @@ impl Grid { pub fn columns(&self) -> &Vec { &self.columns } + + pub fn header(&self) -> String { + let mut s = String::new(); + + let mut tera = Tera::default(); + + tera.add_raw_template("header", &self.header_tmpl); + tera.add_raw_template("header_row", &self.header_row_tmpl); + + for c in &self.columns { + if !c.hidden { + let mut context = tera::Context::new(); + context.insert("title", &c.title); + context.insert("align", &c.align); + s.push_str(tera.render("header_row", &context).unwrap().as_str()); + } + } + + let mut context = tera::Context::new(); + context.insert("row", s.as_str()); + String::from(tera.render("header", &context).unwrap().as_str()) + } }