Skip to content

Commit

Permalink
feat: Add Template.render_with_encoder (#81)
Browse files Browse the repository at this point in the history
Adding the ability to provide a custom encoder and thus custom escaping.
The `Encoder` trait is already public, so seems like a natural addition.
  • Loading branch information
Finistere authored Feb 13, 2025
1 parent 5eaf66e commit 2a309c2
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions ramhorns/src/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::path::Path;
use beef::Cow;
use fnv::FnvHasher;

use crate::encoding::EscapingIOEncoder;
use crate::encoding::{Encoder, EscapingIOEncoder};
use crate::Partials;
use crate::{Content, Error};

Expand Down Expand Up @@ -96,7 +96,7 @@ impl<'tpl> Template<'tpl> {
let mut buf = String::with_capacity(capacity);

// Ignore the result, cannot fail
let _ = Section::new(&self.blocks).with(content).render(&mut buf);
let _ = self.render_with_encoder(&mut buf, content);

buf
}
Expand All @@ -108,9 +108,7 @@ impl<'tpl> Template<'tpl> {
C: Content,
{
let mut encoder = EscapingIOEncoder::new(writer);
Section::new(&self.blocks)
.with(content)
.render(&mut encoder)
self.render_with_encoder(&mut encoder, content)
}

/// Render this `Template` with a given `Content` to a file.
Expand All @@ -123,10 +121,16 @@ impl<'tpl> Template<'tpl> {

let writer = BufWriter::new(File::create(path)?);
let mut encoder = EscapingIOEncoder::new(writer);
self.render_with_encoder(&mut encoder, content)
}

Section::new(&self.blocks)
.with(content)
.render(&mut encoder)
/// Render this `Template` with a given `Content` and a custom `Encoder`
pub fn render_with_encoder<E, C>(&self, encoder: &mut E, content: &C) -> Result<(), E::Error>
where
E: Encoder,
C: Content,
{
Section::new(&self.blocks).with(content).render(encoder)
}

/// Get a reference to a source this `Template` was created from.
Expand Down

0 comments on commit 2a309c2

Please sign in to comment.