springboot 使用freemarker自定义标签
1、pom依赖引入
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2、application配置
#服务启动端口
server.port=8080
## Freemarker 配置
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
3、实现TemplateDirectiveModel
package com.example.springbootfreemarker.tags.directive; import freemarker.core.Environment; import freemarker.template.*; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Component public class MyTagDirective implements TemplateDirectiveModel{ @Override public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { Integer tagId = -1; String tagName = ""; //自己的逻辑 todo Map<String, Object> result = new HashMap<String, Object>(2); if (map.containsKey("tagId")){ tagId = Integer.parseInt(map.get("tagId").toString()); } if (map.containsKey("tagName")){ tagName = (String)map.get("tagName").toString(); } result.put("tagId", tagId); result.put("tagName", tagName); DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
//此处的myTag就是返回给前端的数据 environment.setVariable("myTag", builder.build().wrap(result)); templateDirectiveBody.render(environment.getOut()); } }
前端文件:
<!DOCTYPE html> <html lang="en"> <body> hello, ${name}, let's go! <@myTag tagId = 1 tagName = "mytag"> <#if myTag??> <p>${myTag.tagId},${myTag.tagName}</p> </#if> </@myTag> </body> </html>
用法:跟自定义macro用法一样,直接使用 <@xx></@xx> 来使用即可,值就直接在myTag 标签里传就可以了
流程:当访问前端页面时,会将自定义的标签及其值传到后台MyTagDirective拦截处理并返回结果给前端渲染使用,<#if myTag??>为freemarker语法,可参照freemarker语法