Skip to content

Commit

Permalink
Merge pull request #135 from bkiers/bug/125-map-in-for-loop
Browse files Browse the repository at this point in the history
Support iterating over maps/dictionaries
  • Loading branch information
bkiers authored Mar 29, 2019
2 parents 423c8f4 + 144ecd4 commit 2c7a355
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/main/java/liqp/LValue.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package liqp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -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) {
Expand All @@ -117,6 +119,17 @@ public Object[] asArray(Object value) {
return ((List) value).toArray();
}

if (value instanceof Map) {

List<Object[]> keyValuePairs = new ArrayList<>();

for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) {
keyValuePairs.add(new Object[]{ entry.getKey(), entry.getValue()});
}

return keyValuePairs.toArray();
}

return new Object[]{value};
}

Expand Down
20 changes: 20 additions & 0 deletions src/test/java/liqp/tags/ForTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
}
}

0 comments on commit 2c7a355

Please sign in to comment.