step 1. 增加freemarker依赖
修改 pom.xml
在 <dependencies>标签内部追加以下配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
...
<dependencies>
...
<dependency>
<groupId>fr.ippon.spark.metrics</groupId>
<artifactId>metrics-spark-reporter</artifactId>
<version>${metrics-spark-reporter.version}</version>
</dependency>
<!-- jhipster-needle-maven-add-dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
...
</project>
step 2. 修改application.yml配置
加完依赖的jar之后,我们还希望在freemarker模版中使用一些内置变量,则需要修改 src\main\resources\config\application.yml
# ===================================================================
# Spring Boot configuration.
#
# This configuration will be overriden by the Spring profile you use,
# for example application-dev.yml if you use the "dev" profile.
# ===================================================================
# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================
management:
context-path: /management
health:
mail:
enabled: false # When using the MailService, configure an SMTP server and set this to true
spring:
application:
name: cms
.......
thymeleaf:
mode: XHTML
freemarker:
exposeSpringMacroHelpers: true
exposeRequestAttributes: true
exposeSessionAttributes: true
requestContextAttribute: request
contentType: text/html
.....
step 3. 添加自定义模版宏
创建一个新的java类
package cn.ctodb.cms.config;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import cn.ctodb.cms.freemarker.macro.CmsMyDirective;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.ObjectWrapper;
import freemarker.template.Version;
@org.springframework.context.annotation.Configuration
public class FreemarkerConfiguration {
@Autowired
protected Configuration configuration;
@Autowired
protected CmsMyDirective cms_my;
@PostConstruct
public void setSharedVariable() {
configuration.setSharedVariable("cms_my", cms_my);
}
}
网友评论