From e018c4a4273063989041c1dc1b6c6878d03a56a6 Mon Sep 17 00:00:00 2001 From: mbuscemi Date: Mon, 22 Mar 2021 03:43:29 -0700 Subject: added paragraphbreaks function --- askama_shared/src/filters/mod.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'askama_shared/src') diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 58bcc47..ce87fd9 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -47,7 +47,7 @@ const URLENCODE_SET: &AsciiSet = &URLENCODE_STRICT_SET.remove(b'/'); // 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; 26] = [ +pub const BUILT_IN_FILTERS: [&str; 27] = [ "abs", "capitalize", "center", @@ -62,6 +62,7 @@ pub const BUILT_IN_FILTERS: [&str; 26] = [ "join", "linebreaks", "linebreaksbr", + "paragraphbreaks", "lower", "lowercase", "safe", @@ -212,6 +213,18 @@ pub fn linebreaksbr(s: T) -> Result { Ok(s.replace("\n", "
")) } +/// Replaces only paragraph breaks in plain text with appropriate HTML +/// +/// A new line followed by a blank line becomes a paragraph break `

`. +/// Paragraph tags only wrap content; empty paragraphs are removed. +/// No `
` tags are added. +pub fn paragraphbreaks(s: T) -> Result { + let s = s.to_string(); + let linebroken = s.replace("\n\n", "

").replace("

", ""); + + Ok(format!("

{}

", linebroken)) +} + /// Converts to lowercase pub fn lower(s: T) -> Result { let s = s.to_string(); @@ -457,6 +470,22 @@ mod tests { ); } + #[test] + fn test_paragraphbreaks() { + assert_eq!( + paragraphbreaks(&"Foo\nBar Baz").unwrap(), + "

Foo\nBar Baz

" + ); + assert_eq!( + paragraphbreaks(&"Foo\nBar\n\nBaz").unwrap(), + "

Foo\nBar

Baz

" + ); + assert_eq!( + paragraphbreaks(&"Foo\n\n\n\n\nBar\n\nBaz").unwrap(), + "

Foo

\nBar

Baz

" + ); + } + #[test] fn test_lower() { assert_eq!(lower(&"Foo").unwrap(), "foo"); -- cgit