diff options
author | bott <mhpoin@gmail.com> | 2018-09-22 19:12:24 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2018-09-25 10:23:53 +0200 |
commit | 61456c1648f9fabdd4b50876c68fab2bd0650e39 (patch) | |
tree | 83e0f8470f118824e1c19e5b970b30b005fbd11f /askama_shared | |
parent | 99612c53e89383ca344c3971a6d8c1b99ae41024 (diff) | |
download | askama-61456c1648f9fabdd4b50876c68fab2bd0650e39.tar.gz askama-61456c1648f9fabdd4b50876c68fab2bd0650e39.tar.bz2 askama-61456c1648f9fabdd4b50876c68fab2bd0650e39.zip |
Add capitalize filter
Diffstat (limited to 'askama_shared')
-rw-r--r-- | askama_shared/src/filters/mod.rs | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 6fccf76..546977a 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -20,8 +20,9 @@ use escaping::{self, MarkupDisplay}; // Askama or should refer to a local `filters` module. It should contain all the // filters shipped with Askama, even the optional ones (since optional inclusion // in the const vector based on features seems impossible right now). -pub const BUILT_IN_FILTERS: [&str; 15] = [ +pub const BUILT_IN_FILTERS: [&str; 16] = [ "abs", + "capitalize", "e", "escape", "format", @@ -165,6 +166,27 @@ where Ok(number.abs()) } +/// Capitalize a value. The first character will be uppercase, all others lowercase. +pub fn capitalize(s: &fmt::Display) -> Result<String> { + let mut s = format!("{}", s); + + match s.get_mut(0..1).map(|s| { + s.make_ascii_uppercase(); + &*s + }) { + None => Ok(s), + _ => { + let l = s.len(); + match s.get_mut(1..l).map(|s| { + s.make_ascii_lowercase(); + &*s + }) { + _ => Ok(s), + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -259,4 +281,14 @@ mod tests { assert_eq!(abs(1.0 as f64).unwrap(), 1.0 as f64); assert_eq!(abs(-1.0 as f64).unwrap(), 1.0 as f64); } + + #[test] + fn test_capitalize() { + assert_eq!(capitalize(&"foo").unwrap(), "Foo".to_string()); + assert_eq!(capitalize(&"f").unwrap(), "F".to_string()); + assert_eq!(capitalize(&"fO").unwrap(), "Fo".to_string()); + assert_eq!(capitalize(&"").unwrap(), "".to_string()); + assert_eq!(capitalize(&"FoO").unwrap(), "Foo".to_string()); + assert_eq!(capitalize(&"foO BAR").unwrap(), "Foo bar".to_string()); + } } |