|
| 1 | +package com.github.jknack.handlebars; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.Iterator; |
| 5 | + |
| 6 | +import com.fasterxml.jackson.databind.JsonNode; |
| 7 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 8 | +import com.github.jknack.handlebars.context.MapValueResolver; |
| 9 | +import com.github.jknack.handlebars.helper.StringHelpers; |
| 10 | + |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +public class Issue964 extends AbstractTest { |
| 14 | + |
| 15 | + @Override |
| 16 | + protected Object configureContext(final Object model) { |
| 17 | + return Context.newBuilder(model) |
| 18 | + .resolver(MapValueResolver.INSTANCE, JsonNodeValueResolver.INSTANCE) |
| 19 | + .build(); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void shouldUnwrapJsonArraysAsIterables() throws IOException { |
| 24 | + Hash helpers = $("join", StringHelpers.join); |
| 25 | + JsonNode tree = new ObjectMapper().readTree("{\"pets\":[\"cat\",\"dog\",\"bird\"]}"); |
| 26 | + shouldCompileTo("{{join this.pets \", \"}}", tree, helpers, "cat, dog, bird"); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void shouldUnwrapJsonArraysByIndex() throws IOException { |
| 31 | + Hash helpers = $("join", StringHelpers.join); |
| 32 | + JsonNode tree = new ObjectMapper().readTree("{\"pets\":[\"cat\",\"dog\",\"bird\"]}"); |
| 33 | + shouldCompileTo("{{join this.pets.[0] this.pets.[1] this.pets.[2] \", \"}}", tree, helpers, "cat, dog, bird"); |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + public void shouldUnwrapJsonArraysRecursively() throws IOException { |
| 38 | + Hash helpers = $("elementAt", new ElementAtHelper(), "capitalize", StringHelpers.capitalize); |
| 39 | + JsonNode tree = new ObjectMapper().readTree("{\"kidsPets\":[[\"cat\",\"dog\"],[\"bird\",\"mouse\"]]}"); |
| 40 | + shouldCompileTo("{{capitalize (elementAt (elementAt this.kidsPets 0) 1)}}", tree, helpers, "Dog"); |
| 41 | + } |
| 42 | + |
| 43 | + private static class ElementAtHelper implements Helper<Iterable<Object>> { |
| 44 | + |
| 45 | + @Override |
| 46 | + public Object apply(Iterable<Object> context, Options options) throws IOException { |
| 47 | + int targetIndex = options.param(0); |
| 48 | + int currentIndex = 0; |
| 49 | + |
| 50 | + Iterator<Object> loop = context.iterator(); |
| 51 | + |
| 52 | + while (loop.hasNext()) { |
| 53 | + Object it = loop.next(); |
| 54 | + if (currentIndex++ == targetIndex) { |
| 55 | + return it; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + throw new IOException( |
| 60 | + "Cannot get element at " + targetIndex + ". " + |
| 61 | + "Iterable only has " + currentIndex + " elements." |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments