0

I need to generate the following kinds of code with StringTemplate4:

methodFoo0(Connection conn);
methodFoo1(Connection conn, int arg1);
methodFoo2(Connection conn, int arg1, int arg2); 

etc.

The "Connection conn" part is always present so I am only passing the method name and the rest of the arguments to my ST template. My template looks as follows:

<methodName>(Connection conn, <args; separator=", ">);

This works but produces an extra comma when there are no arguments at all (except conn):

methodFoo0(Connection conn,);

To eliminate the extra comma I tried using the if conditional and the length ST4 function but I couldn't get it to work although I tried various combos like the following:

<methodName>(Connection conn <if (length(fieldsInFind) \> 0)>,<else><endif><fieldsInFind; separator=", ">)

... and others which they all failed with some parsing-related error (mismatched input).

In the end, I gave up and resorted to passing a comma parameter to the template which is either "," or the empty string "" based on pre-rendering logic.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

2 Answers2

0

You could check the presence of the second parameter using <if (fieldsInFind)> and only pass this to the template if its size is greater than 0.

The Cat
  • 2,375
  • 6
  • 25
  • 37
0

The extra comma is not produced by the separator but it is the one you already typed after Connection conn,.

You do the following:

<methodName>(Connection conn<if(args)>,<args; separator=", "><endif>)

Notice the comma after the conn is only placed if there are in fact more arguments.

sebagomez
  • 9,501
  • 7
  • 51
  • 89