From 8228ec4c058f5ec21afd0ae2b62b86e922f9befd Mon Sep 17 00:00:00 2001 From: Aaron Power Date: Fri, 29 Jun 2018 11:36:45 +0100 Subject: Added linebreaks and linebreaksbr filters --- askama_shared/src/filters/mod.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 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 65215e2..f0a6090 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -18,11 +18,13 @@ 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; 12] = [ +pub const BUILT_IN_FILTERS: [&str; 14] = [ "e", "escape", "format", "join", + "linebreaks", + "linebreaksbr", "lower", "lowercase", "safe", @@ -69,6 +71,22 @@ where /// the Askama code generator. pub fn format() {} +/// Replaces line breaks in plain text with appropriate HTML; a single newline +/// becomes an HTML line break `
` and a new line followed by a blank line +/// becomes a paragraph break `

`. +pub fn linebreaks(s: &fmt::Display) -> Result { + let s = format!("{}", s); + let linebroken = s.replace("\n\n", "

").replace("\n", "
"); + + Ok(format!("

{}

", linebroken)) +} + +/// Converts all newlines in a piece of plain text to HTML line breaks. +pub fn linebreaksbr(s: &fmt::Display) -> Result { + let s = format!("{}", s); + Ok(s.replace("\n", "
")) +} + /// Converts to lowercase. pub fn lower(s: &fmt::Display) -> Result { let s = format!("{}", s); @@ -134,6 +152,19 @@ where #[cfg(test)] mod tests { use super::*; + + #[test] + fn test_linebreaks() { + assert_eq!(linebreaks(&"Foo\nBar Baz").unwrap(), "

Foo
Bar Baz

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

Foo
Bar

Baz

"); + } + + #[test] + fn test_linebreaksbr() { + assert_eq!(linebreaksbr(&"Foo\nBar").unwrap(), "Foo
Bar"); + assert_eq!(linebreaksbr(&"Foo\nBar\n\nBaz").unwrap(), "Foo
Bar

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