Skip to content

Commit 6d5e180

Browse files
authored
Merge pull request #1310 from HubSpot/mnobile_hubspot/fix-macro-ternary-npe
Fix NPE when calling macros inside ternary with variable condition
2 parents a6c5d0b + d57126e commit 6d5e180

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

src/main/java/com/hubspot/jinjava/el/ext/ExtendedParser.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ protected AstNode nonliteral() throws ScanException, ParseException {
281281
switch (getToken().getSymbol()) {
282282
case IDENTIFIER:
283283
String name = consumeToken().getImage();
284-
if (getToken().getSymbol() == COLON) {
284+
if (getToken().getSymbol() == COLON && getToken().getImage().equals(":")) {
285285
Symbol lookahead = lookahead(0).getSymbol();
286286
if (
287287
isPossibleExpTest(lookahead) &&

src/test/java/com/hubspot/jinjava/lib/tag/MacroTagTest.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,32 @@ public void itCorrectlyScopesNestedMacroTags() {
373373
}
374374
}
375375

376+
@Test
377+
public void itCallsMacroInTernaryWithVariableCondition() {
378+
String template =
379+
"{% macro greet(name) %}Hello {{ name }}{% endmacro %}" +
380+
"{{ greet('world') if myVar else greet('nobody') }}";
381+
382+
context.put("myVar", true);
383+
assertThat(jinjava.render(template, context).trim()).isEqualTo("Hello world");
384+
385+
context.put("myVar", false);
386+
assertThat(jinjava.render(template, context).trim()).isEqualTo("Hello nobody");
387+
}
388+
389+
@Test
390+
public void itCallsMacroInStandardTernaryWithVariableCondition() {
391+
String template =
392+
"{% macro greet(name) %}Hello {{ name }}{% endmacro %}" +
393+
"{{ myVar ? greet('world') : greet('nobody') }}";
394+
395+
context.put("myVar", true);
396+
assertThat(jinjava.render(template, context).trim()).isEqualTo("Hello world");
397+
398+
context.put("myVar", false);
399+
assertThat(jinjava.render(template, context).trim()).isEqualTo("Hello nobody");
400+
}
401+
376402
private Node snippet(String jinja) {
377403
return new TreeParser(interpreter, jinja).buildTree().getChildren().getFirst();
378404
}

0 commit comments

Comments
 (0)