Struct handlebars::PathAndJson
source · pub struct PathAndJson<'reg, 'rc> { /* private fields */ }
Expand description
Json wrapper that holds the Json value and reference path information
Implementations§
source§impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc>
impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc>
sourcepub fn new(
relative_path: Option<String>,
value: ScopedJson<'reg, 'rc>
) -> PathAndJson<'reg, 'rc>
pub fn new(
relative_path: Option<String>,
value: ScopedJson<'reg, 'rc>
) -> PathAndJson<'reg, 'rc>
Examples found in repository?
src/render.rs (line 568)
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
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!(),
},
}
}
sourcepub fn relative_path(&self) -> Option<&String>
pub fn relative_path(&self) -> Option<&String>
Returns relative path when the value is referenced
If the value is from a literal, the path is None
Examples found in repository?
src/helpers/helper_log.rs (line 32)
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
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
_: &mut dyn Output,
) -> HelperResult {
let param_to_log = h
.params()
.iter()
.map(|p| {
if let Some(ref relative_path) = p.relative_path() {
format!("{}: {}", relative_path, p.value().render())
} else {
p.value().render()
}
})
.collect::<Vec<String>>()
.join(", ");
let level = h
.hash_get("level")
.and_then(|v| v.value().as_str())
.unwrap_or("info");
if let Ok(log_level) = Level::from_str(level) {
log!(log_level, "{}", param_to_log)
} else {
return Err(RenderError::new(&format!(
"Unsupported logging level {}",
level
)));
}
Ok(())
}
More examples
src/helpers/helper_with.rs (line 52)
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(())
}
}
src/render.rs (line 815)
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(()),
}
}
src/helpers/helper_each.rs (line 147)
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 context_path(&self) -> Option<&Vec<String>>
pub fn context_path(&self) -> Option<&Vec<String>>
Returns full path to this value if any
Examples found in repository?
src/helpers/block_util.rs (line 9)
4 5 6 7 8 9 10 11 12 13 14 15 16 17
pub(crate) fn create_block<'reg: 'rc, 'rc>(
param: &'rc PathAndJson<'reg, 'rc>,
) -> BlockContext<'reg> {
let mut block = BlockContext::new();
if let Some(new_path) = param.context_path() {
*block.base_path_mut() = new_path.clone();
} else {
// use clone for now
block.set_base_value(param.value().clone());
}
block
}
More examples
src/helpers/helper_with.rs (line 32)
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(())
}
}
src/helpers/helper_each.rs (line 91)
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(()),
}
}
src/partial.rs (line 78)
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 value(&self) -> &Json
pub fn value(&self) -> &Json
Returns the value
Examples found in repository?
src/helpers/block_util.rs (line 13)
4 5 6 7 8 9 10 11 12 13 14 15 16 17
pub(crate) fn create_block<'reg: 'rc, 'rc>(
param: &'rc PathAndJson<'reg, 'rc>,
) -> BlockContext<'reg> {
let mut block = BlockContext::new();
if let Some(new_path) = param.context_path() {
*block.base_path_mut() = new_path.clone();
} else {
// use clone for now
block.set_base_value(param.value().clone());
}
block
}
More examples
src/render.rs (line 606)
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
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(()),
}
}
src/helpers/helper_if.rs (line 28)
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
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 \"if\""))?;
let include_zero = h
.hash_get("includeZero")
.and_then(|v| v.value().as_bool())
.unwrap_or(false);
let mut value = param.value().is_truthy(include_zero);
if !self.positive {
value = !value;
}
let tmpl = if value { h.template() } else { h.inverse() };
match tmpl {
Some(t) => t.render(r, ctx, rc, out),
None => Ok(()),
}
}
src/helpers/scripting.rs (line 26)
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
fn call_script_helper<'reg: 'rc, 'rc>(
params: &[PathAndJson<'reg, 'rc>],
hash: &BTreeMap<&'reg str, PathAndJson<'reg, 'rc>>,
engine: &Engine,
script: &AST,
) -> Result<ScopedJson<'reg, 'rc>, RenderError> {
let params: Dynamic = to_dynamic(params.iter().map(|p| p.value()).collect::<Vec<&Json>>())?;
let hash: Dynamic = to_dynamic(
hash.iter()
.map(|(k, v)| ((*k).to_owned(), v.value()))
.collect::<HashMap<String, &Json>>(),
)?;
let mut scope = Scope::new();
scope.push_dynamic("params", params);
scope.push_dynamic("hash", hash);
let result = engine
.eval_ast_with_scope::<Dynamic>(&mut scope, script)
.map_err(RenderError::from)?;
let result_json: Json = from_dynamic(&result)?;
Ok(ScopedJson::Derived(result_json))
}
src/helpers/helper_log.rs (line 33)
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
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
_: &mut dyn Output,
) -> HelperResult {
let param_to_log = h
.params()
.iter()
.map(|p| {
if let Some(ref relative_path) = p.relative_path() {
format!("{}: {}", relative_path, p.value().render())
} else {
p.value().render()
}
})
.collect::<Vec<String>>()
.join(", ");
let level = h
.hash_get("level")
.and_then(|v| v.value().as_str())
.unwrap_or("info");
if let Ok(log_level) = Level::from_str(level) {
log!(log_level, "{}", param_to_log)
} else {
return Err(RenderError::new(&format!(
"Unsupported logging level {}",
level
)));
}
Ok(())
}
Additional examples can be found in:
sourcepub fn is_value_missing(&self) -> bool
pub fn is_value_missing(&self) -> bool
Test if value is missing
Examples found in repository?
src/render.rs (line 813)
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(()),
}
}