User input at file template creation


I'm trying to create a clever DTO template, i.e. mainly a class that holds a number av values accessible through getters.

I know I can write $-variables in the template which will be represented by fields in my template creation popup so that I can name all my values in one place.
Like this:

I can also make so that if a value isn't entered in a "var.."-box, the value won't show up int the class.

But is there a way that would enable me to choose nr of values to enter in the template creation popup, so that I'm not limited to a fixed nr of values in my template?

Comment actions Permalink

Not directly. But since the file template uses the velocity template language ( you can use some logic to accomplish your goal. Instead of having a separate text field for the number of values desired, you would enter them as a list (delimited as desired).  The following example will take a list of space delimited names and values to create constants.

#set($contantNamesList = $Constant_Names_-_space_delimited_list.split(" "))
#set($contantValuesList = $Constant_Values_-_space_delimited_list.split(" "))

package ${PACKAGE_NAME};
public class ${NAME}
#foreach( ${zz_template_variable_placeholder} in $contantNamesList)
    public static final String $contantNamesList.get($i) = "$contantValuesList.get($i)";
    #set($i = $i + 1)

The unfortunate shortcoming is that the IDEA dialog will show the the loop variable. While variables set via the #set directive are not shown, $item in #foreach( $item in $myList) does show in the dialog. So the hackish workaround is to name loop variables in a way that they show at the end of the list (such as starting with a 'z') and perhaps use a name that indicates that it does not need to be set. Thus the use of "zz_template_variable_placeholder" in the above example. You can vote for which asks for this shortcoming to be fixed.

The above example shows a dialog as such:
which creates the code:

public class Example
    public static final String ONE = "A";
    public static final String TWO = "B";
    public static final String THREE = "C";

Comment actions Permalink

Thanks a lot! I'm really amazed by the quick and extensive repsonses in this community.

I've voted and will stick to my version until it is fixed.


Please sign in to leave a comment.