This is the 25th day of my participation in the August Challenge

A template engine

What is a template engine

Created to separate the user interface from the business data (content), it can generate documents in a specific format. A template engine for a website, such as JSP, produces a standard HTML document.

It is often necessary to generate HTML and render the page based on the JSON data returned by the back end. A template engine is a page template that fills dynamic values with expressions

Import dependence

The source code

ThymeleafProperties.class

Equivalent to a view parser that prefixes and suffixes resources

@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";Copy the code

Resource location tempates

To jump to resources by controller, you need to put the resources in the Templates directory

And templates’ resources are only accessible to controllers

controller

View name: classpath:/templates/ filene.html

// All resources in the templates directory can be accessed only by controller Thymeleaf @controller public class IndexController {// set RequestMapping("/index") public String index(){ return "index"; } @RequestMapping("/test") public String test(Model model){ model.addAttribute("message","YY"); List<Object> lists = new ArrayList(); lists.add("YZY"); lists.add("YY"); / / template engine to view name joining together into the classpath: / templates/test. The HTML return "test"; }}Copy the code

To obtain parameters

<h1>test</h1> <! ${message} ${message}Copy the code

modified

<html lang="en" xmlns:th="http://www.thymeleaf.org"> <! - use thymeleaf syntax, similar to the vue th: properties - > < p th: text = "${message}" > < / p >Copy the code

grammar

<! - traverse a collection - > < h2 th: each = "list: ${lists}" th: text = "${list}" > < / h2 > <! -- can also write in the content - > < h2 th: each = "list: ${lists}" > [[${list}]] < / h2 >Copy the code

Obtaining static resources requires @{path}

Static th: SRC = "@{/img/ss.png}" th:href = "@{/ CSS /**}"Copy the code

Reuse code:

Reuse components in a common file marked with th: Fragment

<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"th:fragment="navBar">
Copy the code

Call the sideBar component in the common file of the common folder

th:insert = '@{common/common::sideBar}'
Copy the code

judge

<td th:text="${employee.getGender()==0? "></td>Copy the code