Skip to content

Commit

Permalink
Merge pull request #6971 from gastaldi/loop
Browse files Browse the repository at this point in the history
Qute: Support iterating by number
  • Loading branch information
gsmet authored Feb 4, 2020
2 parents 9a1abca + 78b1b77 commit a63bba5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
18 changes: 17 additions & 1 deletion docs/src/main/asciidoc/qute-reference.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ A section helper that defines the logic of a section can "execute" any of the bl

===== Loop Section

The loop section makes it possible to iterate over an instance of `Iterable`, `Map` 's entry set and `Stream`.
The loop section makes it possible to iterate over an instance of `Iterable`, `Map` 's entry set, `Stream` and an Integer.
It has two flavors.
The first one is using the `each` name alias.

Expand Down Expand Up @@ -262,6 +262,22 @@ It's also possible to access the iteration metadata inside the loop:
----
<1> `count` represents one-based index. Metadata also include zero-based `index`, `hasNext`, `odd`, `even`.

The `for` statement also works with integers, starting from 1. In the example below, considering that `total = 3`:

[source]
----
{#for i in total}
{i}:
{/for}
----

The output will be:

[source]
----
1:2:3:
----

===== If Section

A basic control flow section.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
Expand Down Expand Up @@ -43,6 +44,8 @@ public CompletionStage<ResultNode> resolve(SectionResolutionContext context) {
iterator = ((Map<?, ?>) it).entrySet().iterator();
} else if (it instanceof Stream) {
iterator = ((Stream<?>) it).sequential().iterator();
} else if (it instanceof Integer) {
iterator = IntStream.rangeClosed(1, (Integer) it).iterator();
} else {
throw new IllegalStateException("Cannot iterate over: " + it);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,14 @@ public CompletionStage<Object> resolve(EvalContext context) {
engine.parse(template).render(data));
}

@Test
public void testIntegerStream() {
Engine engine = Engine.builder()
.addSectionHelper(new LoopSectionHelper.Factory()).addDefaultValueResolvers()
.build();

assertEquals("1:2:3:",
engine.parse("{#for i in total}{i}:{/for}").data("total", 3).render());
}

}

0 comments on commit a63bba5

Please sign in to comment.