pub struct Engine {
pub strict: bool,
/* private fields */
}Expand description
The Gracile templating engine.
use gracile_core::{Engine, Value};
use std::collections::HashMap;
let mut ctx = HashMap::new();
ctx.insert("name".to_string(), Value::from("World"));
let output = Engine::new().render("Hello, {= name}!", ctx).unwrap();
assert_eq!(output, "Hello, World!");Fields§
§strict: boolRaise an error on undefined variables / properties instead of returning null.
Implementations§
Source§impl Engine
impl Engine
pub fn new() -> Self
Sourcepub fn with_strict(self) -> Self
pub fn with_strict(self) -> Self
Enable strict mode (undefined variables are errors, not null).
Sourcepub fn register_filter<F>(self, name: impl Into<String>, f: F) -> Self
pub fn register_filter<F>(self, name: impl Into<String>, f: F) -> Self
Register a custom filter function.
User filters take precedence over built-ins, so you can override them if
needed. The filter receives the piped value and any parenthesised
arguments evaluated to Value.
Sourcepub fn register_template(
self,
name: impl Into<String>,
source: impl Into<String>,
) -> Self
pub fn register_template( self, name: impl Into<String>, source: impl Into<String>, ) -> Self
Register a named template that can be referenced by {@include "name"}.
Sourcepub fn with_template_loader<F>(self, loader: F) -> Self
pub fn with_template_loader<F>(self, loader: F) -> Self
Set a loader function that is called when a template name is not found in the pre-registered map.
This lets you lazily load templates from the filesystem, a cache, or any other source without having to pre-register them all up front.
use gracile_core::Engine;
use std::collections::HashMap;
let engine = Engine::new()
.with_template_loader(|name| {
std::fs::read_to_string(format!("/tmp/{}", name))
.map_err(|e| gracile_core::Error::RenderError {
message: format!("cannot load '{}': {}", name, e),
})
});Sourcepub fn render_name(
&self,
name: &str,
context: HashMap<String, Value>,
) -> Result<String>
pub fn render_name( &self, name: &str, context: HashMap<String, Value>, ) -> Result<String>
Resolve a template by name (pre-registered or via the loader) and render it.
use gracile_core::{Engine, Value};
use std::collections::HashMap;
let engine = Engine::new()
.with_template_loader(|name| match name {
"greet" => Ok("Hello, {= who}!".to_string()),
other => Err(gracile_core::Error::RenderError {
message: format!("unknown template '{}'", other),
}),
});
let mut ctx = HashMap::new();
ctx.insert("who".to_string(), Value::from("World"));
assert_eq!(engine.render_name("greet", ctx).unwrap(), "Hello, World!");Sourcepub fn render(
&self,
source: &str,
context: HashMap<String, Value>,
) -> Result<String>
pub fn render( &self, source: &str, context: HashMap<String, Value>, ) -> Result<String>
Render source against context and return the produced string.