diff --git a/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java b/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java index d8b985c98..132ebb608 100644 --- a/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java +++ b/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java @@ -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( @@ -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() @@ -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, @@ -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 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; diff --git a/src/test/java/com/hubspot/jinjava/lib/tag/IncludeTagTest.java b/src/test/java/com/hubspot/jinjava/lib/tag/IncludeTagTest.java index c724a14a0..010cd351c 100644 --- a/src/test/java/com/hubspot/jinjava/lib/tag/IncludeTagTest.java +++ b/src/test/java/com/hubspot/jinjava/lib/tag/IncludeTagTest.java @@ -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() + ); + assertThat(result).containsSequence("AB\nCD"); + } } diff --git a/src/test/resources/tags/includetag/missing-include.jinja b/src/test/resources/tags/includetag/missing-include.jinja new file mode 100644 index 000000000..d73d6871d --- /dev/null +++ b/src/test/resources/tags/includetag/missing-include.jinja @@ -0,0 +1,2 @@ +A{% include "foobar" ignore missing %}B +C{% include "foo/" + something + "/bar.j2" ignore missing %}D \ No newline at end of file