Skip to content
Open
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
25 changes: 25 additions & 0 deletions src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.hubspot.jinjava.tree.TagNode;
import com.hubspot.jinjava.util.HelperStringTokenizer;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

@JinjavaDoc(
Expand Down Expand Up @@ -73,6 +74,9 @@ public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {
);
templateFile = interpreter.resolveResourceLocation(templateFile);

/* check next tokens if it could be ignored if missing */
boolean ignoreMissing = checkIgnoreMissing(helper);

try {
interpreter
.getContext()
Expand Down Expand Up @@ -108,6 +112,10 @@ public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {

return interpreter.render(node, false);
} catch (IOException e) {
if (ignoreMissing) {
return "";
}

throw new InterpretException(
e.getMessage(),
e,
Expand All @@ -120,6 +128,23 @@ public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {
}
}

/**
* Returns true if the last two tokens match "ignore" "missing".
*
* @param helper
*/
private boolean checkIgnoreMissing(HelperStringTokenizer helper) {
List<String> all = helper.allTokens();
if (
all.size() >= 2 &&
"ignore".equals(all.get(all.size() - 2)) &&
"missing".equals(all.get(all.size() - 1))
) {
return true;
}
return false;
}

@Override
public String getEndTagName() {
return null;
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/com/hubspot/jinjava/lib/tag/IncludeTagTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,16 @@ public void itAvoidsTagCycleExceptionInsideExtendedFiles() throws Exception {
);
assertThat(result).isEqualTo("Extended text, will be rendered");
}

@Test
public void itIgnoresMissing() throws IOException {
String result = jinjava.render(
Resources.toString(
Resources.getResource("tags/includetag/missing-include.jinja"),
StandardCharsets.UTF_8
),
new HashMap<String, Object>()
);
assertThat(result).containsSequence("AB\nCD");
}
}
2 changes: 2 additions & 0 deletions src/test/resources/tags/includetag/missing-include.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
A{% include "foobar" ignore missing %}B
C{% include "foo/" + something + "/bar.j2" ignore missing %}D