Debian Codegraph @

src/partial.rs

raw symbols SCIP
1 use std::borrow::Cow;
2 use std::collections::HashMap;
3
4 use serde_json::value::Value as Json;
5
6 use crate::block::BlockContext;
7 use crate::context::{merge_json, Context};
8 use crate::error::RenderError;
9 use crate::json::path::Path;
10 use crate::output::Output;
11 use crate::registry::Registry;
12 use crate::render::{Decorator, Evaluable, RenderContext, Renderable};
13 use crate::template::Template;
14 use crate::RenderErrorReason;
15
16 pub(crate) const PARTIAL_BLOCK: &str = "@partial-block";
17
18 fn find_partial<'reg: 'rc, 'rc: 'a, 'a>(
19 rc: &'a RenderContext<'reg, 'rc>,
20 r: &'reg Registry<'reg>,
21 d: &Decorator<'rc>,
22 name: &str,
23 ) -> Result<Option<Cow<'a, Template>>, RenderError> {
24 if let Some(partial) = rc.get_partial(name) {
25 return Ok(Some(Cow::Borrowed(partial)));
26 }
27
28 if let Some(tpl) = r.get_or_load_template_optional(name) {
29 return tpl.map(Option::Some);
30 }
31
32 if let Some(tpl) = d.template() {
33 return Ok(Some(Cow::Borrowed(tpl)));
34 }
35
36 Ok(None)
37 }
38
39 pub fn expand_partial<'reg: 'rc, 'rc>(
40 d: &Decorator<'rc>,
41 r: &'reg Registry<'reg>,
42 ctx: &'rc Context,
43 rc: &mut RenderContext<'reg, 'rc>,
44 out: &mut dyn Output,
45 ) -> Result<(), RenderError> {
46 // try eval inline partials first
47 if let Some(t) = d.template() {
48 t.eval(r, ctx, rc)?;
49 }
50
51 let tname = d.name();
52 if rc.is_current_template(tname) {
53 return Err(RenderErrorReason::CannotIncludeSelf.into());
54 }
55
56 let partial = find_partial(rc, r, d, tname)?;
57
58 if let Some(t) = partial {
59 // clone to avoid lifetime issue
60 // FIXME refactor this to avoid
61 let mut local_rc = rc.clone();
62
63 // if tname == PARTIAL_BLOCK
64 let is_partial_block = tname == PARTIAL_BLOCK;
65
66 // add partial block depth there are consecutive partial
67 // blocks in the stack.
68 if is_partial_block {
69 local_rc.inc_partial_block_depth();
70 } else {
71 // depth cannot be lower than 0, which is guaranted in the
72 // `dec_partial_block_depth` method
73 local_rc.dec_partial_block_depth();
74 }
75
76 let mut block_created = false;
77
78 // create context if param given
79 if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) {
80 // path given, update base_path
81 let mut block_inner = BlockContext::new();
82 *block_inner.base_path_mut() = base_path.to_vec();
83
84 // because block is moved here, we need another bool variable to track
85 // its status for later cleanup
86 block_created = true;
87 // clear blocks to prevent block params from parent
88 // template to be leaked into partials
89 // see `test_partial_context_issue_495` for the case.
90 local_rc.clear_blocks();
91 local_rc.push_block(block_inner);
92 }
93
94 if !d.hash().is_empty() {
95 // hash given, update base_value
96 let hash_ctx = d
97 .hash()
98 .iter()
99 .map(|(k, v)| (*k, v.value()))
100 .collect::<HashMap<&str, &Json>>();
101
102 // create block if we didn't (no param provided for partial expression)
103 if !block_created {
104 let block_inner = if let Some(block) = local_rc.block() {
105 // reuse current block information, including base_path and
106 // base_value if any
107 block.clone()
108 } else {
109 BlockContext::new()
110 };
111
112 local_rc.clear_blocks();
113 local_rc.push_block(block_inner);
114 }
115
116 // evaluate context within current block, this includes block
117 // context provided by partial expression parameter
118 let merged_context = merge_json(
119 local_rc.evaluate2(ctx, &Path::current())?.as_json(),
120 &hash_ctx,
121 );
122
123 // update the base value, there must be a block for this so it's
124 // also safe to unwrap.
125 if let Some(block) = local_rc.block_mut() {
126 block.set_base_value(merged_context);
127 }
128 }
129
130 // @partial-block
131 if let Some(pb) = d.template() {
132 local_rc.push_partial_block(pb);
133 }
134
135 // indent
136 local_rc.set_indent_string(d.indent());
137
138 let result = t.render(r, ctx, &mut local_rc, out);
139
140 // cleanup
141 if block_created {
142 local_rc.pop_block();
143 }
144
145 if d.template().is_some() {
146 local_rc.pop_partial_block();
147 }
148
149 result
150 } else {
151 Err(RenderErrorReason::PartialNotFound(tname.to_owned()).into())
152 }
153 }
154
155 #[cfg(test)]
156 mod test {
157 use crate::context::Context;
158 use crate::error::RenderError;
159 use crate::output::Output;
160 use crate::registry::Registry;
161 use crate::render::{Helper, RenderContext};
162
163 #[test]
164 fn test() {
165 let mut handlebars = Registry::new();
166 assert!(handlebars
167 .register_template_string("t0", "{{> t1}}")
168 .is_ok());
169 assert!(handlebars
170 .register_template_string("t1", "{{this}}")
171 .is_ok());
172 assert!(handlebars
173 .register_template_string("t2", "{{#> t99}}not there{{/t99}}")
174 .is_ok());
175 assert!(handlebars
176 .register_template_string("t3", "{{#*inline \"t31\"}}{{this}}{{/inline}}{{> t31}}")
177 .is_ok());
178 assert!(handlebars
179 .register_template_string(
180 "t4",
181 "{{#> t5}}{{#*inline \"nav\"}}navbar{{/inline}}{{/t5}}"
182 )
183 .is_ok());
184 assert!(handlebars
185 .register_template_string("t5", "include {{> nav}}")
186 .is_ok());
187 assert!(handlebars
188 .register_template_string("t6", "{{> t1 a}}")
189 .is_ok());
190 assert!(handlebars
191 .register_template_string(
192 "t7",
193 "{{#*inline \"t71\"}}{{a}}{{/inline}}{{> t71 a=\"world\"}}"
194 )
195 .is_ok());
196 assert!(handlebars.register_template_string("t8", "{{a}}").is_ok());
197 assert!(handlebars
198 .register_template_string("t9", "{{> t8 a=2}}")
199 .is_ok());
200
201 assert_eq!(handlebars.render("t0", &1).ok().unwrap(), "1".to_string());
202 assert_eq!(
203 handlebars.render("t2", &1).ok().unwrap(),
204 "not there".to_string()
205 );
206 assert_eq!(handlebars.render("t3", &1).ok().unwrap(), "1".to_string());
207 assert_eq!(
208 handlebars.render("t4", &1).ok().unwrap(),
209 "include navbar".to_string()
210 );
211 assert_eq!(
212 handlebars.render("t6", &json!({"a": "2"})).ok().unwrap(),
213 "2".to_string()
214 );
215 assert_eq!(
216 handlebars.render("t7", &1).ok().unwrap(),
217 "world".to_string()
218 );
219 assert_eq!(handlebars.render("t9", &1).ok().unwrap(), "2".to_string());
220 }
221
222 #[test]
223 fn test_include_partial_block() {
224 let t0 = "hello {{> @partial-block}}";
225 let t1 = "{{#> t0}}inner {{this}}{{/t0}}";
226
227 let mut handlebars = Registry::new();
228 assert!(handlebars.register_template_string("t0", t0).is_ok());
229 assert!(handlebars.register_template_string("t1", t1).is_ok());
230
231 let r0 = handlebars.render("t1", &true);
232 assert_eq!(r0.ok().unwrap(), "hello inner true".to_string());
233 }
234
235 #[test]
236 fn test_self_inclusion() {
237 let t0 = "hello {{> t1}} {{> t0}}";
238 let t1 = "some template";
239 let mut handlebars = Registry::new();
240 assert!(handlebars.register_template_string("t0", t0).is_ok());
241 assert!(handlebars.register_template_string("t1", t1).is_ok());
242
243 let r0 = handlebars.render("t0", &true);
244 assert!(r0.is_err());
245 }
246
247 #[test]
248 fn test_issue_143() {
249 let main_template = "one{{> two }}three{{> two }}";
250 let two_partial = "--- two ---";
251
252 let mut handlebars = Registry::new();
253 assert!(handlebars
254 .register_template_string("template", main_template)
255 .is_ok());
256 assert!(handlebars
257 .register_template_string("two", two_partial)
258 .is_ok());
259
260 let r0 = handlebars.render("template", &true);
261 assert_eq!(r0.ok().unwrap(), "one--- two ---three--- two ---");
262 }
263
264 #[test]
265 fn test_hash_context_outscope() {
266 let main_template = "In: {{> p a=2}} Out: {{a}}";
267 let p_partial = "{{a}}";
268
269 let mut handlebars = Registry::new();
270 assert!(handlebars
271 .register_template_string("template", main_template)
272 .is_ok());
273 assert!(handlebars.register_template_string("p", p_partial).is_ok());
274
275 let r0 = handlebars.render("template", &true);
276 assert_eq!(r0.ok().unwrap(), "In: 2 Out: ");
277 }
278
279 #[test]
280 fn test_partial_context_hash() {
281 let mut hbs = Registry::new();
282 hbs.register_template_string("one", "This is a test. {{> two name=\"fred\" }}")
283 .unwrap();
284 hbs.register_template_string("two", "Lets test {{name}}")
285 .unwrap();
286 assert_eq!(
287 "This is a test. Lets test fred",
288 hbs.render("one", &0).unwrap()
289 );
290 }
291
292 #[test]
293 fn teset_partial_context_with_both_hash_and_param() {
294 let mut hbs = Registry::new();
295 hbs.register_template_string("one", "This is a test. {{> two this name=\"fred\" }}")
296 .unwrap();
297 hbs.register_template_string("two", "Lets test {{name}} and {{root_name}}")
298 .unwrap();
299 assert_eq!(
300 "This is a test. Lets test fred and tom",
301 hbs.render("one", &json!({"root_name": "tom"})).unwrap()
302 );
303 }
304
305 #[test]
306 fn test_partial_subexpression_context_hash() {
307 let mut hbs = Registry::new();
308 hbs.register_template_string("one", "This is a test. {{> (x @root) name=\"fred\" }}")
309 .unwrap();
310 hbs.register_template_string("two", "Lets test {{name}}")
311 .unwrap();
312
313 hbs.register_helper(
314 "x",
315 Box::new(
316 |_: &Helper<'_>,
317 _: &Registry<'_>,
318 _: &Context,
319 _: &mut RenderContext<'_, '_>,
320 out: &mut dyn Output|
321 -> Result<(), RenderError> {
322 out.write("two")?;
323 Ok(())
324 },
325 ),
326 );
327 assert_eq!(
328 "This is a test. Lets test fred",
329 hbs.render("one", &0).unwrap()
330 );
331 }
332
333 #[test]
334 fn test_nested_partial_scope() {
335 let t = "{{#*inline \"pp\"}}{{a}} {{b}}{{/inline}}{{#each c}}{{> pp a=2}}{{/each}}";
336 let data = json!({"c": [{"b": true}, {"b": false}]});
337
338 let mut handlebars = Registry::new();
339 assert!(handlebars.register_template_string("t", t).is_ok());
340 let r0 = handlebars.render("t", &data);
341 assert_eq!(r0.ok().unwrap(), "2 true2 false");
342 }
343
344 #[test]
345 fn test_nested_partial_block() {
346 let mut handlebars = Registry::new();
347 let template1 = "<outer>{{> @partial-block }}</outer>";
348 let template2 = "{{#> t1 }}<inner>{{> @partial-block }}</inner>{{/ t1 }}";
349 let template3 = "{{#> t2 }}Hello{{/ t2 }}";
350
351 handlebars
352 .register_template_string("t1", &template1)
353 .unwrap();
354 handlebars
355 .register_template_string("t2", &template2)
356 .unwrap();
357
358 let page = handlebars.render_template(&template3, &json!({})).unwrap();
359 assert_eq!("<outer><inner>Hello</inner></outer>", page);
360 }
361
362 #[test]
363 fn test_up_to_partial_level() {
364 let outer = r#"{{>inner name="fruit:" vegetables=fruits}}"#;
365 let inner = "{{#each vegetables}}{{../name}} {{this}},{{/each}}";
366
367 let data = json!({ "fruits": ["carrot", "tomato"] });
368
369 let mut handlebars = Registry::new();
370 handlebars.register_template_string("outer", outer).unwrap();
371 handlebars.register_template_string("inner", inner).unwrap();
372
373 assert_eq!(
374 handlebars.render("outer", &data).unwrap(),
375 "fruit: carrot,fruit: tomato,"
376 );
377 }
378
379 #[test]
380 fn line_stripping_with_inline_and_partial() {
381 let tpl0 = r#"{{#*inline "foo"}}foo
382 {{/inline}}
383 {{> foo}}
384 {{> foo}}
385 {{> foo}}"#;
386 let tpl1 = r#"{{#*inline "foo"}}foo{{/inline}}
387 {{> foo}}
388 {{> foo}}
389 {{> foo}}"#;
390
391 let hbs = Registry::new();
392 assert_eq!(
393 r#"foo
394 foo
395 foo
396 "#,
397 hbs.render_template(tpl0, &json!({})).unwrap()
398 );
399 assert_eq!(
400 r#"
401 foofoofoo"#,
402 hbs.render_template(tpl1, &json!({})).unwrap()
403 );
404 }
405
406 #[test]
407 fn test_partial_indent() {
408 let outer = r#" {{> inner inner_solo}}
409
410 {{#each inners}}
411 {{> inner}}
412 {{/each}}
413
414 {{#each inners}}
415 {{> inner}}
416 {{/each}}
417 "#;
418 let inner = r#"name: {{name}}
419 "#;
420
421 let mut hbs = Registry::new();
422
423 hbs.register_template_string("inner", inner).unwrap();
424 hbs.register_template_string("outer", outer).unwrap();
425
426 let result = hbs
427 .render(
428 "outer",
429 &json!({
430 "inner_solo": {"name": "inner_solo"},
431 "inners": [
432 {"name": "hello"},
433 {"name": "there"}
434 ]
435 }),
436 )
437 .unwrap();
438
439 assert_eq!(
440 result,
441 r#" name: inner_solo
442
443 name: hello
444 name: there
445
446 name: hello
447 name: there
448 "#
449 );
450 }
451 // Rule::partial_expression should not trim leading indent by default
452
453 #[test]
454 fn test_partial_prevent_indent() {
455 let outer = r#" {{> inner inner_solo}}
456
457 {{#each inners}}
458 {{> inner}}
459 {{/each}}
460
461 {{#each inners}}
462 {{> inner}}
463 {{/each}}
464 "#;
465 let inner = r#"name: {{name}}
466 "#;
467
468 let mut hbs = Registry::new();
469 hbs.set_prevent_indent(true);
470
471 hbs.register_template_string("inner", inner).unwrap();
472 hbs.register_template_string("outer", outer).unwrap();
473
474 let result = hbs
475 .render(
476 "outer",
477 &json!({
478 "inner_solo": {"name": "inner_solo"},
479 "inners": [
480 {"name": "hello"},
481 {"name": "there"}
482 ]
483 }),
484 )
485 .unwrap();
486
487 assert_eq!(
488 result,
489 r#" name: inner_solo
490
491 name: hello
492 name: there
493
494 name: hello
495 name: there
496 "#
497 );
498 }
499
500 #[test]
501 fn test_nested_partials() {
502 let mut hb = Registry::new();
503 hb.register_template_string("partial", "{{> @partial-block}}")
504 .unwrap();
505 hb.register_template_string(
506 "index",
507 r#"{{#>partial}}
508 Yo
509 {{#>partial}}
510 Yo 2
511 {{/partial}}
512 {{/partial}}"#,
513 )
514 .unwrap();
515 assert_eq!(
516 r#" Yo
517 Yo 2
518 "#,
519 hb.render("index", &()).unwrap()
520 );
521
522 hb.register_template_string("partial2", "{{> @partial-block}}")
523 .unwrap();
524 let r2 = hb
525 .render_template(
526 r#"{{#> partial}}
527 {{#> partial2}}
528 :(
529 {{/partial2}}
530 {{/partial}}"#,
531 &(),
532 )
533 .unwrap();
534 assert_eq!(":(\n", r2);
535 }
536
537 #[test]
538 fn test_partial_context_issue_495() {
539 let mut hb = Registry::new();
540 hb.register_template_string(
541 "t1",
542 r#"{{~#*inline "displayName"~}}
543 Template:{{name}}
544 {{/inline}}
545 {{#each data as |name|}}
546 Name:{{name}}
547 {{>displayName name="aaaa"}}
548 {{/each}}"#,
549 )
550 .unwrap();
551
552 hb.register_template_string(
553 "t1",
554 r#"{{~#*inline "displayName"~}}
555 Template:{{this}}
556 {{/inline}}
557 {{#each data as |name|}}
558 Name:{{name}}
559 {{>displayName}}
560 {{/each}}"#,
561 )
562 .unwrap();
563
564 let data = json!({
565 "data": ["hudel", "test"]
566 });
567
568 assert_eq!(
569 r#"Name:hudel
570 Template:hudel
571 Name:test
572 Template:test
573 "#,
574 hb.render("t1", &data).unwrap()
575 );
576 }
577
578 #[test]
579 fn test_multiline_partial_indent() {
580 let mut hb = Registry::new();
581
582 hb.register_template_string(
583 "t1",
584 r#"{{#*inline "thepartial"}}
585 inner first line
586 inner second line
587 {{/inline}}
588 {{> thepartial}}
589 outer third line"#,
590 )
591 .unwrap();
592 assert_eq!(
593 r#" inner first line
594 inner second line
595 outer third line"#,
596 hb.render("t1", &()).unwrap()
597 );
598
599 hb.register_template_string(
600 "t2",
601 r#"{{#*inline "thepartial"}}inner first line
602 inner second line
603 {{/inline}}
604 {{> thepartial}}
605 outer third line"#,
606 )
607 .unwrap();
608 assert_eq!(
609 r#" inner first line
610 inner second line
611 outer third line"#,
612 hb.render("t2", &()).unwrap()
613 );
614
615 hb.register_template_string(
616 "t3",
617 r#"{{#*inline "thepartial"}}{{a}}{{/inline}}
618 {{> thepartial}}
619 outer third line"#,
620 )
621 .unwrap();
622 assert_eq!(
623 r#"
624 inner first line
625 inner second lineouter third line"#,
626 hb.render("t3", &json!({"a": "inner first line\ninner second line"}))
627 .unwrap()
628 );
629
630 hb.register_template_string(
631 "t4",
632 r#"{{#*inline "thepartial"}}
633 inner first line
634 inner second line
635 {{/inline}}
636 {{~> thepartial}}
637 outer third line"#,
638 )
639 .unwrap();
640 assert_eq!(
641 r#" inner first line
642 inner second line
643 outer third line"#,
644 hb.render("t4", &()).unwrap()
645 );
646
647 let mut hb2 = Registry::new();
648 hb2.set_prevent_indent(true);
649
650 hb2.register_template_string(
651 "t1",
652 r#"{{#*inline "thepartial"}}
653 inner first line
654 inner second line
655 {{/inline}}
656 {{> thepartial}}
657 outer third line"#,
658 )
659 .unwrap();
660 assert_eq!(
661 r#" inner first line
662 inner second line
663 outer third line"#,
664 hb2.render("t1", &()).unwrap()
665 )
666 }
667
668 #[test]
669 fn test_issue_534() {
670 let t1 = "{{title}}";
671 let t2 = "{{#each modules}}{{> (lookup this \"module\") content name=0}}{{/each}}";
672
673 let data = json!({
674 "modules": [
675 {"module": "t1", "content": {"title": "foo"}},
676 {"module": "t1", "content": {"title": "bar"}},
677 ]
678 });
679
680 let mut hbs = Registry::new();
681 hbs.register_template_string("t1", t1).unwrap();
682 hbs.register_template_string("t2", t2).unwrap();
683
684 assert_eq!("foobar", hbs.render("t2", &data).unwrap());
685 }
686
687 #[test]
688 fn test_partial_not_found() {
689 let t1 = "{{> bar}}";
690 let hbs = Registry::new();
691 assert!(hbs.render_template(&t1, &()).is_err());
692 }
693 }