Skip to content

Commit

Permalink
Allow destructure in loops.
Browse files Browse the repository at this point in the history
When looping over an iterable of tuples, it should be possible
to destructure the tuple into individual variables directly in
the loop construct.

Suggested by @nubis in #14.
  • Loading branch information
kaj committed Jun 27, 2017
1 parent d0884a3 commit 3e6e59d
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
7 changes: 7 additions & 0 deletions examples/simple/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ fn test_list() {
"<ul>\n \n <li>foo</li>\n \n <li>bar</li>\n </ul>\n");
}

#[test]
fn test_list_destructure() {
assert_eq!(r2s(|o| list_destructure(o, &["foo", "bar"])),
"<ul>\n \n <li>0: foo</li>\n \n \
<li>1: bar</li>\n </ul>\n");
}

#[test]
fn test_uselist() {
assert_eq!(r2s(|o| uselist(o)),
Expand Down
7 changes: 7 additions & 0 deletions examples/simple/templates/list_destructure.rs.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@(items: &[&str])

<ul>
@for (n, item) in items.iter().enumerate() {
<li>@n: @item</li>
}
</ul>
2 changes: 1 addition & 1 deletion src/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ named!(pub expression<&[u8], String>,
}) >>
(format!("{}{}{}", from_utf8(pre).unwrap(), name, post))));

named!(comma_expressions<&[u8], String>,
named!(pub comma_expressions<&[u8], String>,
map!(separated_list!(tag!(", "), expression),
|list: Vec<_>| list.join(", ")));

Expand Down
12 changes: 9 additions & 3 deletions src/templateexpression.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use expression::{expression, rust_name};
use expression::{comma_expressions, expression, rust_name};
use spacelike::{comment, spacelike};
use std::fmt::{self, Display};
use std::str::from_utf8;
Expand Down Expand Up @@ -188,8 +188,14 @@ named!(pub template_expression<&[u8], TemplateExpression>,
}))) |
Some(b"for") => do_parse!(
spacelike >>
name: return_error!(err_str!("Expected loop variable name"),
rust_name) >>
name: return_error!(err_str!("Expected loop variable name \
or destructuring tuple"),
alt!(rust_name |
do_parse!(tag!("(") >>
args: comma_expressions >>
tag!(")") >>
(format!("({})", args)))
)) >>
spacelike >>
return_error!(err_str!("Expected \"in\""), tag!("in")) >>
spacelike >>
Expand Down

0 comments on commit 3e6e59d

Please sign in to comment.