e2b86e84bbab9f86572a21059872fda09ccdf281.svn-base
2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Copyright © 2015-2018 ODM All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* FreeMarkers工具类
* @author ThinkGem
* @version 2013-01-15
*/
public class FreeMarkers {
public static String renderString(String templateString, Map<String, ?> model) {
try {
StringWriter result = new StringWriter();
Template t = new Template("name", new StringReader(templateString), new Configuration());
t.process(model, result);
return result.toString();
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static String renderTemplate(Template template, Object model) {
try {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static Configuration buildConfiguration(String directory) throws IOException {
Configuration cfg = new Configuration();
Resource path = new DefaultResourceLoader().getResource(directory);
cfg.setDirectoryForTemplateLoading(path.getFile());
return cfg;
}
public static void main(String[] args) throws IOException {
// // renderString
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName}", model);
// System.out.println(result);
// // renderTemplate
// Configuration cfg = FreeMarkers.buildConfiguration("classpath:/");
// Template template = cfg.getTemplate("testTemplate.ftl");
// String result2 = FreeMarkers.renderTemplate(template, model);
// System.out.println(result2);
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName} ${r'${userName}'}", model);
// System.out.println(result);
}
}