handlebars

Struct Handlebars

Source
pub struct Handlebars<'reg> { /* private fields */ }
Expand description

The single entry point of your Handlebars templates

It maintains compiled templates and registered helpers.

Implementations§

Source§

impl<'reg> Registry<'reg>

Source

pub fn new() -> Registry<'reg>

Source

pub fn set_strict_mode(&mut self, enabled: bool)

Enable or disable handlebars strict mode

By default, handlebars renders empty string for value that undefined or never exists. Since rust is a static type language, we offer strict mode in handlebars-rust. In strict mode, if you were to render a value that doesn’t exist, a RenderError will be raised.

Source

pub fn strict_mode(&self) -> bool

Return strict mode state, default is false.

By default, handlebars renders empty string for value that undefined or never exists. Since rust is a static type language, we offer strict mode in handlebars-rust. In strict mode, if you were access a value that doesn’t exist, a RenderError will be raised.

Source

pub fn dev_mode(&self) -> bool

Return dev mode state, default is false

With dev mode turned on, handlebars enables a set of development friendly features, that may affect its performance.

Source

pub fn set_dev_mode(&mut self, enabled: bool)

Enable or disable dev mode

With dev mode turned on, handlebars enables a set of development friendly features, that may affect its performance.

Note that you have to enable dev mode before adding templates to the registry. Otherwise it won’t take effect at all.

Source

pub fn set_prevent_indent(&mut self, enable: bool)

Enable or disable indent for partial include tag {{>}}

By default handlebars keeps indent whitespaces for partial include tag, to change this behaviour, set this toggle to true.

Source

pub fn prevent_indent(&self) -> bool

Return state for prevent_indent option, default to false.

Source

pub fn register_template(&mut self, name: &str, tpl: Template)

Register a Template

This is infallible since the template has already been parsed and insert cannot fail. If there is an existing template with this name it will be overwritten.

Dev mode doesn’t apply for pre-compiled template because it’s lifecycle is not managed by the registry.

Source

pub fn register_template_string<S>( &mut self, name: &str, tpl_str: S, ) -> Result<(), TemplateError>
where S: AsRef<str>,

Register a template string

Returns TemplateError if there is syntax error on parsing the template.

Source

pub fn register_partial<S>( &mut self, name: &str, partial_str: S, ) -> Result<(), TemplateError>
where S: AsRef<str>,

Register a partial string

A named partial will be added to the registry. It will overwrite template with same name. Currently a registered partial is just identical to a template.

Source

pub fn register_template_file<P>( &mut self, name: &str, tpl_path: P, ) -> Result<(), TemplateError>
where P: AsRef<Path>,

Register a template from a path on file system

If dev mode is enabled, the registry will keep reading the template file from file system everytime it’s visited.

Source

pub fn register_templates_directory<P>( &mut self, dir_path: P, options: DirectorySourceOptions, ) -> Result<(), TemplateError>
where P: AsRef<Path>,

Available on crate feature dir_source only.

Register templates from a directory

  • tpl_extension: the template file extension
  • dir_path: the path of directory

Hidden files and tempfile (starts with #) will be ignored by default. Set DirectorySourceOptions to something other than DirectorySourceOptions::default() to adjust this. All registered templates will use their relative path to determine their template name. For example, when dir_path is templates/ and DirectorySourceOptions.tpl_extension is .hbs, the file templates/some/path/file.hbs will be registered as some/path/file.

This method is not available by default. You will need to enable the dir_source feature to use it.

When dev_mode is enabled, like with register_template_file, templates are reloaded from the file system every time they’re visited.

Source

pub fn register_embed_templates<E>(&mut self) -> Result<(), TemplateError>
where E: RustEmbed,

Available on crate feature rust-embed only.

Register templates using a RustEmbed type Calls register_embed_templates_with_extension with empty extension.

File names from embed struct are used as template name.

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

let mut hbs = Handlebars::new();
hbs.register_embed_templates::<Assets>();
Source

pub fn register_embed_templates_with_extension<E>( &mut self, tpl_extension: &str, ) -> Result<(), TemplateError>
where E: RustEmbed,

Available on crate feature rust-embed only.

Register templates using a RustEmbed type

  • tpl_extension: the template file extension

File names from embed struct are used as template name, but extension is stripped.

When dev_mode enabled templates is reloaded from embed struct everytime it’s visied.

#[derive(RustEmbed)]
#[folder = "templates"]
struct Assets;

let mut hbs = Handlebars::new();
hbs.register_embed_templates_with_extension::<Assets>(".hbs");
Source

pub fn unregister_template(&mut self, name: &str)

Remove a template from the registry

Source

pub fn register_helper( &mut self, name: &str, def: Box<dyn HelperDef + Send + Sync + 'reg>, )

Register a helper

Source

pub fn register_script_helper( &mut self, name: &str, script: &str, ) -> Result<(), ScriptError>

Available on crate feature script_helper only.

Register a rhai script as handlebars helper

Currently only simple helpers are supported. You can do computation or string formatting with rhai script.

Helper parameters and hash are available in rhai script as array params and map hash. Example script:

{{percent 0.34 label="%"}}
// percent.rhai
let value = params[0];
let label = hash["label"];

(value * 100).to_string() + label
Source

pub fn register_script_helper_file<P>( &mut self, name: &str, script_path: P, ) -> Result<(), ScriptError>
where P: AsRef<Path>,

Available on crate feature script_helper only.

Register a rhai script from file

When dev mode is enable, script file is reloaded from original file everytime it is called.

Source

pub fn engine(&self) -> &Engine

Available on crate feature script_helper only.

Borrow a read-only reference to current rhai engine

Source

pub fn set_engine(&mut self, engine: Engine)

Available on crate feature script_helper only.

Set a custom rhai engine for the registry.

Note that you need to set custom engine before adding scripts.

Source

pub fn register_decorator( &mut self, name: &str, def: Box<dyn DecoratorDef + Send + Sync + 'reg>, )

Register a decorator

Source

pub fn register_escape_fn<F: 'static + Fn(&str) -> String + Send + Sync>( &mut self, escape_fn: F, )

Register a new escape fn to be used from now on by this registry.

Source

pub fn unregister_escape_fn(&mut self)

Restore the default escape fn.

Source

pub fn get_escape_fn(&self) -> &dyn Fn(&str) -> String

Get a reference to the current escape fn.

Source

pub fn has_template(&self, name: &str) -> bool

Return true if a template is registered for the given name

Source

pub fn get_template(&self, name: &str) -> Option<&Template>

Return a registered template,

Source

pub fn get_templates(&self) -> &HashMap<String, Template>

Return all templates registered

Note that in dev mode, the template returned from this method may not reflect its latest state. This method doesn’t try to reload templates from its source.

Source

pub fn clear_templates(&mut self)

Unregister all templates

Source

pub fn render<T>(&self, name: &str, data: &T) -> Result<String, RenderError>
where T: Serialize,

Render a registered template with some data into a string

  • name is the template name you registered previously
  • data is the data that implements serde::Serialize

Returns rendered string or a struct with error information

Source

pub fn render_with_context( &self, name: &str, ctx: &Context, ) -> Result<String, RenderError>

Render a registered template with reused context

Source

pub fn render_to_write<T, W>( &self, name: &str, data: &T, writer: W, ) -> Result<(), RenderError>
where T: Serialize, W: Write,

Render a registered template and write data to the std::io::Write

Source

pub fn render_with_context_to_write<W>( &self, name: &str, ctx: &Context, writer: W, ) -> Result<(), RenderError>
where W: Write,

Render a registered template using reusable Context, and write data to the std::io::Write

Source

pub fn render_template<T>( &self, template_string: &str, data: &T, ) -> Result<String, RenderError>
where T: Serialize,

Render a template string using current registry without registering it

Source

pub fn render_template_with_context( &self, template_string: &str, ctx: &Context, ) -> Result<String, RenderError>

Render a template string using reusable context data

Source

pub fn render_template_with_context_to_write<W>( &self, template_string: &str, ctx: &Context, writer: W, ) -> Result<(), RenderError>
where W: Write,

Render a template string using resuable context, and write data into std::io::Write

Source

pub fn render_template_to_write<T, W>( &self, template_string: &str, data: &T, writer: W, ) -> Result<(), RenderError>
where T: Serialize, W: Write,

Render a template string using current registry without registering it

Trait Implementations§

Source§

impl<'reg> Clone for Registry<'reg>

Source§

fn clone(&self) -> Registry<'reg>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Registry<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Registry<'_>

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<'reg> Freeze for Registry<'reg>

§

impl<'reg> !RefUnwindSafe for Registry<'reg>

§

impl<'reg> Send for Registry<'reg>

§

impl<'reg> Sync for Registry<'reg>

§

impl<'reg> Unpin for Registry<'reg>

§

impl<'reg> !UnwindSafe for Registry<'reg>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.