diff --git a/src/main/java/liqp/LValue.java b/src/main/java/liqp/LValue.java index 9ff64c70..9d4f1f35 100644 --- a/src/main/java/liqp/LValue.java +++ b/src/main/java/liqp/LValue.java @@ -1,5 +1,6 @@ package liqp; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -103,6 +104,7 @@ public static boolean areEqual(Object a, Object b) { * * @return this value as an array. */ + @SuppressWarnings("unchecked") public Object[] asArray(Object value) { if(value == null) { @@ -117,6 +119,17 @@ public Object[] asArray(Object value) { return ((List) value).toArray(); } + if (value instanceof Map) { + + List keyValuePairs = new ArrayList<>(); + + for (Map.Entry entry : ((Map) value).entrySet()) { + keyValuePairs.add(new Object[]{ entry.getKey(), entry.getValue()}); + } + + return keyValuePairs.toArray(); + } + return new Object[]{value}; } diff --git a/src/test/java/liqp/tags/ForTest.java b/src/test/java/liqp/tags/ForTest.java index 5ae187b5..b654ed2c 100644 --- a/src/test/java/liqp/tags/ForTest.java +++ b/src/test/java/liqp/tags/ForTest.java @@ -2,6 +2,7 @@ import liqp.Template; import org.antlr.v4.runtime.RecognitionException; +import org.junit.Assert; import org.junit.Test; import java.util.HashMap; @@ -699,4 +700,23 @@ public void nestedTest() { assertThat(Template.parse(template).render(variables), is(expected)); } + + /* + * @template = Liquid::Template.parse("{% for item in hash %}{{ item[0] }} is {{ item[1] }};{% endfor %}") + * + * puts @template.render('hash' => {'a' => 'AAA', 'b' => 'BBB'}) + */ + @Test + public void mapTest() { + + // https://github.com/bkiers/Liqp/issues/125 + + String hash = "{ \"hash\": { \"a\": \"AAA\", \"b\": \"BBB\" } }"; + String template = "{% for item in hash %}{{ item[0] }} is {{ item[1] }};{% endfor %}"; + + String expected = "a is AAA;b is BBB;"; + String rendered = Template.parse(template).render(hash); + + Assert.assertThat(rendered, is(expected)); + } }