diff options
author | René Kijewski <kijewski@library.vetmed.fu-berlin.de> | 2022-03-28 16:19:59 +0200 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2022-03-31 20:47:34 +0200 |
commit | 8ee5eeef15e672c5b10d70444ea86e4b34dbd5ae (patch) | |
tree | 3ab9e83a2133061dc6663ae2b7b6c740cdac765c /askama_shared | |
parent | 52e068df204ed62b0b93e3ad98a80479b4c6272c (diff) | |
download | askama-8ee5eeef15e672c5b10d70444ea86e4b34dbd5ae.tar.gz askama-8ee5eeef15e672c5b10d70444ea86e4b34dbd5ae.tar.bz2 askama-8ee5eeef15e672c5b10d70444ea86e4b34dbd5ae.zip |
Add io::writer helper methods
It might not be immediately obvious to everyone how easy it is to use
Askama template with std::io (e.g. files) instead of std::fmt, so this
PR adds a few helper methods to make this more obvious to novice users.
Diffstat (limited to 'askama_shared')
-rw-r--r-- | askama_shared/src/lib.rs | 22 |
1 files changed, 20 insertions, 2 deletions
diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs index ecf3d07..5913eb3 100644 --- a/askama_shared/src/lib.rs +++ b/askama_shared/src/lib.rs @@ -37,9 +37,15 @@ pub trait Template: fmt::Display { Ok(buf) } - /// Renders the template to the given `writer` buffer + /// Renders the template to the given `writer` fmt buffer fn render_into(&self, writer: &mut (impl std::fmt::Write + ?Sized)) -> Result<()>; + /// Renders the template to the given `writer` io buffer + #[inline] + fn write_into(&self, writer: &mut (impl std::io::Write + ?Sized)) -> std::io::Result<()> { + writer.write_fmt(format_args!("{}", self)) + } + /// The template's extension, if provided const EXTENSION: Option<&'static str>; @@ -57,9 +63,12 @@ pub trait DynTemplate { /// Helper method which allocates a new `String` and renders into it fn dyn_render(&self) -> Result<String>; - /// Renders the template to the given `writer` buffer + /// Renders the template to the given `writer` fmt buffer fn dyn_render_into(&self, writer: &mut dyn std::fmt::Write) -> Result<()>; + /// Renders the template to the given `writer` io buffer + fn dyn_write_into(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()>; + /// Helper function to inspect the template's extension fn extension(&self) -> Option<&'static str>; @@ -79,6 +88,11 @@ impl<T: Template> DynTemplate for T { <Self as Template>::render_into(self, writer) } + #[inline] + fn dyn_write_into(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> { + writer.write_fmt(format_args!("{}", self)) + } + fn extension(&self) -> Option<&'static str> { Self::EXTENSION } @@ -627,5 +641,9 @@ mod tests { assert_eq!(test.to_string(), "test"); assert_eq!(format!("{}", test), "test"); + + let mut vec = Vec::new(); + test.dyn_write_into(&mut vec).unwrap(); + assert_eq!(vec, vec![b't', b'e', b's', b't']); } } |