diff options
author | René Kijewski <kijewski@library.vetmed.fu-berlin.de> | 2022-03-28 16:10:45 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2022-03-31 20:47:34 +0200 |
commit | 52e068df204ed62b0b93e3ad98a80479b4c6272c (patch) | |
tree | 884ef319e9646a57c1f5831ce665891d0a0fa4d9 | |
parent | e30ce83ecb5b589e6aaf5ed44fbcdfc9fdf47e22 (diff) | |
download | askama-52e068df204ed62b0b93e3ad98a80479b4c6272c.tar.gz askama-52e068df204ed62b0b93e3ad98a80479b4c6272c.tar.bz2 askama-52e068df204ed62b0b93e3ad98a80479b4c6272c.zip |
Expose the fact that templates implement Display
This is a quite useful feature, because you can use templates in
format!(), format_args!(), etc.
-rw-r--r-- | askama_shared/src/lib.rs | 23 |
1 files changed, 21 insertions, 2 deletions
diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs index b656c53..ecf3d07 100644 --- a/askama_shared/src/lib.rs +++ b/askama_shared/src/lib.rs @@ -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); @@ -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>, @@ -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"); } } |