springboot的thymeleaf模板与freemarker模板的基础用法

springboot的thymeleaf模板与freemarker模板的基础用法
1、springboot之thymeleaf模板
优点:最明显的优点就是它是html页面。下面直接上代码
使用thymeleaf首先要给他导入相关pom依赖


            org.springframework.boot
            spring-boot-starter-thymeleaf
        

注意:Spring Boot官方文档建议在开发时将缓存关闭,那就在application.properties文件中加入下面这行
spring.thymeleaf.cache=false
正式环境还是要将缓存开启的

下面是我写的一个demo,主要是介绍它的基础用法





    
    用户列表


默认值

用户ID 用户名 用户描述

2、springboot之freemarker模板
①、导入相关的pom依赖


	org.springframework.boot
	spring-boot-starter-freemarker
   

②、application.yml文件的默认配置
spring:
thymeleaf:
cache: false
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径,默认是/templates,为演示效果添加role
template-loader-path: classpath:/templates/role
mvc:
static-path-pattern: /static/**
③、demo




    
    角色列表
    <#include 'comment.ftl'>


取值
welcome 【${name!'未知'}】to page

非空判断

<#if name??> xxxxx 条件表达式 <#if set=='boy'> 男 <#elseif sex=='girl'> 女 <#else> 保密

循环

<#list roles as role>
角色ID 角色名 角色描述
${role.rid} ${role.roleName} ${role.desc}
获取项目名(设置局部变量及全局变量) <#--jsp ${pageContext.request.contextPath}--> <#--将项目名赋值给ctrl这个变量,这边的作用域在当前页面--> <#assign ctx1> ${springMacroRequestContext.contextPath} <#--将项目名赋值给ctrl这个变量,这边的作用域在当整个项目--> <#global ctx2> ${springMacroRequestContext.contextPath} ${ctx1},${ctx2}

包含include

<#include 'foot.ftl'>

④、项目中怎么引用全局变量、局部变量
你项目中需要引入的文件等、、、
springboot的thymeleaf模板与freemarker模板的基础用法_第1张图片
然后在页面上直接引用即可
在这里插入图片描述
⑤、freemarker模板页面取值的时候会出现的坑
如果${name}的值为null,他就会报下面错, 为’'就不会报错,这种情况的解决办法就是在在${name}后面加上一个感叹号${name!}
!就是一个默认值,如果有值就显示你的没值就显示默认值
springboot的thymeleaf模板与freemarker模板的基础用法_第2张图片

⑥、注意:springboot项目,所有的页面都不能够直接跳页面,都会经过后台;它都会经过springmvc的视图解析器
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(springboot的thymeleaf模板与freemarker模板的基础用法)