我正在使用Velocity在我的项目中生成不同的工件,包括Java Hibernate Entities。
以下是我的模板示例:
#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
问题是生成的代码如下所示:
@Column
private String vendor;
@NotNull
@Column(unique=true)
private String name;
@Column
private Integer min_quantity;
@Column
private String description;
@Column
private Boolean active;
我尝试了在每行之后添加##的建议解决方案,但它没有帮助。有没有办法强制Velocity保持模板中定义的空格?
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);
答案 0 :(得分:2)
行末##
是不够的,你还需要删除Velocity缩进。
保留缩进的另一种方法是使用Velocity注释缩进:
#foreach( $column in $columns )##
#**##if ($column.columnID != "id")##
#* *##if ($column.isColumnAnIdentifier)##
@Id
#* *##end
#* *##if ($column.isColumnValueGenerated)##
...
但我承认这很难看。
即将推出的Velocity 2.0版本增加了space gobbling option,默认情况下处于活动状态,完全符合您的要求。最新的候选版本可用here。
答案 1 :(得分:0)
我存储我的文件没有任何缩进,在我编辑和添加后添加它。你需要在Linux或Cygwin上运行它:
安全识别领先的速度指令:
Android
删除缩进:
gawk '
function ltrim(s) { sub(/^[ \t\r\n]+/, "", s); return s }
BEGIN {p=""}
/^ *#(end|else)\>/ {p = substr(p,5)}
/^ *#(if|end|set|foreach|else|#)\>/ {
printf "%s%s\n", p, ltrim($0);
if($0 ~ /^ *#(if|foreach|else)\>/) p = p " "; next;}
1'
如果您将这些故事描述为脚本(并使用vi / vim),则可以使用:
sed 's/^ #/#/'
...否则只需通过脚本管道文件。