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

Special for loop variables class, to support all attribute resolvers #560

Merged
merged 1 commit into from
Dec 11, 2020
Merged
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
30 changes: 21 additions & 9 deletions pebble/src/main/java/com/mitchellbosecke/pebble/node/ForNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ public ForNode(int lineNumber, String variableName, Expression<?> iterableExpres
this.elseBody = elseBody;
}

private static class LoopVariables {
public boolean first, last;
public LazyLength length;
public int index;
public LazyRevIndex revindex;

@Override
public String toString() {
return "{last=" + last + ", length=" + length + ", index=" + index + ", revindex=" + revindex + ", first=" + first + "}";
}
}

@Override
public void render(PebbleTemplateImpl self, Writer writer, EvaluationContextImpl context)
throws IOException {
Expand Down Expand Up @@ -78,7 +90,7 @@ public void render(PebbleTemplateImpl self, Writer writer, EvaluationContextImpl

int index = 0;

Map<String, Object> loop = null;
LoopVariables loop = null;

boolean usingExecutorService = context.getExecutorService() != null;

Expand All @@ -91,23 +103,23 @@ public void render(PebbleTemplateImpl self, Writer writer, EvaluationContextImpl
* would get it's own distinct copy of the context.
*/
if (index == 0 || usingExecutorService) {
loop = new HashMap<>();
loop.put("first", index == 0);
loop.put("last", !iterator.hasNext());
loop.put("length", length);
loop = new LoopVariables();
loop.first = index == 0;
loop.last = !iterator.hasNext();
loop.length = length;
} else if (index == 1) {
// second iteration
loop.put("first", false);
loop.first = false;
}

loop.put("revindex", new LazyRevIndex(index, length));
loop.put("index", index++);
loop.revindex = new LazyRevIndex(index, length);
loop.index = index++;
scopeChain.put("loop", loop);
scopeChain.put(this.variableName, iterator.next());

// last iteration
if (!iterator.hasNext()) {
loop.put("last", true);
loop.last = true;
}

this.body.render(self, writer, context);
Expand Down