From efc07af41a4f3bd8fbf65d51393c7b274eef8f52 Mon Sep 17 00:00:00 2001 From: Achim Abeling Date: Fri, 25 Feb 2022 15:22:04 +0100 Subject: [PATCH] IncludeTag now respects ignore missing --- .../hubspot/jinjava/lib/tag/IncludeTag.java | 20 +++++++++++++++++++ .../jinjava/lib/tag/IncludeTagTest.java | 12 +++++++++++ .../tags/includetag/missing-include.jinja | 1 + 3 files changed, 33 insertions(+) create mode 100644 src/test/resources/tags/includetag/missing-include.jinja 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..e84454d01 100644 --- a/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java +++ b/src/main/java/com/hubspot/jinjava/lib/tag/IncludeTag.java @@ -73,6 +73,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 +111,9 @@ 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 +126,20 @@ public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) { } } + /** + * Returns true if the next two tokens are "ignore" and "missing" + * @param helper + */ + private boolean checkIgnoreMissing(HelperStringTokenizer helper) { + + if (helper.hasNext() && "ignore".equals(helper.next())) { + if (helper.hasNext() && "missing".equals(helper.next())) { + 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..baf51131a 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"); + } } 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..a5075ac8e --- /dev/null +++ b/src/test/resources/tags/includetag/missing-include.jinja @@ -0,0 +1 @@ +A{% include "foobar" ignore missing %}B \ No newline at end of file