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

Rust embedded support #484

Merged
merged 5 commits into from
Dec 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ serde = "1.0.0"
serde_json = "1.0.39"
walkdir = { version = "2.2.3", optional = true }
rhai = { version = "1", optional = true, features = ["sync", "serde"] }
rust-embed = { version = "6.3.0", optional = true }

[dev-dependencies]
env_logger = "0.9"
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@
//! # }
//! ```
//!
//! #### Additional features for loading template from
//!
//! * Feature `dir_source` enables template loading
//! `register_templates_directory` from given directory.
//! * Feature `rust-embed` enables template loading
//! `register_embed_templates` from embedded resources in rust struct
//! generated with `RustEmbed`.
//!
//! ### Rendering Something
//!
//! Since handlebars is originally based on JavaScript type system. It supports dynamic features like duck-typing, truthy/falsey values. But for a static language like Rust, this is a little difficult. As a solution, we are using the `serde_json::value::Value` internally for data rendering.
Expand Down
35 changes: 35 additions & 0 deletions src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ use rhai::Engine;
#[cfg(feature = "script_helper")]
use crate::helpers::scripting::ScriptHelper;

#[cfg(feature = "rust-embed")]
use rust_embed::RustEmbed;

/// This type represents an *escape fn*, that is a function whose purpose it is
/// to escape potentially problematic characters in a string.
///
Expand Down Expand Up @@ -322,6 +325,38 @@ impl<'reg> Registry<'reg> {
Ok(())
}

/// Register templates using a
/// [RustEmbed](https://github.com/pyros2097/rust-embed) type
///
/// File names from embed struct are used as template name.
///
/// ```skip
/// #[derive(RustEmbed)]
/// #[folder = "templates"]
/// struct Assets;
///
/// let mut hbs = Handlebars::new();
/// hbs.register_embed_templates::<Assets>();
/// ```
///
#[cfg(feature = "rust-embed")]
#[cfg_attr(docsrs, doc(cfg(feature = "rust-embed")))]
pub fn register_embed_templates<E>(&mut self) -> Result<(), TemplateError>
where
E: RustEmbed,
{
for item in E::iter() {
let file_name = item.as_ref();
if let Some(file) = E::get(file_name) {
let data = file.data;

let tpl_content = String::from_utf8_lossy(data.as_ref());
self.register_template_string(&file_name.to_owned(), tpl_content)?;
}
}
Ok(())
}

/// Remove a template from the registry
pub fn unregister_template(&mut self, name: &str) {
self.templates.remove(name);
Expand Down
29 changes: 29 additions & 0 deletions tests/embed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#[macro_use]
extern crate serde_json;

use handlebars::Handlebars;

#[test]
#[cfg(feature = "rust-embed")]
fn test_embed() {
use rust_embed::RustEmbed;

#[derive(RustEmbed)]
#[folder = "tests/templates/"]
#[include = "*.hbs"]
struct Templates;

let mut hbs = Handlebars::new();
hbs.register_embed_templates::<Templates>().unwrap();

assert_eq!(1, hbs.get_templates().len());

let data = json!({
"name": "Andy"
});

assert_eq!(
hbs.render("hello.hbs", &data).unwrap().trim(),
"Hello, Andy"
);
}
1 change: 1 addition & 0 deletions tests/templates/hello.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello, {{name}}