Skip to content

Commit

Permalink
Special class, to support all attribute resolvers (#560)
Browse files Browse the repository at this point in the history
  • Loading branch information
ogrammer authored Dec 11, 2020
1 parent 370df63 commit 3bddb10
Showing 1 changed file with 21 additions and 9 deletions.
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

0 comments on commit 3bddb10

Please sign in to comment.