diff --git a/askama/src/filters/mod.rs b/askama/src/filters/mod.rs index ed380aa8..6f078948 100644 --- a/askama/src/filters/mod.rs +++ b/askama/src/filters/mod.rs @@ -486,31 +486,23 @@ pub fn capitalize(s: impl ToString) -> Result { /// Centers the value in a field of a given width #[inline] -pub fn center(src: impl ToString, dst_len: usize) -> Result { - fn center(src: String, dst_len: usize) -> Result { - let len = src.len(); - if dst_len <= len || dst_len >= MAX_LEN { - Ok(src) - } else { - let diff = dst_len - len; - let mid = diff / 2; - let r = diff % 2; - let mut buf = String::with_capacity(dst_len); - - for _ in 0..mid { - buf.push(' '); - } - - buf.push_str(&src); +pub fn center(src: impl fmt::Display, width: usize) -> Result { + Ok(Center { src, width }) +} - for _ in 0..mid + r { - buf.push(' '); - } +struct Center { + src: T, + width: usize, +} - Ok(buf) +impl fmt::Display for Center { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.width < MAX_LEN { + write!(f, "{: ^1$}", self.src, self.width) + } else { + write!(f, "{}", self.src) } } - center(src.to_string(), dst_len) } /// Count the words in that string.