aboutsummaryrefslogtreecommitdiffstats
path: root/askama_shared
diff options
context:
space:
mode:
authorLibravatar Casey Rodarmor <casey@rodarmor.com>2018-10-17 01:39:52 -0700
committerLibravatar Dirkjan Ochtman <dirkjan@ochtman.nl>2018-10-17 11:14:27 +0200
commit65e13033e14fc05230acb2e0f02cfa507ab2626d (patch)
tree2656109081f6d31c56b8000473ce981327d1a0d7 /askama_shared
parentd48bd54bbe54529b8940be309a840e5361b108e2 (diff)
downloadaskama-65e13033e14fc05230acb2e0f02cfa507ab2626d.tar.gz
askama-65e13033e14fc05230acb2e0f02cfa507ab2626d.tar.bz2
askama-65e13033e14fc05230acb2e0f02cfa507ab2626d.zip
Add `indent` filter
Diffstat (limited to 'askama_shared')
-rw-r--r--askama_shared/src/filters/mod.rs33
1 files changed, 32 insertions, 1 deletions
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<String> {
}
}
+/// Indent lines with `width` spaces
+pub fn indent(s: &fmt::Display, width: &usize) -> Result<String> {
+ 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<T, I, S>(input: I, separator: S) -> Result<String>
where
@@ -270,6 +290,17 @@ mod tests {
}
#[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!(
join((&["hello", "world"]).into_iter(), ", ").unwrap(),