1.pom文件引入依赖
<!--rapid-framework 模板继承框架-->
<dependency>
<groupId>com.googlecode.rapid-framework</groupId>
<artifactId>rapid-core</artifactId>
<version>4.0.5</version>
</dependency>
<!-- lang包 缺少的话可能会报错 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
2.yml文件配置
spring:
freemarker:
charset: UTF-8
check-template-location: true
template-loader-path: classpath:/templates
suffix: .html
request-context-attribute: request
3.config配置
import cn.org.rapid_framework.freemarker.directive.BlockDirective;
import cn.org.rapid_framework.freemarker.directive.ExtendsDirective;
import cn.org.rapid_framework.freemarker.directive.OverrideDirective;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
/**
* <p>
* Freemarker配置
* </p>
*
* @author lzx
* @since 2020/06/10
*/
@Configuration
public class FreemarkerConfig {
@Autowired
freemarker.template.Configuration configuration;
@PostConstruct
public void setSharedVariable(){
configuration.setSharedVariable("block", new BlockDirective());
configuration.setSharedVariable("override", new OverrideDirective());
configuration.setSharedVariable("extends", new ExtendsDirective());
}
}
4.用法
- Freemarker 通过 rapid java实现继承。实际是rapid的jar包提供的三个自定义标签。实现继承用到的有三个标签:@extends,@block ,@override. 他们三个都有一个共同的属性: name
@extend标签: 要继承的模板
@block 标签: 声明在一个模板中定义那些代码是可以被重写的(@ovrride)
@override标签: 选择要重写的代码块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
<@block name="title">父模板的 title</@block>
</title>
<@block name="css"></@block>
</head>
<body>
<div>
<@block name="main">主内容</@block>
</div>
</body>
<@block name="dialog"></@block>
<@block name="js"></@block>
<@block name="script"></@block>
</html>
<@override name="title">
子模版的 title
</@override>
<@override name="css">
<!-- 子模版的 css -->
<style>
.title{
color: #000;
}
</style>
</@override>
<@override name="script">
<!-- 子模版的 script -->
<script>
location.reload();
</script>
</@override>
<@override name="main">
<div>子模版的 body</div>
</@override>
<!--继承的模板要写在最下面-->
<@extends name="layout.html"/>