Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implement a split filter
Browse files Browse the repository at this point in the history
wolfv committed Jun 4, 2024
1 parent bffacbf commit 08b1407
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions minijinja/src/defaults.rs
Original file line number Diff line number Diff line change
@@ -72,6 +72,7 @@ pub(crate) fn get_builtin_filters() -> BTreeMap<Cow<'static, str>, filters::Boxe
rv.insert("reverse".into(), BoxedFilter::new(filters::reverse));
rv.insert("trim".into(), BoxedFilter::new(filters::trim));
rv.insert("join".into(), BoxedFilter::new(filters::join));
rv.insert("split".into(), BoxedFilter::new(filters::split));
rv.insert("default".into(), BoxedFilter::new(filters::default));
rv.insert("round".into(), BoxedFilter::new(filters::round));
rv.insert("abs".into(), BoxedFilter::new(filters::abs));
19 changes: 19 additions & 0 deletions minijinja/src/filters.rs
Original file line number Diff line number Diff line change
@@ -557,6 +557,25 @@ mod builtins {
}
}

/// Split a string with a separator
#[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
pub fn split(val: Value, split: Option<Cow<'_, str>>) -> Result<Value, Error> {
let split = split.as_deref().unwrap_or(" ");

match val.as_str() {
Some(s) => {
let elements = s.split(split).map(Value::from).collect::<Vec<Value>>();
Ok(Value::from(elements))
},
None => {
Err(Error::new(
ErrorKind::InvalidOperation,
format!("cannot split value of type {}", val.kind()),
))
}
}
}

/// If the value is undefined it will return the passed default value,
/// otherwise the value of the variable:
///
2 changes: 2 additions & 0 deletions minijinja/tests/inputs/filters.txt
Original file line number Diff line number Diff line change
@@ -104,3 +104,5 @@ unique-filter: {{ [1, 1, 1, 4, 3, 0, 0, 5]|unique }}
pprint-filter: {{ objects|pprint }}
int-filter: {{ true|int }}, {{ "42"|int }}, {{ "-23"|int }}, {{ 42.0|int }}
float-filter: {{ true|float }}, {{ "42"|float }}, {{ "-23.5"|float }}, {{ 42.5|float }}
split: {{ three_words|split }}
split: {{ three_words|split(" and ") }}

0 comments on commit 08b1407

Please sign in to comment.