Freemarker:方便地生成 UUID [英] Freemarker: generate UUID conveniently
问题描述
Freemarker 中似乎没有方便的内置功能来在模板中生成随机 UUID.
我能想到的最好方法是创建一个 Freemarker 方法;在我的 Java 8 代码中,我注入了该方法以供以后在模板中使用.示例:
public String generate(Map data, String templateLocation) throws IOException, TemplateException {尝试 (StringWriter writer = new StringWriter()) {模板模板 = configuration.getTemplate(templateLocation);//在这一行注入的 UUID 生成方法:data.put("uuid", (TemplateMethodModelEx) (list) -> UUID.randomUUID());模板.过程(数据,作家);返回 writer.toString();}}
在 Freemarker 模板中,我可以使用如下方法:
${uuid()}
在 Freemarker 中生成 uuid 是否有更方便的解决方案?
这是我的 Maven 依赖项:
<依赖><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.25-incubating</version><范围>测试</范围></依赖>
您可以使用 statics 在模板中调用 randomUUID
:
${statics["java.util.UUID"].randomUUID()}
<块引用>
如果该对象用作以类名作为键的散列,则该对象几乎公开任何类的静态方法.
There seems to be no convenient built-in in Freemarker to generate a random UUID in a template.
The best I could come up with was by creating a Freemarker method; in my Java 8 code I inject the method for later usage in the template. Example:
public String generate(Map<String, Object> data, String templateLocation) throws IOException, TemplateException {
try (StringWriter writer = new StringWriter()) {
Template template = configuration.getTemplate(templateLocation);
// UUID generation method injected in this line:
data.put("uuid", (TemplateMethodModelEx) (list) -> UUID.randomUUID());
template.process(data, writer);
return writer.toString();
}
}
In the Freemarker template I can then use the method like this:
${uuid()}
Is there a more convenient solution to generate uuids in Freemarker?
Here is the my Maven dependency:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.25-incubating</version>
<scope>test</scope>
</dependency>
You can use statics to call randomUUID
in your template:
${statics["java.util.UUID"].randomUUID()}
This object exposes just about any class' static methods if it's used as a hash with class name as the key.
这篇关于Freemarker:方便地生成 UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!