Skip to content

Commit

Permalink
Add io::writer helper methods
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Kijewski authored and djc committed Mar 31, 2022
1 parent 52e068d commit 8ee5eee
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions askama_shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>;

Expand All @@ -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>;

Expand All @@ -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
}
Expand Down Expand Up @@ -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']);
}
}

0 comments on commit 8ee5eee

Please sign in to comment.