Struct handlebars::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>
impl<'reg> Registry<'reg>
sourcepub fn set_strict_mode(&mut self, enabled: bool)
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.
sourcepub fn strict_mode(&self) -> bool
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.
Examples found in repository?
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
match self.call_inner(h, r, ctx, rc) {
Ok(result) => {
if r.strict_mode() && result.is_missing() {
Err(RenderError::strict_error(None))
} else {
// auto escape according to settings
let output = do_escape(r, rc, result.render());
out.write(output.as_ref())?;
Ok(())
}
}
Err(e) => {
if e.is_unimplemented() {
// default implementation, do nothing
Ok(())
} else {
Err(e)
}
}
}
}
More examples
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn call_inner<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
) -> Result<ScopedJson<'reg, 'rc>, RenderError> {
let collection_value = h
.param(0)
.ok_or_else(|| RenderError::new("Param not found for helper \"lookup\""))?;
let index = h
.param(1)
.ok_or_else(|| RenderError::new("Insufficient params for helper \"lookup\""))?;
let value = match *collection_value.value() {
Json::Array(ref v) => index
.value()
.as_u64()
.and_then(|u| v.get(u as usize))
.unwrap_or(&Json::Null),
Json::Object(ref m) => index
.value()
.as_str()
.and_then(|k| m.get(k))
.unwrap_or(&Json::Null),
_ => &Json::Null,
};
if r.strict_mode() && value.is_null() {
Err(RenderError::strict_error(None))
} else {
Ok(value.clone().into())
}
}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
let param = h
.param(0)
.ok_or_else(|| RenderError::new("Param not found for helper \"with\""))?;
if param.value().is_truthy(false) {
let mut block = create_block(param);
if let Some(block_param) = h.block_param() {
let mut params = BlockParams::new();
if param.context_path().is_some() {
params.add_path(block_param, Vec::with_capacity(0))?;
} else {
params.add_value(block_param, param.value().clone())?;
}
block.set_block_params(params);
}
rc.push_block(block);
if let Some(t) = h.template() {
t.render(r, ctx, rc, out)?;
};
rc.pop_block();
Ok(())
} else if let Some(t) = h.inverse() {
t.render(r, ctx, rc, out)
} else if r.strict_mode() {
Err(RenderError::strict_error(param.relative_path()))
} else {
Ok(())
}
}
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
fn render<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
match self {
RawString(ref v) => indent_aware_write(v.as_ref(), rc, out),
Expression(ref ht) | HtmlExpression(ref ht) => {
let is_html_expression = matches!(self, HtmlExpression(_));
if is_html_expression {
rc.set_disable_escape(true);
}
// test if the expression is to render some value
let result = if ht.is_name_only() {
let helper_name = ht.name.expand_as_name(registry, ctx, rc)?;
if helper_exists(&helper_name, registry, rc) {
render_helper(ht, registry, ctx, rc, out)
} else {
debug!("Rendering value: {:?}", ht.name);
let context_json = ht.name.expand(registry, ctx, rc)?;
if context_json.is_value_missing() {
if registry.strict_mode() {
Err(RenderError::strict_error(context_json.relative_path()))
} else {
// helper missing
if let Some(hook) = registry.get_or_load_helper(HELPER_MISSING)? {
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
hook.call(&h, registry, ctx, rc, out)
} else {
Ok(())
}
}
} else {
let rendered = context_json.value().render();
let output = do_escape(registry, rc, rendered);
indent_aware_write(output.as_ref(), rc, out)
}
}
} else {
// this is a helper expression
render_helper(ht, registry, ctx, rc, out)
};
if is_html_expression {
rc.set_disable_escape(false);
}
result
}
HelperBlock(ref ht) => render_helper(ht, registry, ctx, rc, out),
DecoratorExpression(_) | DecoratorBlock(_) => self.eval(registry, ctx, rc),
PartialExpression(ref dt) | PartialBlock(ref dt) => {
let di = Decorator::try_from_template(dt, registry, ctx, rc)?;
partial::expand_partial(&di, registry, ctx, rc, out)
}
_ => Ok(()),
}
}
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
let value = h
.param(0)
.ok_or_else(|| RenderError::new("Param not found for helper \"each\""))?;
let template = h.template();
match template {
Some(t) => match *value.value() {
Json::Array(ref list)
if !list.is_empty() || (list.is_empty() && h.inverse().is_none()) =>
{
let block_context = create_block(value);
rc.push_block(block_context);
let len = list.len();
let array_path = value.context_path();
for (i, v) in list.iter().enumerate().take(len) {
if let Some(ref mut block) = rc.block_mut() {
let is_first = i == 0usize;
let is_last = i == len - 1;
let index = to_json(i);
block.set_local_var("first", to_json(is_first));
block.set_local_var("last", to_json(is_last));
block.set_local_var("index", index.clone());
update_block_context(block, array_path, i.to_string(), is_first, v);
set_block_param(block, h, array_path, &index, v)?;
}
t.render(r, ctx, rc, out)?;
}
rc.pop_block();
Ok(())
}
Json::Object(ref obj)
if !obj.is_empty() || (obj.is_empty() && h.inverse().is_none()) =>
{
let block_context = create_block(value);
rc.push_block(block_context);
let len = obj.len();
let obj_path = value.context_path();
for (i, (k, v)) in obj.iter().enumerate() {
if let Some(ref mut block) = rc.block_mut() {
let is_first = i == 0usize;
let is_last = i == len - 1;
let key = to_json(k);
block.set_local_var("first", to_json(is_first));
block.set_local_var("last", to_json(is_last));
block.set_local_var("key", key.clone());
update_block_context(block, obj_path, k.to_string(), is_first, v);
set_block_param(block, h, obj_path, &key, v)?;
}
t.render(r, ctx, rc, out)?;
}
rc.pop_block();
Ok(())
}
_ => {
if let Some(else_template) = h.inverse() {
else_template.render(r, ctx, rc, out)
} else if r.strict_mode() {
Err(RenderError::strict_error(value.relative_path()))
} else {
Ok(())
}
}
},
None => Ok(()),
}
}
sourcepub fn dev_mode(&self) -> bool
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.
sourcepub fn set_dev_mode(&mut self, enabled: bool)
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.
sourcepub fn set_prevent_indent(&mut self, enable: bool)
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
.
sourcepub fn prevent_indent(&self) -> bool
pub fn prevent_indent(&self) -> bool
Return state for prevent_indent
option, default to false
.
sourcepub fn register_template(&mut self, name: &str, tpl: Template)
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.
Examples found in repository?
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
pub fn register_template_string<S>(
&mut self,
name: &str,
tpl_str: S,
) -> Result<(), TemplateError>
where
S: AsRef<str>,
{
let template = Template::compile2(
tpl_str.as_ref(),
TemplateOptions {
name: Some(name.to_owned()),
prevent_indent: self.prevent_indent,
},
)?;
self.register_template(name, template);
Ok(())
}
sourcepub fn register_template_string<S>(
&mut self,
name: &str,
tpl_str: S
) -> Result<(), TemplateError>where
S: AsRef<str>,
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.
Examples found in repository?
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
pub fn register_partial<S>(&mut self, name: &str, partial_str: S) -> Result<(), TemplateError>
where
S: AsRef<str>,
{
self.register_template_string(name, partial_str)
}
/// 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.
pub fn register_template_file<P>(
&mut self,
name: &str,
tpl_path: P,
) -> Result<(), TemplateError>
where
P: AsRef<Path>,
{
let source = FileSource::new(tpl_path.as_ref().into());
let template_string = source
.load()
.map_err(|err| TemplateError::from((err, name.to_owned())))?;
self.register_template_string(name, template_string)?;
if self.dev_mode {
self.template_sources
.insert(name.to_owned(), Arc::new(source));
}
Ok(())
}
/// 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. All registered
/// will use their relative name as template name. For example, when `dir_path` is
/// `templates/` and `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 enabled, like `register_template_file`, templates is reloaded
/// from file system everytime it's visied.
#[cfg(feature = "dir_source")]
#[cfg_attr(docsrs, doc(cfg(feature = "dir_source")))]
pub fn register_templates_directory<P>(
&mut self,
tpl_extension: &str,
dir_path: P,
) -> Result<(), TemplateError>
where
P: AsRef<Path>,
{
let dir_path = dir_path.as_ref();
let walker = WalkDir::new(dir_path);
let dir_iter = walker
.min_depth(1)
.into_iter()
.filter_map(|e| e.ok().map(|e| e.into_path()))
// Checks if extension matches
.filter(|tpl_path| tpl_path.to_string_lossy().ends_with(tpl_extension))
// Rejects any hidden or temporary files.
.filter(|tpl_path| {
tpl_path
.file_stem()
.map(|stem| stem.to_string_lossy())
.map(|stem| !(stem.starts_with('.') || stem.starts_with('#')))
.unwrap_or(false)
})
.filter_map(|tpl_path| {
tpl_path
.strip_prefix(dir_path)
.ok()
.map(|tpl_canonical_name| {
let tpl_name = tpl_canonical_name
.components()
.map(|component| component.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
tpl_name
.strip_suffix(tpl_extension)
.map(|s| s.to_owned())
.unwrap_or(tpl_name)
})
.map(|tpl_canonical_name| (tpl_canonical_name, tpl_path))
});
for (tpl_canonical_name, tpl_path) in dir_iter {
self.register_template_file(&tpl_canonical_name, &tpl_path)?;
}
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, tpl_content)?;
}
}
Ok(())
}
sourcepub fn register_partial<S>(
&mut self,
name: &str,
partial_str: S
) -> Result<(), TemplateError>where
S: AsRef<str>,
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.
sourcepub fn register_template_file<P>(
&mut self,
name: &str,
tpl_path: P
) -> Result<(), TemplateError>where
P: AsRef<Path>,
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.
Examples found in repository?
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
pub fn register_templates_directory<P>(
&mut self,
tpl_extension: &str,
dir_path: P,
) -> Result<(), TemplateError>
where
P: AsRef<Path>,
{
let dir_path = dir_path.as_ref();
let walker = WalkDir::new(dir_path);
let dir_iter = walker
.min_depth(1)
.into_iter()
.filter_map(|e| e.ok().map(|e| e.into_path()))
// Checks if extension matches
.filter(|tpl_path| tpl_path.to_string_lossy().ends_with(tpl_extension))
// Rejects any hidden or temporary files.
.filter(|tpl_path| {
tpl_path
.file_stem()
.map(|stem| stem.to_string_lossy())
.map(|stem| !(stem.starts_with('.') || stem.starts_with('#')))
.unwrap_or(false)
})
.filter_map(|tpl_path| {
tpl_path
.strip_prefix(dir_path)
.ok()
.map(|tpl_canonical_name| {
let tpl_name = tpl_canonical_name
.components()
.map(|component| component.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
tpl_name
.strip_suffix(tpl_extension)
.map(|s| s.to_owned())
.unwrap_or(tpl_name)
})
.map(|tpl_canonical_name| (tpl_canonical_name, tpl_path))
});
for (tpl_canonical_name, tpl_path) in dir_iter {
self.register_template_file(&tpl_canonical_name, &tpl_path)?;
}
Ok(())
}
sourcepub fn register_templates_directory<P>(
&mut self,
tpl_extension: &str,
dir_path: P
) -> Result<(), TemplateError>where
P: AsRef<Path>,
Available on crate feature dir_source
only.
pub fn register_templates_directory<P>(
&mut self,
tpl_extension: &str,
dir_path: P
) -> Result<(), TemplateError>where
P: AsRef<Path>,
dir_source
only.Register templates from a directory
tpl_extension
: the template file extensiondir_path
: the path of directory
Hidden files and tempfile (starts with #
) will be ignored. All registered
will use their relative name as template name. For example, when dir_path
is
templates/
and 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 enabled, like register_template_file
, templates is reloaded
from file system everytime it’s visied.
sourcepub fn register_embed_templates<E>(&mut self) -> Result<(), TemplateError>where
E: RustEmbed,
Available on crate feature rust-embed
only.
pub fn register_embed_templates<E>(&mut self) -> Result<(), TemplateError>where
E: RustEmbed,
rust-embed
only.Register templates using a RustEmbed type
File names from embed struct are used as template name.
#[derive(RustEmbed)]
#[folder = "templates"]
struct Assets;
let mut hbs = Handlebars::new();
hbs.register_embed_templates::<Assets>();
sourcepub fn unregister_template(&mut self, name: &str)
pub fn unregister_template(&mut self, name: &str)
Remove a template from the registry
sourcepub fn register_helper(
&mut self,
name: &str,
def: Box<dyn HelperDef + Send + Sync + 'reg>
)
pub fn register_helper(
&mut self,
name: &str,
def: Box<dyn HelperDef + Send + Sync + 'reg>
)
Register a helper
Examples found in repository?
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
fn setup_builtins(mut self) -> Registry<'reg> {
self.register_helper("if", Box::new(helpers::IF_HELPER));
self.register_helper("unless", Box::new(helpers::UNLESS_HELPER));
self.register_helper("each", Box::new(helpers::EACH_HELPER));
self.register_helper("with", Box::new(helpers::WITH_HELPER));
self.register_helper("lookup", Box::new(helpers::LOOKUP_HELPER));
self.register_helper("raw", Box::new(helpers::RAW_HELPER));
self.register_helper("log", Box::new(helpers::LOG_HELPER));
self.register_helper("eq", Box::new(helpers::helper_extras::eq));
self.register_helper("ne", Box::new(helpers::helper_extras::ne));
self.register_helper("gt", Box::new(helpers::helper_extras::gt));
self.register_helper("gte", Box::new(helpers::helper_extras::gte));
self.register_helper("lt", Box::new(helpers::helper_extras::lt));
self.register_helper("lte", Box::new(helpers::helper_extras::lte));
self.register_helper("and", Box::new(helpers::helper_extras::and));
self.register_helper("or", Box::new(helpers::helper_extras::or));
self.register_helper("not", Box::new(helpers::helper_extras::not));
self.register_helper("len", Box::new(helpers::helper_extras::len));
self.register_decorator("inline", Box::new(decorators::INLINE_DECORATOR));
self
}
sourcepub fn register_script_helper(
&mut self,
name: &str,
script: &str
) -> Result<(), ScriptError>
Available on crate feature script_helper
only.
pub fn register_script_helper(
&mut self,
name: &str,
script: &str
) -> Result<(), ScriptError>
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
Examples found in repository?
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
pub fn register_script_helper_file<P>(
&mut self,
name: &str,
script_path: P,
) -> Result<(), ScriptError>
where
P: AsRef<Path>,
{
let source = FileSource::new(script_path.as_ref().into());
let script = source.load()?;
self.script_sources
.insert(name.to_owned(), Arc::new(source));
self.register_script_helper(name, &script)
}
sourcepub 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.
pub fn register_script_helper_file<P>(
&mut self,
name: &str,
script_path: P
) -> Result<(), ScriptError>where
P: AsRef<Path>,
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.
sourcepub fn engine(&self) -> &Engine
Available on crate feature script_helper
only.
pub fn engine(&self) -> &Engine
script_helper
only.Borrow a read-only reference to current rhai engine
sourcepub fn set_engine(&mut self, engine: Engine)
Available on crate feature script_helper
only.
pub fn set_engine(&mut self, engine: Engine)
script_helper
only.Set a custom rhai engine for the registry.
Note that you need to set custom engine before adding scripts.
sourcepub fn register_decorator(
&mut self,
name: &str,
def: Box<dyn DecoratorDef + Send + Sync + 'reg>
)
pub fn register_decorator(
&mut self,
name: &str,
def: Box<dyn DecoratorDef + Send + Sync + 'reg>
)
Register a decorator
Examples found in repository?
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
fn setup_builtins(mut self) -> Registry<'reg> {
self.register_helper("if", Box::new(helpers::IF_HELPER));
self.register_helper("unless", Box::new(helpers::UNLESS_HELPER));
self.register_helper("each", Box::new(helpers::EACH_HELPER));
self.register_helper("with", Box::new(helpers::WITH_HELPER));
self.register_helper("lookup", Box::new(helpers::LOOKUP_HELPER));
self.register_helper("raw", Box::new(helpers::RAW_HELPER));
self.register_helper("log", Box::new(helpers::LOG_HELPER));
self.register_helper("eq", Box::new(helpers::helper_extras::eq));
self.register_helper("ne", Box::new(helpers::helper_extras::ne));
self.register_helper("gt", Box::new(helpers::helper_extras::gt));
self.register_helper("gte", Box::new(helpers::helper_extras::gte));
self.register_helper("lt", Box::new(helpers::helper_extras::lt));
self.register_helper("lte", Box::new(helpers::helper_extras::lte));
self.register_helper("and", Box::new(helpers::helper_extras::and));
self.register_helper("or", Box::new(helpers::helper_extras::or));
self.register_helper("not", Box::new(helpers::helper_extras::not));
self.register_helper("len", Box::new(helpers::helper_extras::len));
self.register_decorator("inline", Box::new(decorators::INLINE_DECORATOR));
self
}
sourcepub fn register_escape_fn<F: 'static + Fn(&str) -> String + Send + Sync>(
&mut self,
escape_fn: F
)
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.
sourcepub fn unregister_escape_fn(&mut self)
pub fn unregister_escape_fn(&mut self)
Restore the default escape fn.
sourcepub fn get_escape_fn(&self) -> &dyn Fn(&str) -> String
pub fn get_escape_fn(&self) -> &dyn Fn(&str) -> String
Get a reference to the current escape fn.
sourcepub fn has_template(&self, name: &str) -> bool
pub fn has_template(&self, name: &str) -> bool
Return true
if a template is registered for the given name
sourcepub fn get_template(&self, name: &str) -> Option<&Template>
pub fn get_template(&self, name: &str) -> Option<&Template>
Return a registered template,
sourcepub fn get_templates(&self) -> &HashMap<String, Template>
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.
sourcepub fn clear_templates(&mut self)
pub fn clear_templates(&mut self)
Unregister all templates
sourcepub fn render<T>(&self, name: &str, data: &T) -> Result<String, RenderError>where
T: Serialize,
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 previouslydata
is the data that implementsserde::Serialize
Returns rendered string or a struct with error information
sourcepub fn render_with_context(
&self,
name: &str,
ctx: &Context
) -> Result<String, RenderError>
pub fn render_with_context(
&self,
name: &str,
ctx: &Context
) -> Result<String, RenderError>
Render a registered template with reused context
sourcepub fn render_to_write<T, W>(
&self,
name: &str,
data: &T,
writer: W
) -> Result<(), RenderError>where
T: Serialize,
W: Write,
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
sourcepub fn render_with_context_to_write<W>(
&self,
name: &str,
ctx: &Context,
writer: W
) -> Result<(), RenderError>where
W: Write,
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
sourcepub fn render_template<T>(
&self,
template_string: &str,
data: &T
) -> Result<String, RenderError>where
T: Serialize,
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
sourcepub fn render_template_with_context(
&self,
template_string: &str,
ctx: &Context
) -> Result<String, RenderError>
pub fn render_template_with_context(
&self,
template_string: &str,
ctx: &Context
) -> Result<String, RenderError>
Render a template string using reusable context data
sourcepub fn render_template_with_context_to_write<W>(
&self,
template_string: &str,
ctx: &Context,
writer: W
) -> Result<(), RenderError>where
W: Write,
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
Examples found in repository?
702 703 704 705 706 707 708 709 710 711 712 713 714
pub fn render_template_to_write<T, W>(
&self,
template_string: &str,
data: &T,
writer: W,
) -> Result<(), RenderError>
where
T: Serialize,
W: Write,
{
let ctx = Context::wraps(data)?;
self.render_template_with_context_to_write(template_string, &ctx, writer)
}
sourcepub fn render_template_to_write<T, W>(
&self,
template_string: &str,
data: &T,
writer: W
) -> Result<(), RenderError>where
T: Serialize,
W: Write,
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