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 1 commit
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
48 changes: 48 additions & 0 deletions askama/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,54 @@ 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(())
}
}

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)
}
}
}

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
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