From 1af594b0c06f6e84955992e08b7c1ee28b4dc61b Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Fri, 6 Jan 2023 11:27:46 +0100 Subject: [PATCH] Field's filters. --- examples/form.rs | 6 ++++++ src/filters.rs | 9 +++++++++ src/lib.rs | 14 ++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 src/filters.rs diff --git a/examples/form.rs b/examples/form.rs index 7909609..fa85845 100644 --- a/examples/form.rs +++ b/examples/form.rs @@ -1,5 +1,7 @@ extern crate zakform; +use zakform::filters; + use config::{Config, ConfigError}; use serde_derive::Deserialize; @@ -61,12 +63,16 @@ async fn index_post( let mut fi = zakform::Field::new(zakform::FType::Text, "name"); fi.set_label("Name"); fi.set_value(form.name.as_str()); + fi.add_filter(filters::filter_uppercase); + fi.filter(); f.add_field(fi); let mut fi = zakform::Field::new(zakform::FType::TextArea, "notes"); fi.set_label("Notes"); fi.set_rows(15); fi.set_value(form.notes.as_str()); + fi.add_filter(filters::filter_trim); + fi.filter(); f.add_field(fi); let fs = f.fields(); diff --git a/src/filters.rs b/src/filters.rs new file mode 100644 index 0000000..e6e628f --- /dev/null +++ b/src/filters.rs @@ -0,0 +1,9 @@ +pub type Filter = fn(value: &String) -> String; + +pub fn filter_trim(value: &String) -> String { + String::from(value.trim()) +} + +pub fn filter_uppercase(value: &String) -> String { + value.to_uppercase() +} diff --git a/src/lib.rs b/src/lib.rs index 689f40f..79e48ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ use tera::Tera; +pub mod filters; + pub enum FType { Text, TextArea @@ -16,6 +18,7 @@ pub struct Field { help: String, value: String, tmpl: tera::Tera, + filters: Vec, } impl Field { @@ -31,6 +34,7 @@ impl Field { help: String::new(), value: String::new(), tmpl: Tera::default(), + filters: vec![], }; match f.ftype { @@ -111,6 +115,16 @@ impl Field { self.value = String::from(value); } + pub fn add_filter(&mut self, filter: filters::Filter) { + self.filters.push(filter); + } + + pub fn filter(&mut self) { + for f in &self.filters { + self.value = (f)(&self.value); + } + } + pub fn render(&self) -> String { let mut s = String::new(); -- 2.49.0