Skip to content

Add new reject filter #430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions askama/src/filters/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,63 @@ impl<S: FastWritable, P: FastWritable> FastWritable for Pluralize<S, P> {
}
}

/// Returns an iterator without filtered out values.
///
/// ```
/// # use askama::Template;
/// #[derive(Template)]
/// #[template(
/// ext = "html",
/// source = r#"{% for elem in strs|reject("a") %}{{ elem }},{% endfor %}"#,
/// )]
/// struct Example<'a> {
/// strs: Vec<&'a str>,
/// }
///
/// assert_eq!(
/// Example { strs: vec!["a", "b", "c"] }.to_string(),
/// "b,c,"
/// );
/// ```
pub fn reject<T: PartialEq>(
it: impl IntoIterator<Item = T>,
filter: T,
) -> Result<impl Iterator<Item = T>, Infallible> {
Ok(it.into_iter().filter(move |v| v != &filter))
}

/// Returns an iterator without filtered out values.
///
/// ```
/// # use askama::Template;
///
/// fn is_odd(v: &&u32) -> bool {
/// **v & 1 != 0
/// }
///
/// #[derive(Template)]
/// #[template(
/// ext = "html",
/// source = r#"{% for elem in numbers|reject(self::is_odd) %}{{ elem }},{% endfor %}"#,
/// )]
/// struct Example {
/// numbers: Vec<u32>,
/// }
///
/// fn main() {
/// assert_eq!(
/// Example { numbers: vec![1, 2, 3, 4] }.to_string(),
/// "2,4,"
/// );
/// }
/// ```
pub fn reject_with<T: PartialEq, F: Fn(&T) -> bool>(
it: impl IntoIterator<Item = T>,
callback: F,
) -> Result<impl Iterator<Item = T>, Infallible> {
Ok(it.into_iter().filter(move |v| !callback(v)))
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
use alloc::string::{String, ToString};
Expand Down
2 changes: 1 addition & 1 deletion askama/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub use self::alloc::{
AsIndent, capitalize, fmt, format, indent, linebreaks, linebreaksbr, lower, lowercase,
paragraphbreaks, title, titlecase, trim, upper, uppercase, wordcount,
};
pub use self::builtin::{PluralizeCount, center, join, pluralize, truncate};
pub use self::builtin::{PluralizeCount, center, join, pluralize, reject, reject_with, truncate};
pub use self::escape::{
AutoEscape, AutoEscaper, Escaper, Html, HtmlSafe, HtmlSafeOutput, MaybeSafe, Safe, Text,
Unsafe, Writable, WriteWritable, e, escape, safe,
Expand Down
37 changes: 37 additions & 0 deletions askama_derive/src/generator/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ impl<'a> Generator<'a, '_> {
"paragraphbreaks" => Self::visit_paragraphbreaks_filter,
"pluralize" => Self::visit_pluralize_filter,
"ref" => Self::visit_ref_filter,
"reject" => Self::visit_reject_filter,
"safe" => Self::visit_safe_filter,
"truncate" => Self::visit_truncate_filter,
"urlencode" => Self::visit_urlencode_filter,
Expand Down Expand Up @@ -212,6 +213,42 @@ impl<'a> Generator<'a, '_> {
Ok(DisplayWrap::Unwrapped)
}

fn visit_reject_filter(
&mut self,
ctx: &Context<'_>,
buf: &mut Buffer,
args: &[WithSpan<'a, Expr<'a>>],
node: Span<'_>,
) -> Result<DisplayWrap, CompileError> {
const ARGUMENTS: &[&FilterArgument; 2] = &[
FILTER_SOURCE,
&FilterArgument {
name: "filter",
default_value: None,
},
];
let [input, filter] = collect_filter_args(ctx, "reject", node, args, ARGUMENTS)?;

let extra_ampersand = match &**filter {
Expr::Path(_) => {
buf.write("askama::filters::reject_with(");
false
}
_ => {
buf.write("askama::filters::reject(");
true
}
};
self.visit_arg(ctx, buf, input)?;
buf.write(',');
if extra_ampersand {
buf.write('&');
}
self.visit_arg(ctx, buf, filter)?;
buf.write(")?");
Ok(DisplayWrap::Wrapped)
}

fn visit_pluralize_filter(
&mut self,
ctx: &Context<'_>,
Expand Down
43 changes: 43 additions & 0 deletions book/src/filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,49 @@ will become:
&self.x
```

### reject
[#reject]: #reject

This filter filters out values matching the given value/filter.

With this data:

```rust
vec![1, 2, 3, 1]
```

And this template:

```jinja
{% for elem in data|reject(1) %}{{ elem }},{% endfor %}
```

Output will be:

```text
2,3,
```

For more control over the filtering, you can use a callback instead. Declare a function:

```jinja
fn is_odd(value: &&u32) -> bool {
**value % 2 != 0
}
```

Then you can pass the path to the `is_odd` function:

```jinja
{% for elem in data|reject(crate::is_odd) %}{{ elem }},{% endfor %}
```

Output will be:

```text
2,
```

### safe
[#safe]: #safe

Expand Down