diff options
author | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2018-06-25 14:45:58 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2018-06-25 14:45:58 +0200 |
commit | cd58a6943071c92a17e534849866c1cdf576737a (patch) | |
tree | f39ae66f9d1797981679c95f1f892d99ee65ddcb /askama_shared | |
parent | 4ecd886c6f557eee0446315fd5ad6f132cdca578 (diff) | |
download | askama-cd58a6943071c92a17e534849866c1cdf576737a.tar.gz askama-cd58a6943071c92a17e534849866c1cdf576737a.tar.bz2 askama-cd58a6943071c92a17e534849866c1cdf576737a.zip |
Add support for 'truncate' filter (see #95)
Diffstat (limited to '')
-rw-r--r-- | askama_shared/src/filters/mod.rs | 15 |
1 files changed, 14 insertions, 1 deletions
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<String> { Ok(s.trim().to_owned()) } +/// Limit string length, appens '...' if truncated { +pub fn truncate(s: &fmt::Display, len: &usize) -> Result<String> { + 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<T, I, S>(input: I, separator: S) -> Result<String> where |