From 230263711e7edb0110e1679f6d31353ba7cdc919 Mon Sep 17 00:00:00 2001 From: vallentin Date: Tue, 15 Dec 2020 07:12:24 +0100 Subject: Improved template loop generation (fixes #107, #333) --- askama_shared/src/generator.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'askama_shared/src/generator.rs') diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs index 146f9db..0053b38 100644 --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -667,8 +667,26 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { ", _loop_item) in ::askama::helpers::TemplateLoop::new({}) {{", expr_code )), + Expr::Array(..) => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new({}.iter()) {{", + expr_code + )), + // If `iter` is a call then we assume it's something that returns + // an iterator. If not then the user can explicitly add the needed + // call without issues. + Expr::MethodCall(..) | Expr::PathCall(..) | Expr::Index(..) => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new(({}).into_iter()) {{", + expr_code + )), + // If accessing `self` then it most likely needs to be + // borrowed, to prevent an attempt of moving. + _ if expr_code.starts_with("self.") => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new(((&{}).into_iter())) {{", + expr_code + )), + // Otherwise, we borrow `iter` assuming that it implements `IntoIterator`. _ => buf.writeln(&format!( - ", _loop_item) in ::askama::helpers::TemplateLoop::new((&{}).into_iter()) {{", + ", _loop_item) in ::askama::helpers::TemplateLoop::new(({}).into_iter()) {{", expr_code )), }?; -- cgit