Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parentloop support #511

Merged
merged 2 commits into from
Sep 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Fluid.Tests/ForStatementTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,16 @@ public async Task ForShouldProvideHelperVariables()
[Fact]
public async Task ForShouldBeNestable()
{
/*
* {% for i in items %}
* {{ forloop.index }}
* {% for j in items %}
* {{ forloop.index }}
* {% endfor %}
* {% endfor %}
*
*/

var nested = new ForStatement(
new List<Statement> {
CreateMemberStatement("forloop.index")
Expand Down Expand Up @@ -207,6 +217,50 @@ public async Task ForShouldBeNestable()
Assert.Equal("112321233123", sw.ToString());
}

[Fact]
public async Task NestedForShouldProvideParentLoop()
{
/*
* {% for i in items %}
* {{ forloop.index }}
* {% for j in items %}
* {{ parentloop.index }}
* {% endfor %}
* {% endfor %}
*
*/

var nested = new ForStatement(
new List<Statement> {
CreateMemberStatement("parentloop.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("111122223333", sw.ToString());
}

[Fact]
public async Task ForEvaluatesOptions()
{
Expand Down
7 changes: 7 additions & 0 deletions Fluid/Ast/ForStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ public override async ValueTask<Completion> WriteToAsync(TextWriter writer, Text
source.Reverse(startIndex, count);
}

var parentLoop = context.LocalScope.GetValue("forloop");

context.EnterForLoopScope();

try
Expand All @@ -113,6 +115,11 @@ public override async ValueTask<Completion> WriteToAsync(TextWriter writer, Text

context.LocalScope._properties["forloop"] = forloop;

if (!parentLoop.IsNil())
{
context.LocalScope._properties["parentloop"] = parentLoop;
}

for (var i = startIndex; i < length; i++)
{
context.IncrementSteps();
Expand Down