Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Publish source api #415

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ pub use self::json::value::{to_json, JsonRender, PathAndJson, ScopedJson};
pub use self::output::Output;
pub use self::registry::{html_escape, no_escape, EscapeFn, Registry as Handlebars};
pub use self::render::{Decorator, Evaluable, Helper, RenderContext, Renderable};
pub use self::sources::Source;
pub use self::template::Template;

#[doc(hidden)]
Expand Down
78 changes: 69 additions & 9 deletions src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,15 @@ impl<'reg> Registry<'reg> {
Ok(())
}

/// Register a template source
pub fn register_template_source<S>(&mut self, name: &str, tpl_src: S)
where
S: Source<Item = String, Error = IoError> + Send + Sync + 'reg,
{
self.template_sources
.insert(name.to_owned(), Arc::new(tpl_src));
}

/// Register a partial string
///
/// A named partial will be added to the registry. It will overwrite template with
Expand All @@ -242,6 +251,8 @@ impl<'reg> Registry<'reg> {
.map_err(|err| TemplateError::from((err, name.to_owned())))?;

self.register_template_string(name, template_string)?;
// Register as template source only with dev_mode.
// The default FileSource has no cache so it doesn't perform well
if self.dev_mode {
self.template_sources
.insert(name.to_owned(), Arc::new(source));
Expand Down Expand Up @@ -308,6 +319,7 @@ impl<'reg> Registry<'reg> {
/// Remove a template from the registry
pub fn unregister_template(&mut self, name: &str) {
self.templates.remove(name);
self.template_sources.remove(name);
}

/// Register a helper
Expand Down Expand Up @@ -394,20 +406,33 @@ impl<'reg> Registry<'reg> {

/// Return `true` if a template is registered for the given name
pub fn has_template(&self, name: &str) -> bool {
self.get_template(name).is_some()
self.templates.contains_key(name) || self.template_sources.contains_key(name)
}

/// Return a registered template,
pub fn get_template(&self, name: &str) -> Option<&Template> {
self.templates.get(name)
pub fn get_template(
&'reg self,
name: &str,
) -> Option<Result<Cow<'reg, Template>, TemplateError>> {
self.templates
.get(name)
.map(|t| Ok(Cow::Borrowed(t)))
.or_else(|| {
self.template_sources.get(name).map(|src| {
src.load()
.map_err(|e| TemplateError::from((e, name.to_owned())))
.and_then(|tpl_str| Template::compile_with_name(tpl_str, name.to_owned()))
.map(Cow::Owned)
})
})
}

#[inline]
pub(crate) fn get_or_load_template_optional(
&'reg self,
name: &str,
) -> Option<Result<Cow<'reg, Template>, RenderError>> {
if let (true, Some(source)) = (self.dev_mode, self.template_sources.get(name)) {
if let Some(source) = self.template_sources.get(name) {
let r = source
.load()
.map_err(|e| TemplateError::from((e, name.to_owned())))
Expand Down Expand Up @@ -438,7 +463,7 @@ impl<'reg> Registry<'reg> {
name: &str,
) -> Result<Option<Arc<dyn HelperDef + Send + Sync + 'reg>>, RenderError> {
#[cfg(feature = "script_helper")]
if let (true, Some(source)) = (self.dev_mode, self.script_sources.get(name)) {
if let Some(source) = self.script_sources.get(name) {
return source
.load()
.map_err(ScriptError::from)
Expand Down Expand Up @@ -467,14 +492,23 @@ impl<'reg> Registry<'reg> {
self.decorators.get(name).map(|v| v.as_ref())
}

/// Return all templates registered
pub fn get_templates(&self) -> &HashMap<String, Template> {
&self.templates
/// Return all registered template names
pub fn get_template_names(&self) -> Vec<String> {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sad that we didn't catch the 4.0 release train to ship this break change.

With the Source API, the original get_templates() -> &HashMap<String, Template> has lost its meaning

let mut names = self
.templates
.keys()
.chain(self.template_sources.keys())
.cloned()
.collect::<Vec<String>>();
names.sort();
names.dedup();
names
}

/// Unregister all templates
pub fn clear_templates(&mut self) {
self.templates.clear();
self.template_sources.clear();
}

#[inline]
Expand Down Expand Up @@ -583,8 +617,9 @@ mod test {
use crate::render::{Helper, RenderContext, Renderable};
use crate::support::str::StringWriter;
use crate::template::Template;
use crate::Source;
use std::fs::File;
use std::io::Write;
use std::io::{Error as IoError, ErrorKind as IoErrorKind, Write};
use tempfile::tempdir;

#[derive(Clone, Copy)]
Expand Down Expand Up @@ -634,6 +669,31 @@ mod test {
);
}

#[test]
fn test_register_template_source() {
let mut r = Registry::new();

impl Source for &'static str {
type Item = String;
type Error = IoError;
fn load(&self) -> Result<Self::Item, Self::Error> {
Ok(String::from(*self))
}
}
r.register_template_source("test", "<h1>Hello world!</h1>");
assert_eq!("<h1>Hello world!</h1>", r.render("test", &()).unwrap());

impl Source for () {
type Item = String;
type Error = IoError;
fn load(&self) -> Result<Self::Item, Self::Error> {
Err(IoError::from(IoErrorKind::Other))
}
}
r.register_template_source("test2", ());
assert!(r.render("test2", &()).is_err());
}

#[test]
#[cfg(feature = "dir_source")]
fn test_register_templates_directory() {
Expand Down
2 changes: 1 addition & 1 deletion src/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fs::File;
use std::io::{BufReader, Error as IOError, Read};
use std::path::PathBuf;

pub(crate) trait Source {
pub trait Source {
type Item;
type Error;

Expand Down