如何使用 Apache Velocity 1.7 保持模板空格(制表符)格式



我正在使用Velocity在我的项目中生成不同的工件,包括Java Hibernate实体。

这是我的模板示例:

#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);

行尾的##是不够的,还需要删除速度缩进。

为了保持缩进,另一种方法是使用 Velocity 注释缩进:

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

但我承认它相当丑陋。

即将发布的 Velocity 2.0 版本增加了一个空间吞噬选项,默认情况下处于活动状态,可以完全按照您的要求进行操作。此处提供了最新版本候选版本。

我存储文件时没有任何缩进,在编辑时添加它,然后在之后删除它。 你需要在Linux或Cygwin上运行它:

安全识别前导速度指令:

gawk '
function ltrim(s) { sub(/^[ trn]+/, "", s); return s }
BEGIN {p=""}
/^ *#(end|else)>/ {p = substr(p,5)}
/^ *#(if|end|set|foreach|else|#)>/ {
    printf "%s%sn", p, ltrim($0);
    if($0 ~ /^ *#(if|foreach|else)>/) p = p "    "; next;}
1'

删除缩进:

sed 's/^  #/#/'

如果你将这些故事作为脚本(并使用vi/vim(,那么你可以使用:

:%!VelocityIndent

。否则,只需通过脚本管道传输文件即可。

最新更新