Skip to content

Commit

Permalink
Expose the fact that templates implement Display
Browse files Browse the repository at this point in the history
This is a quite useful feature, because you can use templates in
format!(), format_args!(), etc.
  • Loading branch information
Kijewski authored and djc committed Mar 31, 2022
1 parent e30ce83 commit 52e068d
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions askama_shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ mod parser;
/// Main `Template` trait; implementations are generally derived
///
/// If you need an object-safe template, use [`DynTemplate`].
pub trait Template {
pub trait Template: fmt::Display {
/// Helper method which allocates a new `String` and renders into it
fn render(&self) -> Result<String> {
let mut buf = String::with_capacity(Self::SIZE_HINT);
Expand Down Expand Up @@ -92,6 +92,12 @@ impl<T: Template> DynTemplate for T {
}
}

impl fmt::Display for dyn DynTemplate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.dyn_render_into(f).map_err(|_| ::std::fmt::Error {})
}
}

#[derive(Debug)]
struct Config<'a> {
dirs: Vec<PathBuf>,
Expand Down Expand Up @@ -603,10 +609,23 @@ mod tests {
const MIME_TYPE: &'static str = "text/plain; charset=utf-8";
}

impl fmt::Display for Test {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.render_into(f).map_err(|_| fmt::Error {})
}
}

fn render(t: &dyn DynTemplate) -> String {
t.dyn_render().unwrap()
}

assert_eq!(render(&Test), "test");
let test = &Test as &dyn DynTemplate;

assert_eq!(render(test), "test");

assert_eq!(test.to_string(), "test");

assert_eq!(format!("{}", test), "test");
}
}

0 comments on commit 52e068d

Please sign in to comment.