Skip to content

Commit

Permalink
Add a method to manually insert a template parsed from source (#67)
Browse files Browse the repository at this point in the history
This covers the cases where the source is available elsewhere than in a particular file
  • Loading branch information
grego authored Mar 18, 2024
1 parent f3a53de commit df20640
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 2 deletions.
17 changes: 15 additions & 2 deletions ramhorns/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,21 @@ impl<H: BuildHasher + Default> Ramhorns<H> {
}
Err(e) => Err(Error::Io(e)),
}?;
let template = Template::load(file, self)?;
self.partials.insert(name, template);
self.insert(file, name)
}

/// Insert a template parsed from `src` with the name `name`.
/// If a template with this name is present, it gets replaced.
///
/// # Warning
/// This can load partials from an arbitrary path. Use only with trusted source.
pub fn insert<S, T>(&mut self, src: S, name: T) -> Result<(), Error>
where
S: Into<Cow<'static, str>>,
T: Into<Cow<'static, str>>
{
let template = Template::load(src, self)?;
self.partials.insert(name.into(), template);
Ok(())
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/templates/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
html { display: none; }
1 change: 1 addition & 0 deletions tests/templates/style.result
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
html { display: none; } OH YEAH
3 changes: 3 additions & 0 deletions tests/templates/yeah.result
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<head>
<title>Hello, Ramhorns!</title>
</head> OH YEAH
24 changes: 24 additions & 0 deletions tests/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,30 @@ fn simple_partials_folder() {
);
}

#[test]
fn simple_partials_insert() {
use std::fs::read_to_string;

let mut tpls: Ramhorns = Ramhorns::from_folder("templates").unwrap();
let post = Post {
title: "Hello, Ramhorns!",
body: "This is a really simple test of the rendering!",
};

tpls.insert("{{>head.html}} OH YEAH", "yeah.html").unwrap();
assert_eq!(
tpls.get("yeah.html").unwrap().render(&post),
read_to_string("templates/yeah.result").unwrap().trim_end()
);
tpls.insert("{{>style.css}} OH YEAH", "style.html").unwrap();
assert_eq!(
tpls.get("style.html").unwrap().render(&post),
read_to_string("templates/style.result")
.unwrap()
.trim_end()
);
}

#[test]
fn simple_partials_extend() {
use std::fs::read_to_string;
Expand Down

0 comments on commit df20640

Please sign in to comment.