gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:35:04 25 4
gpt4 key购买 nike

我正在使用 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 缩进。

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

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

但我承认它相当丑陋。

即将发布的 Velocity 2.0 版本添加了 space gobbling option ,默认情况下处于 Activity 状态, with 正是您想要的。最新候选版本已发布 here .

关于java - 如何使用 Apache Velocity 1.7 保持模板空白(制表符)格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com