From 65e13033e14fc05230acb2e0f02cfa507ab2626d Mon Sep 17 00:00:00 2001 From: Casey Rodarmor Date: Wed, 17 Oct 2018 01:39:52 -0700 Subject: Add `indent` filter --- askama_shared/src/filters/mod.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) (limited to 'askama_shared') diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 9b760f0..0efb7bc 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -20,13 +20,14 @@ 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; 18] = [ +pub const BUILT_IN_FILTERS: [&str; 19] = [ "abs", "capitalize", "center", "e", "escape", "format", + "indent", "join", "linebreaks", "linebreaksbr", @@ -138,6 +139,25 @@ pub fn truncate(s: &fmt::Display, len: &usize) -> Result { } } +/// Indent lines with `width` spaces +pub fn indent(s: &fmt::Display, width: &usize) -> Result { + let s = format!("{}", s); + + let mut indented = String::new(); + + for (i, c) in s.char_indices() { + indented.push(c); + + if c == '\n' && i < s.len() - 1 { + for _ in 0..*width { + indented.push(' '); + } + } + } + + Ok(indented) +} + /// Joins iterable into a string separated by provided argument pub fn join(input: I, separator: S) -> Result where @@ -269,6 +289,17 @@ mod tests { assert_eq!(trim(&" Hello\tworld\t").unwrap(), "Hello\tworld"); } + #[test] + fn test_indent() { + assert_eq!(indent(&"hello", &2).unwrap(), "hello"); + assert_eq!(indent(&"hello\n", &2).unwrap(), "hello\n"); + assert_eq!(indent(&"hello\nfoo", &2).unwrap(), "hello\n foo"); + assert_eq!( + indent(&"hello\nfoo\n bar", &4).unwrap(), + "hello\n foo\n bar" + ); + } + #[test] fn test_join() { assert_eq!( -- cgit