diff options
author | bott <mhpoin@gmail.com> | 2018-09-25 01:12:09 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2018-09-25 10:23:53 +0200 |
commit | af880b3f202d3b94a7a38ec9a8503d3a18d924e6 (patch) | |
tree | 9eaf8c75086e2cccb530d885aea8cb3825cc1a33 /askama_shared | |
parent | 598472d5c18ba2f5a11b7dbfcf77b7ba6989145e (diff) | |
download | askama-af880b3f202d3b94a7a38ec9a8503d3a18d924e6.tar.gz askama-af880b3f202d3b94a7a38ec9a8503d3a18d924e6.tar.bz2 askama-af880b3f202d3b94a7a38ec9a8503d3a18d924e6.zip |
Add center filter
Diffstat (limited to 'askama_shared')
-rw-r--r-- | askama_shared/src/filters/mod.rs | 38 |
1 files changed, 37 insertions, 1 deletions
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 60d17f1..2b3758c 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -20,9 +20,10 @@ 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; 17] = [ +pub const BUILT_IN_FILTERS: [&str; 18] = [ "abs", "capitalize", + "center", "e", "escape", "format", @@ -188,6 +189,33 @@ pub fn capitalize(s: &fmt::Display) -> Result<String> { } } +/// Centers the value in a field of a given width. +pub fn center(s: &fmt::Display, l: usize) -> Result<String> { + let s = format!("{}", s); + let len = s.len(); + + if l <= len { + Ok(s) + } else { + let p = l - len; + let q = p / 2; + let r = p % 2; + let mut buf = String::with_capacity(l); + + for _ in 0..q { + buf.push(' '); + } + + buf.push_str(&s); + + for _ in 0..q + r { + buf.push(' '); + } + + Ok(buf) + } +} + /// Count the words in that string. pub fn wordcount(s: &fmt::Display) -> Result<usize> { let s = format!("{}", s); @@ -301,6 +329,14 @@ mod tests { } #[test] + fn test_center() { + assert_eq!(center(&"f", 3).unwrap(), " f ".to_string()); + assert_eq!(center(&"f", 4).unwrap(), " f ".to_string()); + assert_eq!(center(&"foo", 1).unwrap(), "foo".to_string()); + assert_eq!(center(&"foo bar", 8).unwrap(), "foo bar ".to_string()); + } + + #[test] fn test_wordcount() { assert_eq!(wordcount(&"").unwrap(), 0); assert_eq!(wordcount(&" \n\t").unwrap(), 0); |