Skip to content

Commit

Permalink
Fixing nested for loops
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienros committed Mar 14, 2019
1 parent 1d2fccc commit f2aa794
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
35 changes: 34 additions & 1 deletion Fluid.Tests/ForStatementTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,40 @@ public async Task ForShouldProvideHelperVariables()
Assert.Equal("31023truefalse32112falsefalse33201falsetrue", sw.ToString());
}

[Fact]
public async Task ForShouldBeNestable()
{
var nested = new ForStatement(
new List<Statement> {
CreateMemberStatement("forloop.index")
},
"j",
new MemberExpression(
new IdentifierSegment("items")
),
null, null, false
);

var outer = new ForStatement(
new List<Statement> {
CreateMemberStatement("forloop.index"),
nested
},
"i",
new MemberExpression(
new IdentifierSegment("items")
),
null, null, false
);

var sw = new StringWriter();
var context = new TemplateContext();
context.SetValue("items", new[] { 1, 2, 3 });
await outer.WriteToAsync(sw, HtmlEncoder.Default, context);

Assert.Equal("112321233123", sw.ToString());
}

[Fact]
public async Task ForEvaluatesOptions()
{
Expand All @@ -174,7 +208,6 @@ public async Task ForEvaluatesOptions()
Assert.Equal("543", sw.ToString());
}


Statement CreateMemberStatement(string p)
{
return new OutputStatement(new MemberExpression(p.Split('.').Select(x => new IdentifierSegment(x)).ToArray()));
Expand Down
5 changes: 5 additions & 0 deletions Fluid/Ast/ForStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ public override async ValueTask<Completion> WriteToAsync(TextWriter writer, Text
var forloop = new ForLoopValue();

var length = forloop.Length = list.Count;

context.SetValue("forloop", forloop);

for (var i = 0; i < length; i++)
Expand All @@ -143,6 +144,10 @@ public override async ValueTask<Completion> WriteToAsync(TextWriter writer, Text
var statement = Statements[index];
completion = await statement.WriteToAsync(writer, encoder, context);

// Restore the forloop property after every statement in case it replaced it,
// for instance if it contains a nested for loop
context.SetValue("forloop", forloop);

if (completion != Completion.Normal)
{
// Stop processing the block statements
Expand Down

0 comments on commit f2aa794

Please sign in to comment.