Skip to main content

Engine

Struct Engine 

Source
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: bool

Raise an error on undefined variables / properties instead of returning null.

Implementations§

Source§

impl Engine

Source

pub fn new() -> Self

Source

pub fn with_strict(self) -> Self

Enable strict mode (undefined variables are errors, not null).

Source

pub fn register_filter<F>(self, name: impl Into<String>, f: F) -> Self
where F: Fn(Value, Vec<Value>) -> Result<Value> + Send + Sync + 'static,

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.

Source

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"}.

Source

pub fn with_template_loader<F>(self, loader: F) -> Self
where F: Fn(&str) -> Result<String> + Send + Sync + 'static,

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),
            })
    });
Source

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!");
Source

pub fn render( &self, source: &str, context: HashMap<String, Value>, ) -> Result<String>

Render source against context and return the produced string.

Source

pub fn compile(&self, source: &str) -> Result<Template>

Pre-compile a source string into a Template AST (for repeated rendering).

Source

pub fn render_template( &self, template: &Template, context: HashMap<String, Value>, ) -> Result<String>

Render a pre-compiled template.

Trait Implementations§

Source§

impl Default for Engine

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.