使用Freemarker模板引擎渲染web視圖

在Web前端的學(xué)習(xí)中我們會(huì)應(yīng)用多種的模板引擎來(lái)快速的完成動(dòng)態(tài)網(wǎng)站的開(kāi)發(fā),下面就給大家詳細(xì)的講解一下使用Freemarker模板引擎渲染web視圖的應(yīng)用方法。

1.3.1、pom文件引入:

<!-- 引入freeMarker的依賴包. -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-freemarker</artifactId>

</dependency>

1.3.2、后臺(tái)代碼

在src/main/resources/創(chuàng)建一個(gè)templates文件夾,后綴為*.ftl

??????????? @RequestMapping("/index")

???????? public String index(Map<String, Object> map) {

???????? ??? map.put("name","美麗的天使...");

???????? ?? return "index";

???????? }

 

1.3.3、前臺(tái)代碼

 

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="UTF-8" />

<title></title>

</head>

<body>

??????????? ? ${name}

</body>

</html>

1.3.4、Freemarker其他用法

@RequestMapping("/freemarkerIndex")

??????????? public String index(Map<String, Object> result) {

?????????????????????? result.put("name", "zhaocong");

?????????????????????? result.put("sex", "0");

?????????????????????? List<String> userlist = new ArrayList<String>();

?????????????????????? userlist .add("zhangsan");

?????????????????????? userlist .add("lisi");

?????????????????????? userlist .add("atguigu");

?????????????????????? result.put("userlist ", userlist );

?????????????????????? return "index";

??????????? }

 

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="UTF-8" />

<title>首頁(yè)</title>

</head>

<body>

?????? ? ${name}

<#if sex=="1">

???????????

????? <#elseif sex=="2">

???????????

???? <#else>

??????? 帥氣的boy?

???????? ? </#if>????? ?

???????? ?<#list userlist as user>

???????? ?? ${user}

???????? ?</#list>

</body>

</html>

 

1.3.5、Freemarker配置

新建application.properties文件

########################################################

###FREEMARKER (FreeMarkerAutoConfiguration)

########################################################

spring.freemarker.allow-request-override=false

spring.freemarker.cache=true

spring.freemarker.check-template-location=true

spring.freemarker.charset=UTF-8

spring.freemarker.content-type=text/html

spring.freemarker.expose-request-attributes=false

spring.freemarker.expose-session-attributes=false

spring.freemarker.expose-spring-macro-helpers=false

#spring.freemarker.prefix=

#spring.freemarker.request-context-attribute=

#spring.freemarker.settings.*=

spring.freemarker.suffix=.ftl

spring.freemarker.template-loader-path=classpath:/templates/

#comma-separated list

#spring.freemarker.view-names= # whitelist of view names that can be resolved