From cd58a6943071c92a17e534849866c1cdf576737a Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Mon, 25 Jun 2018 14:45:58 +0200 Subject: Add support for 'truncate' filter (see #95) --- askama_shared/src/filters/mod.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'askama_shared') diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index c9c6bdf..65215e2 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -18,7 +18,7 @@ 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; 11] = [ +pub const BUILT_IN_FILTERS: [&str; 12] = [ "e", "escape", "format", @@ -27,6 +27,7 @@ pub const BUILT_IN_FILTERS: [&str; 11] = [ "lowercase", "safe", "trim", + "truncate", "upper", "uppercase", "json", // Optional feature; reserve the name anyway @@ -96,6 +97,18 @@ pub fn trim(s: &fmt::Display) -> Result { Ok(s.trim().to_owned()) } +/// Limit string length, appens '...' if truncated { +pub fn truncate(s: &fmt::Display, len: &usize) -> Result { + let mut s = format!("{}", s); + if s.len() < *len { + Ok(s) + } else { + s.truncate(*len); + s.push_str("..."); + Ok(s) + } +} + /// Joins iterable into a string separated by provided argument pub fn join(input: I, separator: S) -> Result where -- cgit