Skip to content

Commit

Permalink
Exiting an else didn't reset the match / inElse attributes on lea…
Browse files Browse the repository at this point in the history
…ving scope of the `if`, meaning subsequent `true` conditions would never get met.
  • Loading branch information
brett-smith committed Mar 12, 2024
1 parent 8c1180a commit 2c6fcec
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 9 deletions.
28 changes: 19 additions & 9 deletions src/main/java/com/sshtools/tinytemplate/Templates.java
Original file line number Diff line number Diff line change
Expand Up @@ -905,17 +905,25 @@ else if (ch == 't') {
if(isNest) {
block.nestDepth--;
}
if(directive.equals(block.scope) && (!isNest || (isNest && block.nestDepth == 0))) {
logger.ifPresent(lg -> lg.debug("Leaving scope {0}", block.scope));
return;
} else {
if(directive.equals(block.scope) && isNest && process) {
buf.setLength(0);
try {
if(directive.equals(block.scope) && (!isNest || (isNest && block.nestDepth == 0))) {
logger.ifPresent(lg -> lg.debug("Leaving scope {0}", block.scope));
return;
} else {
if(directive.equals(block.scope) && isNest && process) {
buf.setLength(0);
}
else {
flushBuf(ch, buf, block);
}
block.state = State.START;
}
else {
flushBuf(ch, buf, block);
}
finally {
if(directive.equals("if") && block.inElse) {
block.inElse = false;
block.match = !block.match;
}
block.state = State.START;
}
}
else {
Expand Down Expand Up @@ -957,9 +965,11 @@ else if (ch == 't') {
}

private boolean processDirective(Block block, String directive) {

var spc = directive.indexOf(' ');
var dir = ( spc == -1 ? directive : directive.substring(0, spc)).trim();
var var = ( spc == -1 ? null : directive.substring(spc + 1).trim());

if(dir.equals("t:if")) {

var condition = Condition.parse(var);
Expand Down
39 changes: 39 additions & 0 deletions src/test/java/com/sshtools/tinytemplate/TemplatesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,45 @@ public void testTemplateNestedList() {
variable("var1", "Some Name")));
}

@Test
public void testTemplateIfAfterIfAndElseWithNestedIf() {
Assertions.assertEquals("""
<html>
<body>
<p>Show this</p>
<p>And this</p>
<p>Do show this</p>
</body>
</html>
""",
createParser().process(TemplateModel.ofContent("""
<html>
<body>
<t:if aCondition>
<p>Show this</p>
<t:if cCondition>
<p>And this</p>
</t:if>
<t:else/>
<p>Dont show this</p>
</t:if>
<t:if bCondition>
<p>Do show this</p>
</t:if>
</body>
</html>
""").
condition("cCondition", true).
condition("aCondition", true).
condition("bCondition", true)));
}

@Test
public void testTemplateWithConditionsInList() {
Assertions.assertEquals("""
Expand Down

0 comments on commit 2c6fcec

Please sign in to comment.