Skip to content
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

Implemented display_some and display_some_or #1014

Open
wants to merge 3 commits into
base: main
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
97 changes: 97 additions & 0 deletions askama/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,64 @@ pub fn wordcount<T: fmt::Display>(s: T) -> Result<usize> {
Ok(s.split_whitespace().count())
}

pub struct DisplaySome<'a, T>(Option<&'a T>);

impl<T> fmt::Display for DisplaySome<'_, T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(val) = self.0 {
write!(f, "{val}")?;
}
Ok(())
}
}

/// See [`display_some` in the Askama book] for more information.
///
/// See also [`display_some_or`].
///
/// [`display_some` in the Askama book]: https://djc.github.io/askama/filters.html#display_some
pub fn display_some<T>(value: &Option<T>) -> Result<DisplaySome<'_, T>>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put the filter functions before the types that need it.

Can we make DisplaySome and DisplaySomeOr private and yield impl Display from the filter functions?

where
T: fmt::Display,
{
Ok(DisplaySome(value.as_ref()))
}

pub struct DisplaySomeOr<'a, T, U>(Option<&'a T>, U);

impl<T, U> fmt::Display for DisplaySomeOr<'_, T, U>
where
T: fmt::Display,
U: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(val) = self.0 {
write!(f, "{val}")
} else {
write!(f, "{}", self.1)
}
}
}

/// See [`display_some_or` in the Askama book] for more information.
///
/// See also [`display_some`].
///
/// [`display_some_or` in the Askama book]: https://djc.github.io/askama/filters.html#display_some_or
pub fn display_some_or<'a, T, U>(
value: &'a Option<T>,
otherwise: U,
) -> Result<DisplaySomeOr<'a, T, U>>
where
T: fmt::Display,
U: fmt::Display + 'a,
{
Ok(DisplaySomeOr(value.as_ref(), otherwise))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -582,4 +640,43 @@ mod tests {
assert_eq!(wordcount("foo").unwrap(), 1);
assert_eq!(wordcount("foo bar").unwrap(), 2);
}

#[test]
fn test_display_some() {
assert_eq!(display_some(&None::<String>).unwrap().to_string(), "");
assert_eq!(display_some(&None::<i32>).unwrap().to_string(), "");

assert_eq!(
display_some(&Some("hello world")).unwrap().to_string(),
"hello world"
);
assert_eq!(display_some(&Some(123)).unwrap().to_string(), "123");
}

#[test]
fn test_display_some_or() {
assert_eq!(
display_some_or(&None::<String>, "default")
.unwrap()
.to_string(),
"default"
);
assert_eq!(
display_some_or(&None::<i32>, "default")
.unwrap()
.to_string(),
"default"
);

assert_eq!(
display_some_or(&Some("hello world"), "default")
.unwrap()
.to_string(),
"hello world"
);
assert_eq!(
display_some_or(&Some(123), "default").unwrap().to_string(),
"123"
);
}
}
2 changes: 2 additions & 0 deletions askama_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ const BUILT_IN_FILTERS: &[&str] = &[
"abs",
"capitalize",
"center",
"display_some",
"display_some_or",
"e",
"escape",
"filesizeformat",
Expand Down
42 changes: 42 additions & 0 deletions book/src/filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Enable it with Cargo features (see below for more information).
[`as_ref`][#as_ref],
[`capitalize`][#capitalize],
[`center`][#center],
[`display_some`][#display_some],
[`display_some_or`][#display_some_or],
[`escape|e`][#escape],
[`filesizeformat`][#filesizeformat],
[`fmt`][#fmt],
Expand Down Expand Up @@ -108,6 +110,46 @@ Output:
- a -
```

### display_some

[#display_some]: #display_some

The `display_some` filter is essentially a shorthand for:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I think we don't need the "a" before "shorthand".


```text
{% if let Some(value) = value %}{{ value }}{% endif %}
```

It can be used like this:

```text
<title>{{ title|display_some }}</title>
```

Where `title` can be any `Option<T>` as long as `T` implements [`fmt::Display`].

### display_some_or

[#display_some_or]: #display_some_or

The `display_some_or` filter is similar to `display_some`, but allows providing
a default value to render for `None`. In short, instead of the following:

```text
{% if let Some(value) = value %}{{ value }}{% else %}My default title{% endif %}
```

Then `display_some_or` can be used like this:

```text
<title>{{ title|display_some_or("My default title") }}</title>
```

Where `title` can be any `Option<T>` as long as `T` implements [`fmt::Display`].
While the `default` value can be any `U` implementing [`fmt::Display`].

[`fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html

### escape | e
[#escape]: #escape--e

Expand Down
14 changes: 14 additions & 0 deletions book/src/template_syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,20 @@ mirror Rust's [`if let` expressions]:
{% endif %}
```

See also the [`display_some`] and [`display_some_or`] filters, which
can be used to simplify _"render `Some` or nothing/default"_.

```text
<title>{{ title|display_some }}</title>

<title>{{ title|display_some_or("My default title") }}</title>
```

_Assuming `title` is `Option<String>`._

[`display_some`]: filters.html#display_some
[`display_some_or`]: filters.html#display_some_or

[`if let` expressions]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions

### Match
Expand Down
73 changes: 73 additions & 0 deletions testing/tests/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,76 @@ fn test_let_borrow() {
};
assert_eq!(template.render().unwrap(), "hello")
}

#[derive(askama::Template)]
#[template(
source = "|{{ a|display_some }}|{{ b|display_some }}|{{ c|display_some }}|",
ext = "html"
)]
struct DisplaySome {
a: Option<String>,
b: Option<i32>,
c: Option<bool>,
}

#[test]
fn test_display_some() {
let template = DisplaySome {
a: None,
b: None,
c: None,
};
assert_eq!(template.render().unwrap(), "||||");

let template = DisplaySome {
a: Some(String::from("Hello World")),
b: Some(12345),
c: Some(true),
};
assert_eq!(template.render().unwrap(), "|Hello World|12345|true|");
}

#[derive(askama::Template)]
#[template(
source = "|{{ a|display_some_or(\"default\") }}|{{ b|display_some_or(0) }}|{{ c|display_some_or(\"none\") }}|",
ext = "html"
)]
struct DisplaySomeOr {
a: Option<String>,
b: Option<i32>,
c: Option<bool>,
}

#[test]
fn test_display_some_or() {
let template = DisplaySomeOr {
a: None,
b: None,
c: None,
};
assert_eq!(template.render().unwrap(), "|default|0|none|");

let template = DisplaySomeOr {
a: Some(String::from("Hello World")),
b: Some(12345),
c: Some(true),
};
assert_eq!(template.render().unwrap(), "|Hello World|12345|true|");
}

#[derive(askama::Template)]
#[template(
source = "\
{% set val = Some(\"Hello World\") %}|{{ val|display_some }}|\
{% set val = Some(123) %}{{ val|display_some }}|\
{% set val = Some(true) %}{{ val|display_some }}|\
",
ext = "html"
)]
struct DisplaySomeUsingSet;

#[test]
fn test_display_some_using_set() {
let template = DisplaySomeUsingSet;
assert_eq!(template.render().unwrap(), "|Hello World|123|true|");
}
Loading