antlr / stringtemplate4

StringTemplate 4
http://www.stringtemplate.org
Other
955 stars 231 forks source link

comma in if statement template not possible #258

Closed frank-123456 closed 4 years ago

frank-123456 commented 4 years ago

Using the following code:

    ST sqlTemplate = new ST(
            "SELECT $attributes:{a|d.$a$}; separator=\", \"$$if(attributes), $max(f.$period$) as last_period",
            '$', '$'
    );
    sqlTemplate.add("period", "month");
    sqlTemplate.add("attributes", new ArrayList<String>());
    System.out.println(sqlTemplate.render());

I get the error message "1:60: mismatched input ',' expecting RDELIM". I did not find any way to escape the comma in the if-true expression ", ". Neither preceding it with backslash, nor by including it in quotes, curly braces, or any combination thereof helped. Could you somehow make the comma escapable in this case? Or did I miss an obvious way to escape it?

BTW: The requested output can - in this case - better be achieved by not using a separator, but including the comma in the attributes loop, i. e, the following template does not cause the error: "SELECT $attributes:{a|d.$a$, }$max(f.$periodId$) as last_period", Nevertheless, there may be valid cases where a comma is needed in an if expression result.

Clashsoft commented 4 years ago

I think you are using the if statement incorrectly -- there's no endif. You want to include , in the output if attributes is falsy? Then use this:

SELECT $attributes:{a|d.$a$}; separator=\", \"$$if(attributes)$, $endif$max(f.$period$) as last_period
frank-123456 commented 4 years ago

Right, that was the issue.