使用freemarker渲染生成模板文件

  1. 1. Freemarker 杂记
    1. 1.1. 方法1
    2. 1.2. 方法2

Freemarker 杂记

需求: 使用freemarker渲染生成模板文件

freemarker常用与web项目前端页面渲染,同样也可以用于其他代码的模板化生成

方法1

使用自带的Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import freemarker.template.Configuration;

Configuration cfg = new
//指定Freemarker版本
Configuration(Configuration.VERSION_2_3_28);
//模板文件夹存放地址
File file = new File("");
cfg.setDirectoryForTemplateLoading(file);
//设置封装格式
vfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));

//获取文件
//文件路径加文件名
Template template = cfg.getTemplate("fileName","UTF-8");
//param 为输出参数
Writer out = new StringWriter();
template.process(params, out);
out.toString();

方法2

如果freemarker已经与spring集成可以直接通过配置文件指定多个模板文件地址(推荐)

  • springboot 配置

    1
    spring.freemarker.template-loader-path=classpath:/templates/page,classpath:/code_temp
  • springMvc 配置(未测试)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <bean id="freemarkerConfig"
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPaths" >
    <list>
    <value>"/WEB-INF/page"</value>
    <value>"/code_temp"</value>
    </list>
    </property>
    </bean>

代码逻辑与方法1类似

1
2
3
4
5
6
7
8
9
@Autowired
private freemarker.template.Configuration configuration;

//templateFile 文件路径及文件
Template template = configuration.getTemplate(templateFile, "UTF-8");
Writer out = new StringWriter();
//param 为输出参数
template.process(params, out);
out.toString();

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者