Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/main/java/com/hubspot/jinjava/lib/tag/ForTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,17 @@ public String renderForCollection(
} else {
for (int loopVarIndex = 0; loopVarIndex < loopVars.size(); loopVarIndex++) {
String loopVar = loopVars.get(loopVarIndex);
if (val == null) {
if (
interpreter.getContext().get(loopVar) != null &&
interpreter.getConfig().getLegacyOverrides().isKeepNullableLoopValues()
) {
interpreter.getContext().put(loopVar, NullValue.INSTANCE);
} else {
interpreter.getContext().put(loopVar, null);
}
Comment on lines +219 to +226
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This and L#208-214 can be extracted to a single method.

continue;
}
if (Entry.class.isAssignableFrom(val.getClass())) {
Entry<String, Object> entry = (Entry<String, Object>) val;
Object entryVal = null;
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/com/hubspot/jinjava/lib/tag/ForTagTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,21 @@ public void forLoopWithNullValues() {
assertThat(result).isEqualTo(" 1 2 null null null ");
}

@Test
public void forLoopTupleWithNullValues() {
context.put("number", -1);
context.put("the_list", Lists.newArrayList(1L, 2L, null, null, null));
String template = "{% for number,name in the_list %} {{ number }} {% endfor %}";
TagNode tagNode = (TagNode) new TreeParser(interpreter, template)
.buildTree()
.getChildren()
.getFirst();
String result = tag.interpret(tagNode, interpreter);
// This is quite intuitive, if the value cannot be assigned to the loop var,
// the outer value of number is used as in the loop, number is not assigned if val is not null.
assertThat(result).isEqualTo(" -1 -1 null null null ");
}

public static boolean inForLoop() {
JinjavaInterpreter interpreter = JinjavaInterpreter.getCurrent();
return interpreter.getContext().isInForLoop();
Expand Down