sprin boot使用freemarker模板,并将模板内容以字符串形式返回

博客介绍了模板引擎的使用步骤,包括引入依赖、创建模板文件,说明了模板文件中变量类型取值及相关符号的使用,如${time?date}只取date部分,“?date”还有其他可选值。还提及使用模板引擎,给出循环遍历List的模板示例,强调空值处理加感叹号的注意点。

1、引入依赖

<!-- 引入freeMarker的依赖包. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

2、创建模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发送邮件测试</title>
</head>
<body>
<p>内容:${content}</p>
<p>日期:${time?date}</p>
</body>
</html>

注意,这里的${time?date}表示time是日期类型的变量,只取date部分。“?date”还可以使用“?datetime”或“?time”。

3、使用模板引擎

	@Autowired
    FreeMarkerConfigurer configurer;//模板引擎

    @Test
    public String index(Map map) throws IOException, TemplateException {
        map.put("content","哈哈哈");
        map.put("time",new Date());
        Template template = configurer.getConfiguration().getTemplate("mail.ftl");
        String resp = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
        return resp;
    }

附:使用循环遍历一个List的模板:(转)

<html>  
<body>  
    <h3>发现错误!<a href="${errorLogLink}" target="_blank">点击这里查看详情</a></h3>  
      
    <h3>错误列表:</h3>  
      
    <table border="1px solid #8968CD" style="border-collapse: collapse;"><tr><th>错误位置</th> <th>数量</th> <th>错误信息</th> <th>错误类名</th> <th>更多信息</th> </tr>  
    <#list errorList as error>  
        <tr>  
            <td>${error.pos}</td>  
            <td>${error.count}</td>  
            <td>${error.msg}</td>  
            <td>${error.eName!}</td>  
            <td>${error.details!}</td>  
        </tr>  
    </#list>  
    </table>  
      
</body>  
</html> 

注意:最后那个两个感叹号表示:如果error.eName/error.details的值为空,则用空格代替。感叹号后面也可以加一个缺省字符串,在空值的时候代替空值。如果不加感叹号会报错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值