diff options
author | bott <mhpoin@gmail.com> | 2018-09-24 18:10:09 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2018-09-25 10:23:53 +0200 |
commit | 598472d5c18ba2f5a11b7dbfcf77b7ba6989145e (patch) | |
tree | 29f3baee26c763e6c499bdbb99586d522ca027df /askama_shared | |
parent | 61456c1648f9fabdd4b50876c68fab2bd0650e39 (diff) | |
download | askama-598472d5c18ba2f5a11b7dbfcf77b7ba6989145e.tar.gz askama-598472d5c18ba2f5a11b7dbfcf77b7ba6989145e.tar.bz2 askama-598472d5c18ba2f5a11b7dbfcf77b7ba6989145e.zip |
Add wordcount filter
Diffstat (limited to 'askama_shared')
-rw-r--r-- | askama_shared/src/filters/mod.rs | 18 |
1 files changed, 17 insertions, 1 deletions
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 546977a..60d17f1 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -20,7 +20,7 @@ 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; 16] = [ +pub const BUILT_IN_FILTERS: [&str; 17] = [ "abs", "capitalize", "e", @@ -36,6 +36,7 @@ pub const BUILT_IN_FILTERS: [&str; 16] = [ "truncate", "upper", "uppercase", + "wordcount", "json", // Optional feature; reserve the name anyway ]; @@ -187,6 +188,13 @@ pub fn capitalize(s: &fmt::Display) -> Result<String> { } } +/// Count the words in that string. +pub fn wordcount(s: &fmt::Display) -> Result<usize> { + let s = format!("{}", s); + + Ok(s.split_whitespace().count()) +} + #[cfg(test)] mod tests { use super::*; @@ -291,4 +299,12 @@ mod tests { assert_eq!(capitalize(&"FoO").unwrap(), "Foo".to_string()); assert_eq!(capitalize(&"foO BAR").unwrap(), "Foo bar".to_string()); } + + #[test] + fn test_wordcount() { + assert_eq!(wordcount(&"").unwrap(), 0); + assert_eq!(wordcount(&" \n\t").unwrap(), 0); + assert_eq!(wordcount(&"foo").unwrap(), 1); + assert_eq!(wordcount(&"foo bar").unwrap(), 2); + } } |