[Spring Boot] Thymeleaf Template Engine - Advanced Usage of Thymeleaf

Advanced usage of Thymeleaf

It mainly introduces the advanced usage of Thymeleaf's inline, built-in objects, and built-in variables.

1. Inline

Although the tag attributes in Thymeleaf have met almost all the needs in development, in some cases it is necessary to access the data returned by the background in CSS or JS. So Thymeleaf provides the th:inline="text/javascript/none" tag, using [[…]] inline expressions to easily access model object data in HTML, JavaScript, and CSS code blocks.

1.1 Text inlining

Thymeleaf inline expressions are expressed using the [[…]] or [(…)] syntax. First use the inline method th:inline="text" in the parent tag definition, and then use [[…]] or [(…)] expressions in the tag to operate the data object. Text inline is more concise than th:text code. The following example demonstrates how to use inline.

First, create the page inline.html. The sample code is as follows:

<h1>Thymeleaf模板引擎</h1>
<div>
    <h1>内联</h1>
    <div th:inline="text">
        <p>Hello[[${
    
    userName}]] !</p>
        <br/>
    </div>
</div>

The above code is equivalent to:

    <div th:inline="text">
        <h1>不使用内联</h1>
        <p th:text=" 'Hello’, + ${userName} + '!'"></p>
        <br/>
    </div>

From the above two examples, it can be seen that using inline syntax will be more concise.

1) th:inline="text" means to use text inline.

2) Any parent tag can add th:inline.

3) [[…]] is equivalent to th:text results will be HTML escaped, [(…)] is equivalent to th:utext results will not be HTML escaped.

Then, create a background route /inline, the sample code is as follows:

    @RequestMapping("/inline")
    public String inline(ModelMap map) {
    
    
        map.addAttribute("userName", "admin");
        return "inline";
    }

In the above example, the background returns the inline.html page, and returns userName=admin at the same time.

Finally, run the tests. After starting the project, enter the address http://localhost:8080/inline in the browser, and the result as shown in the figure will appear.

insert image description here

The page shows that the userName returned by the background is admin, which is simpler and clearer than the th:text=${userName} method introduced earlier.

1.2 Script inlining

Script inlining, as the name implies, uses inline expressions in JavaScript scripts. When using it, you only need to <script>add the th:inline="javascript" attribute to the tag, and then you can use the [[]] expression in the JavaScript code block. Realize obtaining the parameters passed from the background in the JavaScript script.

First, modify the inline.html page and add the following script:

<script th:inline="javascript">
    var name = 'hello, ' + [[${
    
    userName}]];
    alert(name);
</script>

In the above example, <script>adding th:inline="javascript" to the tag indicates that the [ [ ] ] value can be used in JavaScript. When accessing the page, the name value is spliced ​​according to the value passed in the backend, and displayed in an alert box.

Then start the project, enter the address http://localhost:8080/inline in the browser, and the result as shown in the figure will appear.

insert image description here

When the page is displayed, an alert prompt box will pop up first, displaying "hello admin", indicating that the data transmitted from the background is bound using the script inline.

1.3 Style inlining

Thymeleaf also allows <style>dynamic generation of CSS property styles using inline expressions in tags. The following example demonstrates the usage of inline CSS styles.

First, modify the inline.html page and add the following styles:

<style type="text/css" th:inline="css" th:with="color='yellow', fontSize='25px'">
    p {
    
    
        color: /*[[${color}]]*/ red;
        font-size: [(${
    
    fontSize})];
    }
</style>

In the example above, like inline JavaScript, CSS inlining also allows

Then, modify the /inline route to return fontSize and color. The sample code is as follows:

    @RequestMapping("/inline")
    public String inline(ModelMap map) {
    
    
        map.addAttribute("fontSize", "20px");
        map.addAttribute("color", "yellow");
        map.addAttribute("userName", "admin");
        return "inline";
    }

In the above example, two CSS attribute styles, fontSize and color, are added, and the fontSize is set to 20px, and the color is yellow.

Then start the project, enter the address http://localhost:8080/inline in the browser, the font size and color displayed on the page are displayed according to the data returned by the background, indicating that CSS inline takes effect.

1.4 Disable inlining

Thymeleaf supports the use of th:inline="none" to disable inlining. The sample code is as follows:

<!--/*禁用内联表达式*/-->
<p th:inline="none">[[${
    
    info}]]</p>
<!--/*禁用内联表达式*/-->
<p th:inline="none">[[Info]]</p>

2. Built-in objects

Thymeleaf includes some built-in basic objects that can be used in views to obtain information such as context objects, request parameters, and sessions. These basic objects start with #, as shown in the table.

insert image description here
As shown in the table, Thymeleaf provides a series of objects and properties for accessing application properties such as request parameters and session properties. The following two commonly used objects are used as examples to demonstrate.

Step 01 defines the background method to pass values.

Create a background method that returns request parameters and session attributes in the background. The sample code is as follows:

    @RequestMapping("/object")
    public String test1(HttpServletRequest request) {
    
    
        request.setAttribute("request", "spring boot");
        request.getSession().setAttribute("session", "admin session");
        request.getServletContext().setAttribute("servletContext", "Thymeleaf servletContext");
        return "baseobject";
    }

In the above example, we wrote related tests in the request and session objects respectively, to verify whether the foreground can obtain these custom web request information.

Step 02 The front-end page receives parameters.

Next, let's see how the front-end page obtains the value passed by the back-end through the built-in basic object of Thymeleaf. Create a new front-end page baseobject.html under the /resources directory. The sample code is as follows:

<h1>Thymeleaf模板引擎</h1>
<h3>基本对象</h3>
<p th:text="${#request.getAttribute('request')}"></p>
<p th:text="${#session.getAttribute('session')}"></p>
<p th:text="${#servletContext.getAttribute('servletContext')}"></p>

In the above example, we can obtain the relevant information in the web request through objects such as #request and #session in the HTML page.

Step 03 starts verification.

After starting the project, enter the address http://localhost:8080/object in the browser, and the result as shown in the figure will appear.

insert image description here

In the HTML page, the web request information returned by the background is successfully obtained through objects such as #request and #session.

3. Embedded variables

To make templates easier to use, Thymeleaf also provides a series of public Utility objects (built into Context), which can be directly accessed through #. The specific objects are shown in the table.

insert image description here
insert image description here
insert image description here

In addition to defining the commonly used objects above, Thymeleaf also has some other utility objects, such as #ids, which will not be listed here.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132138828