Skip to content

Commit

Permalink
Merge pull request #710 from HubSpot/for-in-whitespace
Browse files Browse the repository at this point in the history
Use regex to match whitespace for locating the "in" in a for loop
  • Loading branch information
jasmith-hs authored Jul 14, 2021
2 parents ada1b59 + 3f771ee commit 1d08530
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/main/java/com/hubspot/jinjava/lib/tag/ForTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.tuple.Pair;

/**
Expand Down Expand Up @@ -93,6 +95,7 @@ public class ForTag implements Tag {

private static final long serialVersionUID = 6175143875754966497L;
private static final String LOOP = "loop";
private static final Pattern IN_PATTERN = Pattern.compile("\\sin\\s");

@Override
public boolean isRenderedInValidationMode() {
Expand Down Expand Up @@ -246,9 +249,9 @@ public Pair<List<String>, String> getLoopVarsAndExpression(TagToken tagToken) {
}

private Optional<String> getLoopExpression(String helpers) {
int inIndex = helpers.indexOf(" in ");
if (inIndex > 0) {
return Optional.of(helpers.substring(inIndex + 4).trim());
Matcher matcher = IN_PATTERN.matcher(helpers);
if (matcher.find()) {
return Optional.of(helpers.substring(matcher.end()).trim());
}
return Optional.empty();
}
Expand Down
8 changes: 8 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 @@ -308,6 +308,14 @@ public void itShouldHandleSpacesInMaps() {
assertThat(rendered).isEqualTo("foo?\nbar?\n");
}

@Test
public void itHandlesUnconventionalSpacing() {
String template = "{% for item\nin \t[0,1] %}" + "{{ item }}\n" + "{% endfor %}";

String rendered = jinjava.render(template, context);
assertThat(rendered).isEqualTo("0\n1\n");
}

private Node fixture(String name) {
try {
return new TreeParser(
Expand Down

0 comments on commit 1d08530

Please sign in to comment.