diff --git a/src/main/java/com/hubspot/jinjava/tree/TreeParser.java b/src/main/java/com/hubspot/jinjava/tree/TreeParser.java index ebcd5a0d7..409b3db1f 100644 --- a/src/main/java/com/hubspot/jinjava/tree/TreeParser.java +++ b/src/main/java/com/hubspot/jinjava/tree/TreeParser.java @@ -68,7 +68,9 @@ public Node buildTree() { !interpreter.getConfig().getLegacyOverrides().isAllowAdjacentTextNodes() ) { // merge adjacent text nodes so whitespace control properly applies - getLastSibling().getMaster().mergeImageAndContent(node.getMaster()); + ((TextToken) getLastSibling().getMaster()).mergeImageAndContent( + (TextToken) node.getMaster() + ); } else { parent.getChildren().add(node); } diff --git a/src/main/java/com/hubspot/jinjava/tree/parse/TextToken.java b/src/main/java/com/hubspot/jinjava/tree/parse/TextToken.java index dc3d64b42..edfbb4d3e 100644 --- a/src/main/java/com/hubspot/jinjava/tree/parse/TextToken.java +++ b/src/main/java/com/hubspot/jinjava/tree/parse/TextToken.java @@ -29,6 +29,13 @@ public TextToken( super(image, lineNumber, startPosition, symbols); } + public void mergeImageAndContent(TextToken otherToken) { + String thisOutput = output(); + String otherTokenOutput = otherToken.output(); + this.image = thisOutput + otherTokenOutput; + this.content = image; + } + @Override public int getType() { return getSymbols().getFixed(); diff --git a/src/main/java/com/hubspot/jinjava/tree/parse/Token.java b/src/main/java/com/hubspot/jinjava/tree/parse/Token.java index dda5bd63b..487987626 100644 --- a/src/main/java/com/hubspot/jinjava/tree/parse/Token.java +++ b/src/main/java/com/hubspot/jinjava/tree/parse/Token.java @@ -53,11 +53,6 @@ public String getImage() { return image; } - public void mergeImageAndContent(Token otherToken) { - this.image = image + otherToken.image; - this.content = content + otherToken.content; - } - public int getLineNumber() { return lineNumber; } diff --git a/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java b/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java index a30031d93..7a665abc8 100644 --- a/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java +++ b/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java @@ -232,6 +232,13 @@ public void itTrimsNotes() { assertThat(interpreter.render(tree)).isEqualTo("AB"); } + @Test + public void itMergesTextNodesWhileRespectingTrim() { + String expression = "{% print 'A' -%}\n{#- note -#}\nB\n{%- print 'C' %}"; + final Node tree = new TreeParser(interpreter, expression).buildTree(); + assertThat(interpreter.render(tree)).isEqualTo("ABC"); + } + @Test public void itTrimsExpressions() { String expression = "A\n{{- 'B' -}}\nC";