Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep template whitespace (tabs) formatting using Apache Velocity 1.7?

I am using Velocity to generate different artifacts in my project, including Java Hibernate Entities.

Here is an example of my template:

#foreach( $column in $columns )
    #if ($column.columnID != "id")
        #if ($column.isColumnAnIdentifier)
@Id
        #end
        #if ($column.isColumnValueGenerated)
@GeneratedValue
        #end
        #if ($column.isColumnValueNotNull)
@NotNull
        #end
        #if ($column.columnAllowedValues)
@Enumerated(EnumType.STRING)        
        #end
        #if ($column.isColumnValueUnique)
@Column(unique=true)
        #elseif ($column.isColumnJoinedManyToOne)
@ManyToOne
@JoinColumn(name = "$column.columnJoinByID")
        #else
@Column
        #end
private #if ($column.columnAllowedValues) $column.columnID.toUpperCase() #else $column.columnType #end $column.columnID;
    #end
#end

The problem is that the generated code looks like this:

@Column
            private  String  vendor;

                                                        @NotNull
                                    @Column(unique=true)
            private  String  name;


@Column
            private  Integer  min_quantity;


@Column
            private  String  description;


@Column
            private  Boolean  active;

I tried the suggested solution with adding ## after each line, it does not help. Is there a way to force Velocity to keep whitespace as defined in the template?

    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RESOURCE_LOADER_PROPERTY, RESOURCE_LOADER_VALUE);
    velocityEngine.setProperty(CLASSPATH_RESOURCE_LOADER_PROPERTY, ClasspathResourceLoader.class.getName());
    velocityEngine.init();
    Template velocityTemplate = velocityEngine.getTemplate(TEMPLATE_RESOURCES_ROOT_FOLDER + "/" + templateFileName);;
    StringWriter writer = new StringWriter();
    velocityTemplate.merge(velocityContext, writer);
    writeToFile(writer, destinationFilePath);
like image 213
Daniel Avatar asked Oct 26 '25 14:10

Daniel


1 Answers

The ## at the end of lines is not enough, you also need to remove the Velocity indentation.

An alternative, to keep the indentation, is to indent with Velocity comments:

#foreach( $column in $columns )##
#**##if ($column.columnID != "id")##
#*    *##if ($column.isColumnAnIdentifier)##
@Id
#*    *##end
#*    *##if ($column.isColumnValueGenerated)##
...

but I concede it is rather ugly.

The upcoming Velocity 2.0 release adds a space gobbling option, active by default, with does exactly what you want. The latest release candidate is available here.

like image 119
Claude Brisson Avatar answered Oct 29 '25 02:10

Claude Brisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!