aboutsummaryrefslogtreecommitdiffstats
path: root/askama_shared/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--askama_shared/src/filters/mod.rs38
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);