Struct handlebars::RenderContext
source · pub struct RenderContext<'reg, 'rc> { /* private fields */ }
Expand description
The context of a render call
This context stores information of a render and a writer where generated content is written to.
Implementations§
source§impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc>
impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc>
sourcepub fn new(root_template: Option<&'reg String>) -> RenderContext<'reg, 'rc>
pub fn new(root_template: Option<&'reg String>) -> RenderContext<'reg, 'rc>
Create a render context
Examples found in repository?
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
fn render_to_output<O>(
&self,
name: &str,
ctx: &Context,
output: &mut O,
) -> Result<(), RenderError>
where
O: Output,
{
self.get_or_load_template(name).and_then(|t| {
let mut render_context = RenderContext::new(t.name.as_ref());
t.render(self, ctx, &mut render_context, output)
})
}
/// 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
pub fn render<T>(&self, name: &str, data: &T) -> Result<String, RenderError>
where
T: Serialize,
{
let mut output = StringOutput::new();
let ctx = Context::wraps(data)?;
self.render_to_output(name, &ctx, &mut output)?;
output.into_string().map_err(RenderError::from)
}
/// Render a registered template with reused context
pub fn render_with_context(&self, name: &str, ctx: &Context) -> Result<String, RenderError> {
let mut output = StringOutput::new();
self.render_to_output(name, ctx, &mut output)?;
output.into_string().map_err(RenderError::from)
}
/// Render a registered template and write data to the `std::io::Write`
pub fn render_to_write<T, W>(&self, name: &str, data: &T, writer: W) -> Result<(), RenderError>
where
T: Serialize,
W: Write,
{
let mut output = WriteOutput::new(writer);
let ctx = Context::wraps(data)?;
self.render_to_output(name, &ctx, &mut output)
}
/// Render a registered template using reusable `Context`, and write data to
/// the `std::io::Write`
pub fn render_with_context_to_write<W>(
&self,
name: &str,
ctx: &Context,
writer: W,
) -> Result<(), RenderError>
where
W: Write,
{
let mut output = WriteOutput::new(writer);
self.render_to_output(name, ctx, &mut output)
}
/// Render a template string using current registry without registering it
pub fn render_template<T>(&self, template_string: &str, data: &T) -> Result<String, RenderError>
where
T: Serialize,
{
let mut writer = StringWriter::new();
self.render_template_to_write(template_string, data, &mut writer)?;
Ok(writer.into_string())
}
/// Render a template string using reusable context data
pub fn render_template_with_context(
&self,
template_string: &str,
ctx: &Context,
) -> Result<String, RenderError> {
let tpl = Template::compile2(
template_string,
TemplateOptions {
prevent_indent: self.prevent_indent,
..Default::default()
},
)?;
let mut out = StringOutput::new();
{
let mut render_context = RenderContext::new(None);
tpl.render(self, ctx, &mut render_context, &mut out)?;
}
out.into_string().map_err(RenderError::from)
}
/// Render a template string using resuable context, and write data into
/// `std::io::Write`
pub fn render_template_with_context_to_write<W>(
&self,
template_string: &str,
ctx: &Context,
writer: W,
) -> Result<(), RenderError>
where
W: Write,
{
let tpl = Template::compile2(
template_string,
TemplateOptions {
prevent_indent: self.prevent_indent,
..Default::default()
},
)?;
let mut render_context = RenderContext::new(None);
let mut out = WriteOutput::new(writer);
tpl.render(self, ctx, &mut render_context, &mut out)
}
sourcepub fn push_block(&mut self, block: BlockContext<'reg>)
pub fn push_block(&mut self, block: BlockContext<'reg>)
Push a block context into render context stack. This is typically called when you entering a block scope.
Examples found in repository?
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(())
}
}
More examples
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(()),
}
}
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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
pub fn expand_partial<'reg: 'rc, 'rc>(
d: &Decorator<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
// try eval inline partials first
if let Some(t) = d.template() {
t.eval(r, ctx, rc)?;
}
let tname = d.name();
if rc.is_current_template(tname) {
return Err(RenderError::new("Cannot include self in >"));
}
let partial = find_partial(rc, r, d, tname)?;
if let Some(t) = partial {
// clone to avoid lifetime issue
// FIXME refactor this to avoid
let mut local_rc = rc.clone();
// if tname == PARTIAL_BLOCK
let is_partial_block = tname == PARTIAL_BLOCK;
// add partial block depth there are consecutive partial
// blocks in the stack.
if is_partial_block {
local_rc.inc_partial_block_depth();
} else {
// depth cannot be lower than 0, which is guaranted in the
// `dec_partial_block_depth` method
local_rc.dec_partial_block_depth();
}
let mut block_created = false;
// create context if param given
if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
// path given, update base_path
let mut block_inner = BlockContext::new();
*block_inner.base_path_mut() = base_path.to_vec();
// because block is moved here, we need another bool variable to track
// its status for later cleanup
block_created = true;
// clear blocks to prevent block params from parent
// template to be leaked into partials
// see `test_partial_context_issue_495` for the case.
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
if !d.hash().is_empty() {
// hash given, update base_value
let hash_ctx = d
.hash()
.iter()
.map(|(k, v)| (*k, v.value()))
.collect::<HashMap<&str, &Json>>();
// create block if we didn't (no param provided for partial expression)
if !block_created {
let block_inner = if let Some(block) = local_rc.block() {
// reuse current block information, including base_path and
// base_value if any
block.clone()
} else {
BlockContext::new()
};
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
// evaluate context within current block, this includes block
// context provided by partial expression parameter
let merged_context = merge_json(
local_rc.evaluate2(ctx, &Path::current())?.as_json(),
&hash_ctx,
);
// update the base value, there must be a block for this so it's
// also safe to unwrap.
if let Some(block) = local_rc.block_mut() {
block.set_base_value(merged_context);
}
}
// @partial-block
if let Some(pb) = d.template() {
local_rc.push_partial_block(pb);
}
// indent
local_rc.set_indent_string(d.indent());
let result = t.render(r, ctx, &mut local_rc, out);
// cleanup
if block_created {
local_rc.pop_block();
}
if d.template().is_some() {
local_rc.pop_partial_block();
}
result
} else {
Ok(())
}
}
sourcepub fn pop_block(&mut self)
pub fn pop_block(&mut self)
Pop and drop current block context. This is typically called when leaving a block scope.
Examples found in repository?
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(())
}
}
More examples
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(()),
}
}
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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
pub fn expand_partial<'reg: 'rc, 'rc>(
d: &Decorator<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
// try eval inline partials first
if let Some(t) = d.template() {
t.eval(r, ctx, rc)?;
}
let tname = d.name();
if rc.is_current_template(tname) {
return Err(RenderError::new("Cannot include self in >"));
}
let partial = find_partial(rc, r, d, tname)?;
if let Some(t) = partial {
// clone to avoid lifetime issue
// FIXME refactor this to avoid
let mut local_rc = rc.clone();
// if tname == PARTIAL_BLOCK
let is_partial_block = tname == PARTIAL_BLOCK;
// add partial block depth there are consecutive partial
// blocks in the stack.
if is_partial_block {
local_rc.inc_partial_block_depth();
} else {
// depth cannot be lower than 0, which is guaranted in the
// `dec_partial_block_depth` method
local_rc.dec_partial_block_depth();
}
let mut block_created = false;
// create context if param given
if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
// path given, update base_path
let mut block_inner = BlockContext::new();
*block_inner.base_path_mut() = base_path.to_vec();
// because block is moved here, we need another bool variable to track
// its status for later cleanup
block_created = true;
// clear blocks to prevent block params from parent
// template to be leaked into partials
// see `test_partial_context_issue_495` for the case.
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
if !d.hash().is_empty() {
// hash given, update base_value
let hash_ctx = d
.hash()
.iter()
.map(|(k, v)| (*k, v.value()))
.collect::<HashMap<&str, &Json>>();
// create block if we didn't (no param provided for partial expression)
if !block_created {
let block_inner = if let Some(block) = local_rc.block() {
// reuse current block information, including base_path and
// base_value if any
block.clone()
} else {
BlockContext::new()
};
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
// evaluate context within current block, this includes block
// context provided by partial expression parameter
let merged_context = merge_json(
local_rc.evaluate2(ctx, &Path::current())?.as_json(),
&hash_ctx,
);
// update the base value, there must be a block for this so it's
// also safe to unwrap.
if let Some(block) = local_rc.block_mut() {
block.set_base_value(merged_context);
}
}
// @partial-block
if let Some(pb) = d.template() {
local_rc.push_partial_block(pb);
}
// indent
local_rc.set_indent_string(d.indent());
let result = t.render(r, ctx, &mut local_rc, out);
// cleanup
if block_created {
local_rc.pop_block();
}
if d.template().is_some() {
local_rc.pop_partial_block();
}
result
} else {
Ok(())
}
}
sourcepub fn block(&self) -> Option<&BlockContext<'reg>>
pub fn block(&self) -> Option<&BlockContext<'reg>>
Borrow a reference to current block context
Examples found in repository?
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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
pub fn expand_partial<'reg: 'rc, 'rc>(
d: &Decorator<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
// try eval inline partials first
if let Some(t) = d.template() {
t.eval(r, ctx, rc)?;
}
let tname = d.name();
if rc.is_current_template(tname) {
return Err(RenderError::new("Cannot include self in >"));
}
let partial = find_partial(rc, r, d, tname)?;
if let Some(t) = partial {
// clone to avoid lifetime issue
// FIXME refactor this to avoid
let mut local_rc = rc.clone();
// if tname == PARTIAL_BLOCK
let is_partial_block = tname == PARTIAL_BLOCK;
// add partial block depth there are consecutive partial
// blocks in the stack.
if is_partial_block {
local_rc.inc_partial_block_depth();
} else {
// depth cannot be lower than 0, which is guaranted in the
// `dec_partial_block_depth` method
local_rc.dec_partial_block_depth();
}
let mut block_created = false;
// create context if param given
if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
// path given, update base_path
let mut block_inner = BlockContext::new();
*block_inner.base_path_mut() = base_path.to_vec();
// because block is moved here, we need another bool variable to track
// its status for later cleanup
block_created = true;
// clear blocks to prevent block params from parent
// template to be leaked into partials
// see `test_partial_context_issue_495` for the case.
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
if !d.hash().is_empty() {
// hash given, update base_value
let hash_ctx = d
.hash()
.iter()
.map(|(k, v)| (*k, v.value()))
.collect::<HashMap<&str, &Json>>();
// create block if we didn't (no param provided for partial expression)
if !block_created {
let block_inner = if let Some(block) = local_rc.block() {
// reuse current block information, including base_path and
// base_value if any
block.clone()
} else {
BlockContext::new()
};
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
// evaluate context within current block, this includes block
// context provided by partial expression parameter
let merged_context = merge_json(
local_rc.evaluate2(ctx, &Path::current())?.as_json(),
&hash_ctx,
);
// update the base value, there must be a block for this so it's
// also safe to unwrap.
if let Some(block) = local_rc.block_mut() {
block.set_base_value(merged_context);
}
}
// @partial-block
if let Some(pb) = d.template() {
local_rc.push_partial_block(pb);
}
// indent
local_rc.set_indent_string(d.indent());
let result = t.render(r, ctx, &mut local_rc, out);
// cleanup
if block_created {
local_rc.pop_block();
}
if d.template().is_some() {
local_rc.pop_partial_block();
}
result
} else {
Ok(())
}
}
sourcepub fn block_mut(&mut self) -> Option<&mut BlockContext<'reg>>
pub fn block_mut(&mut self) -> Option<&mut BlockContext<'reg>>
Borrow a mutable reference to current block context in order to modify some data.
Examples found in repository?
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(()),
}
}
More examples
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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
pub fn expand_partial<'reg: 'rc, 'rc>(
d: &Decorator<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
// try eval inline partials first
if let Some(t) = d.template() {
t.eval(r, ctx, rc)?;
}
let tname = d.name();
if rc.is_current_template(tname) {
return Err(RenderError::new("Cannot include self in >"));
}
let partial = find_partial(rc, r, d, tname)?;
if let Some(t) = partial {
// clone to avoid lifetime issue
// FIXME refactor this to avoid
let mut local_rc = rc.clone();
// if tname == PARTIAL_BLOCK
let is_partial_block = tname == PARTIAL_BLOCK;
// add partial block depth there are consecutive partial
// blocks in the stack.
if is_partial_block {
local_rc.inc_partial_block_depth();
} else {
// depth cannot be lower than 0, which is guaranted in the
// `dec_partial_block_depth` method
local_rc.dec_partial_block_depth();
}
let mut block_created = false;
// create context if param given
if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
// path given, update base_path
let mut block_inner = BlockContext::new();
*block_inner.base_path_mut() = base_path.to_vec();
// because block is moved here, we need another bool variable to track
// its status for later cleanup
block_created = true;
// clear blocks to prevent block params from parent
// template to be leaked into partials
// see `test_partial_context_issue_495` for the case.
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
if !d.hash().is_empty() {
// hash given, update base_value
let hash_ctx = d
.hash()
.iter()
.map(|(k, v)| (*k, v.value()))
.collect::<HashMap<&str, &Json>>();
// create block if we didn't (no param provided for partial expression)
if !block_created {
let block_inner = if let Some(block) = local_rc.block() {
// reuse current block information, including base_path and
// base_value if any
block.clone()
} else {
BlockContext::new()
};
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
// evaluate context within current block, this includes block
// context provided by partial expression parameter
let merged_context = merge_json(
local_rc.evaluate2(ctx, &Path::current())?.as_json(),
&hash_ctx,
);
// update the base value, there must be a block for this so it's
// also safe to unwrap.
if let Some(block) = local_rc.block_mut() {
block.set_base_value(merged_context);
}
}
// @partial-block
if let Some(pb) = d.template() {
local_rc.push_partial_block(pb);
}
// indent
local_rc.set_indent_string(d.indent());
let result = t.render(r, ctx, &mut local_rc, out);
// cleanup
if block_created {
local_rc.pop_block();
}
if d.template().is_some() {
local_rc.pop_partial_block();
}
result
} else {
Ok(())
}
}
sourcepub fn context(&self) -> Option<Rc<Context>>
pub fn context(&self) -> Option<Rc<Context>>
Get the modified context data if any
Examples found in repository?
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
pub fn expand<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match self {
Parameter::Name(ref name) => {
// FIXME: raise error when expanding with name?
Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing))
}
Parameter::Path(ref path) => {
if let Some(rc_context) = rc.context() {
let result = rc.evaluate2(rc_context.borrow(), path)?;
Ok(PathAndJson::new(
Some(path.raw().to_owned()),
ScopedJson::Derived(result.as_json().clone()),
))
} else {
let result = rc.evaluate2(ctx, path)?;
Ok(PathAndJson::new(Some(path.raw().to_owned()), result))
}
}
Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))),
Parameter::Subexpression(ref t) => match *t.as_element() {
Expression(ref ht) => {
let name = ht.name.expand_as_name(registry, ctx, rc)?;
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
if let Some(ref d) = rc.get_local_helper(&name) {
call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)
} else {
let mut helper = registry.get_or_load_helper(&name)?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| {
RenderError::new(format!("Helper not defined: {:?}", ht.name))
})
.and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc))
}
}
_ => unreachable!(),
},
}
}
sourcepub fn set_context(&mut self, ctx: Context)
pub fn set_context(&mut self, ctx: Context)
Set new context data into the render process. This is typically called in decorators where user can modify the data they were rendering.
sourcepub fn evaluate(
&self,
context: &'rc Context,
relative_path: &str
) -> Result<ScopedJson<'reg, 'rc>, RenderError>
pub fn evaluate(
&self,
context: &'rc Context,
relative_path: &str
) -> Result<ScopedJson<'reg, 'rc>, RenderError>
Evaluate a Json path in current scope.
Typically you don’t need to evaluate it by yourself. The Helper and Decorator API will provide your evaluated value of their parameters and hash data.
sourcepub fn get_partial(&self, name: &str) -> Option<&Template>
pub fn get_partial(&self, name: &str) -> Option<&Template>
Get registered partial in this render context
Examples found in repository?
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
fn find_partial<'reg: 'rc, 'rc: 'a, 'a>(
rc: &'a RenderContext<'reg, 'rc>,
r: &'reg Registry<'reg>,
d: &Decorator<'reg, 'rc>,
name: &str,
) -> Result<Option<Cow<'a, Template>>, RenderError> {
if let Some(partial) = rc.get_partial(name) {
return Ok(Some(Cow::Borrowed(partial)));
}
if let Some(tpl) = r.get_or_load_template_optional(name) {
return tpl.map(Option::Some);
}
if let Some(tpl) = d.template() {
return Ok(Some(Cow::Borrowed(tpl)));
}
Ok(None)
}
sourcepub fn set_partial(&mut self, name: String, partial: &'reg Template)
pub fn set_partial(&mut self, name: String, partial: &'reg Template)
Register a partial for this context
Examples found in repository?
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
fn call<'reg: 'rc, 'rc>(
&self,
d: &Decorator<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> DecoratorResult {
let name = get_name(d)?;
let template = d
.template()
.ok_or_else(|| RenderError::new("inline should have a block"))?;
rc.set_partial(name, template);
Ok(())
}
sourcepub fn remove_partial(&mut self, name: &str)
pub fn remove_partial(&mut self, name: &str)
Remove a registered partial
sourcepub fn is_current_template(&self, p: &str) -> bool
pub fn is_current_template(&self, p: &str) -> bool
Test if given template name is current template.
Examples found in repository?
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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
pub fn expand_partial<'reg: 'rc, 'rc>(
d: &Decorator<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
// try eval inline partials first
if let Some(t) = d.template() {
t.eval(r, ctx, rc)?;
}
let tname = d.name();
if rc.is_current_template(tname) {
return Err(RenderError::new("Cannot include self in >"));
}
let partial = find_partial(rc, r, d, tname)?;
if let Some(t) = partial {
// clone to avoid lifetime issue
// FIXME refactor this to avoid
let mut local_rc = rc.clone();
// if tname == PARTIAL_BLOCK
let is_partial_block = tname == PARTIAL_BLOCK;
// add partial block depth there are consecutive partial
// blocks in the stack.
if is_partial_block {
local_rc.inc_partial_block_depth();
} else {
// depth cannot be lower than 0, which is guaranted in the
// `dec_partial_block_depth` method
local_rc.dec_partial_block_depth();
}
let mut block_created = false;
// create context if param given
if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
// path given, update base_path
let mut block_inner = BlockContext::new();
*block_inner.base_path_mut() = base_path.to_vec();
// because block is moved here, we need another bool variable to track
// its status for later cleanup
block_created = true;
// clear blocks to prevent block params from parent
// template to be leaked into partials
// see `test_partial_context_issue_495` for the case.
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
if !d.hash().is_empty() {
// hash given, update base_value
let hash_ctx = d
.hash()
.iter()
.map(|(k, v)| (*k, v.value()))
.collect::<HashMap<&str, &Json>>();
// create block if we didn't (no param provided for partial expression)
if !block_created {
let block_inner = if let Some(block) = local_rc.block() {
// reuse current block information, including base_path and
// base_value if any
block.clone()
} else {
BlockContext::new()
};
local_rc.clear_blocks();
local_rc.push_block(block_inner);
}
// evaluate context within current block, this includes block
// context provided by partial expression parameter
let merged_context = merge_json(
local_rc.evaluate2(ctx, &Path::current())?.as_json(),
&hash_ctx,
);
// update the base value, there must be a block for this so it's
// also safe to unwrap.
if let Some(block) = local_rc.block_mut() {
block.set_base_value(merged_context);
}
}
// @partial-block
if let Some(pb) = d.template() {
local_rc.push_partial_block(pb);
}
// indent
local_rc.set_indent_string(d.indent());
let result = t.render(r, ctx, &mut local_rc, out);
// cleanup
if block_created {
local_rc.pop_block();
}
if d.template().is_some() {
local_rc.pop_partial_block();
}
result
} else {
Ok(())
}
}
sourcepub fn register_local_helper(
&mut self,
name: &str,
def: Box<dyn HelperDef + Send + Sync + 'rc>
)
pub fn register_local_helper(
&mut self,
name: &str,
def: Box<dyn HelperDef + Send + Sync + 'rc>
)
Register a helper in this render context. This is a feature provided by Decorator where you can create temporary helpers.
sourcepub fn unregister_local_helper(&mut self, name: &str)
pub fn unregister_local_helper(&mut self, name: &str)
Remove a helper from render context
sourcepub fn get_local_helper(
&self,
name: &str
) -> Option<Rc<dyn HelperDef + Send + Sync + 'rc>>
pub fn get_local_helper(
&self,
name: &str
) -> Option<Rc<dyn HelperDef + Send + Sync + 'rc>>
Attempt to get a helper from current render context.
Examples found in repository?
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
pub fn expand<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match self {
Parameter::Name(ref name) => {
// FIXME: raise error when expanding with name?
Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing))
}
Parameter::Path(ref path) => {
if let Some(rc_context) = rc.context() {
let result = rc.evaluate2(rc_context.borrow(), path)?;
Ok(PathAndJson::new(
Some(path.raw().to_owned()),
ScopedJson::Derived(result.as_json().clone()),
))
} else {
let result = rc.evaluate2(ctx, path)?;
Ok(PathAndJson::new(Some(path.raw().to_owned()), result))
}
}
Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))),
Parameter::Subexpression(ref t) => match *t.as_element() {
Expression(ref ht) => {
let name = ht.name.expand_as_name(registry, ctx, rc)?;
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
if let Some(ref d) = rc.get_local_helper(&name) {
call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)
} else {
let mut helper = registry.get_or_load_helper(&name)?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| {
RenderError::new(format!("Helper not defined: {:?}", ht.name))
})
.and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc))
}
}
_ => unreachable!(),
},
}
}
}
impl Renderable for Template {
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> {
rc.set_current_template_name(self.name.as_ref());
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.render(registry, ctx, rc, out).map_err(|mut e| {
// add line/col number if the template has mapping data
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
if e.template_name.is_none() {
e.template_name = self.name.clone();
}
e
})?;
}
Ok(())
}
}
impl Evaluable for Template {
fn eval<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<(), RenderError> {
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.eval(registry, ctx, rc).map_err(|mut e| {
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
e.template_name = self.name.clone();
e
})?;
}
Ok(())
}
}
fn helper_exists<'reg: 'rc, 'rc>(
name: &str,
reg: &Registry<'reg>,
rc: &RenderContext<'reg, 'rc>,
) -> bool {
rc.has_local_helper(name) || reg.has_helper(name)
}
#[inline]
fn render_helper<'reg: 'rc, 'rc>(
ht: &'reg HelperTemplate,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
debug!(
"Rendering helper: {:?}, params: {:?}, hash: {:?}",
h.name(),
h.params(),
h.hash()
);
if let Some(ref d) = rc.get_local_helper(h.name()) {
d.call(&h, registry, ctx, rc, out)
} else {
let mut helper = registry.get_or_load_helper(h.name())?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name())))
.and_then(|d| d.call(&h, registry, ctx, rc, out))
}
}
sourcepub fn get_current_template_name(&self) -> Option<&'reg String>
pub fn get_current_template_name(&self) -> Option<&'reg String>
Returns the current template name. Note that the name can be vary from root template when you are rendering from partials.
sourcepub fn set_current_template_name(&mut self, name: Option<&'reg String>)
pub fn set_current_template_name(&mut self, name: Option<&'reg String>)
Set the current template name.
Examples found in repository?
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
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> {
rc.set_current_template_name(self.name.as_ref());
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.render(registry, ctx, rc, out).map_err(|mut e| {
// add line/col number if the template has mapping data
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
if e.template_name.is_none() {
e.template_name = self.name.clone();
}
e
})?;
}
Ok(())
}
sourcepub fn get_root_template_name(&self) -> Option<&'reg String>
pub fn get_root_template_name(&self) -> Option<&'reg String>
Get root template name if any.
This is the template name that you call render
from Handlebars
.
sourcepub fn is_disable_escape(&self) -> bool
pub fn is_disable_escape(&self) -> bool
Get the escape toggle
Examples found in repository?
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
fn call_helper_for_value<'reg: 'rc, 'rc>(
hd: &dyn HelperDef,
ht: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match hd.call_inner(ht, r, ctx, rc) {
Ok(result) => Ok(PathAndJson::new(None, result)),
Err(e) => {
if e.is_unimplemented() {
// parse value from output
let mut so = StringOutput::new();
// here we don't want subexpression result escaped,
// so we temporarily disable it
let disable_escape = rc.is_disable_escape();
rc.set_disable_escape(true);
hd.call(ht, r, ctx, rc, &mut so)?;
rc.set_disable_escape(disable_escape);
let string = so.into_string().map_err(RenderError::from)?;
Ok(PathAndJson::new(
None,
ScopedJson::Derived(Json::String(string)),
))
} else {
Err(e)
}
}
}
}
impl Parameter {
pub fn expand_as_name<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<Cow<'reg, str>, RenderError> {
match self {
Parameter::Name(ref name) => Ok(Cow::Borrowed(name)),
Parameter::Path(ref p) => Ok(Cow::Borrowed(p.raw())),
Parameter::Subexpression(_) => self
.expand(registry, ctx, rc)
.map(|v| v.value().render())
.map(Cow::Owned),
Parameter::Literal(ref j) => Ok(Cow::Owned(j.render())),
}
}
pub fn expand<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match self {
Parameter::Name(ref name) => {
// FIXME: raise error when expanding with name?
Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing))
}
Parameter::Path(ref path) => {
if let Some(rc_context) = rc.context() {
let result = rc.evaluate2(rc_context.borrow(), path)?;
Ok(PathAndJson::new(
Some(path.raw().to_owned()),
ScopedJson::Derived(result.as_json().clone()),
))
} else {
let result = rc.evaluate2(ctx, path)?;
Ok(PathAndJson::new(Some(path.raw().to_owned()), result))
}
}
Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))),
Parameter::Subexpression(ref t) => match *t.as_element() {
Expression(ref ht) => {
let name = ht.name.expand_as_name(registry, ctx, rc)?;
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
if let Some(ref d) = rc.get_local_helper(&name) {
call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)
} else {
let mut helper = registry.get_or_load_helper(&name)?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| {
RenderError::new(format!("Helper not defined: {:?}", ht.name))
})
.and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc))
}
}
_ => unreachable!(),
},
}
}
}
impl Renderable for Template {
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> {
rc.set_current_template_name(self.name.as_ref());
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.render(registry, ctx, rc, out).map_err(|mut e| {
// add line/col number if the template has mapping data
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
if e.template_name.is_none() {
e.template_name = self.name.clone();
}
e
})?;
}
Ok(())
}
}
impl Evaluable for Template {
fn eval<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<(), RenderError> {
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.eval(registry, ctx, rc).map_err(|mut e| {
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
e.template_name = self.name.clone();
e
})?;
}
Ok(())
}
}
fn helper_exists<'reg: 'rc, 'rc>(
name: &str,
reg: &Registry<'reg>,
rc: &RenderContext<'reg, 'rc>,
) -> bool {
rc.has_local_helper(name) || reg.has_helper(name)
}
#[inline]
fn render_helper<'reg: 'rc, 'rc>(
ht: &'reg HelperTemplate,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
debug!(
"Rendering helper: {:?}, params: {:?}, hash: {:?}",
h.name(),
h.params(),
h.hash()
);
if let Some(ref d) = rc.get_local_helper(h.name()) {
d.call(&h, registry, ctx, rc, out)
} else {
let mut helper = registry.get_or_load_helper(h.name())?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name())))
.and_then(|d| d.call(&h, registry, ctx, rc, out))
}
}
pub(crate) fn do_escape(r: &Registry<'_>, rc: &RenderContext<'_, '_>, content: String) -> String {
if !rc.is_disable_escape() {
r.get_escape_fn()(&content)
} else {
content
}
}
sourcepub fn set_disable_escape(&mut self, disable: bool)
pub fn set_disable_escape(&mut self, disable: bool)
Set the escape toggle. When toggle is on, escape_fn will be called when rendering.
Examples found in repository?
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 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 call_helper_for_value<'reg: 'rc, 'rc>(
hd: &dyn HelperDef,
ht: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match hd.call_inner(ht, r, ctx, rc) {
Ok(result) => Ok(PathAndJson::new(None, result)),
Err(e) => {
if e.is_unimplemented() {
// parse value from output
let mut so = StringOutput::new();
// here we don't want subexpression result escaped,
// so we temporarily disable it
let disable_escape = rc.is_disable_escape();
rc.set_disable_escape(true);
hd.call(ht, r, ctx, rc, &mut so)?;
rc.set_disable_escape(disable_escape);
let string = so.into_string().map_err(RenderError::from)?;
Ok(PathAndJson::new(
None,
ScopedJson::Derived(Json::String(string)),
))
} else {
Err(e)
}
}
}
}
impl Parameter {
pub fn expand_as_name<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<Cow<'reg, str>, RenderError> {
match self {
Parameter::Name(ref name) => Ok(Cow::Borrowed(name)),
Parameter::Path(ref p) => Ok(Cow::Borrowed(p.raw())),
Parameter::Subexpression(_) => self
.expand(registry, ctx, rc)
.map(|v| v.value().render())
.map(Cow::Owned),
Parameter::Literal(ref j) => Ok(Cow::Owned(j.render())),
}
}
pub fn expand<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
match self {
Parameter::Name(ref name) => {
// FIXME: raise error when expanding with name?
Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing))
}
Parameter::Path(ref path) => {
if let Some(rc_context) = rc.context() {
let result = rc.evaluate2(rc_context.borrow(), path)?;
Ok(PathAndJson::new(
Some(path.raw().to_owned()),
ScopedJson::Derived(result.as_json().clone()),
))
} else {
let result = rc.evaluate2(ctx, path)?;
Ok(PathAndJson::new(Some(path.raw().to_owned()), result))
}
}
Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))),
Parameter::Subexpression(ref t) => match *t.as_element() {
Expression(ref ht) => {
let name = ht.name.expand_as_name(registry, ctx, rc)?;
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
if let Some(ref d) = rc.get_local_helper(&name) {
call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)
} else {
let mut helper = registry.get_or_load_helper(&name)?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| {
RenderError::new(format!("Helper not defined: {:?}", ht.name))
})
.and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc))
}
}
_ => unreachable!(),
},
}
}
}
impl Renderable for Template {
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> {
rc.set_current_template_name(self.name.as_ref());
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.render(registry, ctx, rc, out).map_err(|mut e| {
// add line/col number if the template has mapping data
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
if e.template_name.is_none() {
e.template_name = self.name.clone();
}
e
})?;
}
Ok(())
}
}
impl Evaluable for Template {
fn eval<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
) -> Result<(), RenderError> {
let iter = self.elements.iter();
for (idx, t) in iter.enumerate() {
t.eval(registry, ctx, rc).map_err(|mut e| {
if e.line_no.is_none() {
if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
e.line_no = Some(line);
e.column_no = Some(col);
}
}
e.template_name = self.name.clone();
e
})?;
}
Ok(())
}
}
fn helper_exists<'reg: 'rc, 'rc>(
name: &str,
reg: &Registry<'reg>,
rc: &RenderContext<'reg, 'rc>,
) -> bool {
rc.has_local_helper(name) || reg.has_helper(name)
}
#[inline]
fn render_helper<'reg: 'rc, 'rc>(
ht: &'reg HelperTemplate,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
debug!(
"Rendering helper: {:?}, params: {:?}, hash: {:?}",
h.name(),
h.params(),
h.hash()
);
if let Some(ref d) = rc.get_local_helper(h.name()) {
d.call(&h, registry, ctx, rc, out)
} else {
let mut helper = registry.get_or_load_helper(h.name())?;
if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}
helper
.ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name())))
.and_then(|d| d.call(&h, registry, ctx, rc, out))
}
}
pub(crate) fn do_escape(r: &Registry<'_>, rc: &RenderContext<'_, '_>, content: String) -> String {
if !rc.is_disable_escape() {
r.get_escape_fn()(&content)
} else {
content
}
}
#[inline]
fn indent_aware_write(
v: &str,
rc: &mut RenderContext<'_, '_>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
if let Some(indent) = rc.get_indent_string() {
out.write(support::str::with_indent(v, indent).as_ref())?;
} else {
out.write(v.as_ref())?;
}
Ok(())
}
impl Renderable for TemplateElement {
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(()),
}
}
Trait Implementations§
source§impl<'reg, 'rc> Clone for RenderContext<'reg, 'rc>
impl<'reg, 'rc> Clone for RenderContext<'reg, 'rc>
source§fn clone(&self) -> RenderContext<'reg, 'rc>
fn clone(&self) -> RenderContext<'reg, 'rc>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more