Home Java Thymeleaf Tutorial: Chapter 13.Text Template Modes

Thymeleaf Tutorial: Chapter 13.Text Template Modes

by admin

Table of Contents

13 Text Template Modes

13.1 Text Syntax

Three types of Thymeleaf patterns are considered textual : TEXT , JAVASCRIPT and CSS This distinguishes them from the markup template modes : HTML and XML
The key difference between the text template and markup modes is that there are no tags in the text template where we need to insert logic in the form of attributes, so we have to rely on other mechanisms.
The first and most basic of these mechanisms is inlining, which we already discussed in the previous chapter. Inlining syntax is the easiest way to display the results of expressions in text pattern mode.
Consider the letter :

Dear [(${name})], Please find attached the results of the report you requestedwith name "[(${report.name})]".Sincerely, The Reporter.

Even without the tags, the above example is a complete and valid Thymeleaf pattern that can be executed in TEXTmode.
But in order to include more complex logic than simple expressions, we need a new syntax that does not contain :

[# th:each="item : ${items}"]- [(${item})][/]

This is actually a condensed version of a more detailed version :

[#th:blockth:each="item : ${items}"]- [#th:blockth:utext="${item}"/][/th:block]

Notice how this new syntax is based on elements (i.e., processed tags) that are declared as [#element …] instead of <element …> The elements are opened as [#element …] and closed as [/element] , and autonomous tags can be declared by minimizing the open element with / in a way almost equivalent to XML tags : [#element…/]
The standard dialect contains only the processor for one of these elements : already known th:block although we could extend our dialects and create new elements in the usual way. In addition, the element th:block ( [#th:block …] [/th:block] ) is allowed to be abbreviated as an empty string ( [# …]…[/] ), so the above block is actually equivalent to :

[# th:each="item : ${items}"]- [# th:utext="${item}" /][/]

And the given [# th:utext="${item}" /] is equivalent to an embedded unshaded expression, we could just use it to have less code. So we get the first code snippet we saw above :

[# th:each="item : ${items}"]- [(${item})][/]

Note that the text syntax requires a full balance of elements (no unclosed tags) and quoted attributes – this is more of an XML style than an HTML style.
Let’s look at a more complete example of the TEXT template, a text email template :

Dear [(${customer.name})], This is the list of our products:[# th:each="prod : ${products}"]- [(${prod.name})]. Price: [(${prod.price})] EUR/kg[/]Thanks, The Thymeleaf Shop

After execution, the result may be something like :

Dear Mary Ann Blueberry, This is the list of our products:- Apricots. Price: 1.12 EUR/kg- Bananas. Price: 1.78 EUR/kg- Apples. Price: 0.85 EUR/kg- Watermelon. Price: 1.91 EUR/kgThanks, The Thymeleaf Shop

And another example in pattern mode JAVASCRIPT , the file greeter.js, we treat as a text template, and which we call in HTML pages. Note that this is not a <script> block in an HTML template, but the .js file is treated as a template by itself :

var greeter = function() {var username = [[${session.user.name}]];[# th:each="salut : ${salutations}"]alert([[${salut}]] + " " + username);[/]};

Once executed, the result could be something like :

var greeter = function() {var username = "Bertrand \"Crunchy\" Pear";alert("Hello" + " " + username);alert("Ol\u00E1" + " " + username);alert("Hola" + " " + username);};

Shielded element attributes
To avoid interacting with parts of a template that can be handled in other modes (such as text mode embedded within an HTML template), Thymeleaf 3.0 allows you to avoid element attributes in its text syntax. Thus :

  • Attributes in TEXT template mode will be unshaded by HTML
  • Attributes in JAVASCRIPTtemplate mode will be JavaScript-unescaped
  • Attributes in CSStemplate mode will be CSS-unescaped

So this would be great in the TEXT template (note the gt;):

[# th:if="${120<user.age}"]Congratulations![/]

Of course, the example doesn’t make much sense in a real text template, but it’s a good idea if we process an HTML template with a block of th:inline="text" containing the code above, and we want to make sure that our browser doesn’t take <user.age for the open tag name when we statically open the file as a prototype.

13.2 Extensibility

One advantage of this syntax is that it is as extensible as the markup. Developers can still define their dialects with configurable elements and attributes, apply a prefix (optional) to them, and then use them in text template modes :

[#myorg:dosomething myorg:importantattr="211"]some text[/myorg:dosomething]

13.3 Text comment blocks for prototype only : adding code

Template modes JAVASCRIPT and CSS ( not available for TEXT ) allow you to include code between the special comment syntax /*[+…+]*/ to have Thymeleaf automatically uncomment such code when processing the pattern :

var x = 23;/*[+var msg = "This is a working application";+]*/var f = function() {...

To be executed as :

var x = 23;var msg = "This is a working application";var f = function() {...

You can include expressions within these comments and they will be evaluated :

var x = 23;/*[+var msg = "Hello, " + [[${session.user.name}]];+]*/var f = function() {...

13.4 Comment text blocks at parser level : code removal

Similarly, as for the comment blocks for the prototype, all three modes of the text patterns ( TEXT , JAVASCRIPT and CSS ) allow you to instruct Thymeleaf to remove code between special /*[- */ and /* -]*/ markers :

var x = 23;/*[- */var msg = "This is shown only when executed statically!";/* -]*/var f = function() {...

Or in TEXT mode :

../*[- Note the user is obtained from the session, which must exist -]*/Welcome [(${session.user.name})]!...

13.5 Natural JavaScript and CSS Templates

As seen in the previous chapter, JavaScript and CSS-inlining offer the ability to include embedded expressions in JavaScript / CSS comments, such as :

..var username = /*[[${session.user.name}]]*/ "Sebastian Lychee";...

which is valid JavaScript, and the executable code may look like this :

..var username = "John Apricot";...

The same trick of including embedded expressions within comments can actually be used for the entire text mode syntax :

/*[# th:if="${user.admin}"]*/alert('Welcome admin');/*[/]*/

This warning in the above code will be shown when the template is opened statically because it is 100% JavaScript and also when the template is run if the user is the administrator. This is equivalent to :

[# th:if="${user.admin}"]alert('Welcome admin');[/]

which is actually the code that the original version converts during pattern parsing.
Note, however, that wrapping elements in comments does not clear the lines in which they reside (right as long as ; is not found), as inlined expressions do. This behavior is reserved only for inlined expressions.
Thus, Thymeleaf 3.0 allows you to create complex JavaScript scripts and CSS style sheets as natural templates, valid as a prototype and as a working template.

You may also like