模板引擎
模板引擎
,我们其实大家听到很多,其实jsp
就是一个模板引擎
,还有用的比较多的freemarker
,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,什么样一个思想呢我们来看一下这张图:
模板引擎
的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
引入Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf分析
我们已经引入了
Thymeleaf
,那这个要怎么处理呢?
我们首先得按照SpringBoot
的自动配置原理看一下我们这个Thymeleaf
的自动配置规则,在按照那个规则,我们进行使用
我们再去找一下
Thymeleaf
的自动配置类:hymeleafProperties
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
//默认编码
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
//默认前缀
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//默认后缀
public static final String DEFAULT_SUFFIX = ".html";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
/**
* Prefix that gets prepended to view names when building a URL.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Suffix that gets appended to view names when building a URL.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
*/
private String mode = "HTML";
/**
* Template files encoding.
*/
private Charset encoding = DEFAULT_ENCODING;
/**
* Whether to enable template caching.
*/
private boolean cache = true;
/**
* Order of the template resolver in the chain. By default, the template resolver is
* first in the chain. Order start at 1 and should only be set if you have defined
* additional "TemplateResolver" beans.
*/
private Integer templateResolverOrder;
/**
* Comma-separated list of view names (patterns allowed) that can be resolved.
*/
private String[] viewNames;
/**
* Comma-separated list of view names (patterns allowed) that should be excluded from
* resolution.
*/
private String[] excludedViewNames;
/**
* Enable the SpringEL compiler in SpringEL expressions.
*/
private boolean enableSpringElCompiler;
/**
* Whether hidden form inputs acting as markers for checkboxes should be rendered
* before the checkbox element itself.
*/
private boolean renderHiddenMarkersBeforeCheckboxes = false;
/**
* Whether to enable Thymeleaf view resolution for Web frameworks.
*/
private boolean enabled = true;
我们可以在其中看到默认的
前缀
和后缀
我们只需要把我们的html
页面放在类路径下的templates
下,thymeleaf
就可以帮我们自动渲染了。
使用thymeleaf
什么都不要配置,只需要将它放在指定的路径下即可