Inlining

Um Thymeleaf-Ausdrücke innerhalb des HTML-Codes zu verwenden existiert eine einfache Syntax:

In order for inlining to work, we must activate it by using the th:inline attribute, which has three possible values or modes ( text , javascript and none ). Let’s try text :

<p th:inline="text">Hello, [[${session.user.name}]]!</p>

…instead of this:

<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>

Es spielt keine Rolle, ob das Element selbst oder ein parent das Attribut th:inline besitzt.

Hinweis

Why aren’t we doing this from the beginning? It’s less code than all those th:text attributes! Well, be careful there, because although you might find inlining quite interesting, you should always remember that inlined expressions will be displayed verbatim in your HTML files when you open them statically, so you probably won’t be able to use them as prototypes anymore!

JavaScript Inlining

/*<![CDATA[*/
  ...
  var username = /*[[${session.user.name}]]*/ 'Sebastian';
  ...
/*]]>*/
  • Being a javascript comment ( /.../ ), our expression will be ignored when displaying the page statically in a browser.
  • The code after the inline expression ( 'Sebastian' ) will be executed when displaying the page statically.
  • Thymeleaf will execute the expression and insert the result, but it will also remove all the code in the line after the inline expression itself (the part that is executed when displayed statically).

Welche Datentypen können verwendet werden?

Note that this evaluation is intelligent and not limited to Strings. Thymeleaf will correctly write in Javascript/Dart syntax the following kinds of objects:

  • Strings
  • Numbers
  • Booleans
  • Arrays
  • Collections
  • Maps
  • Beans (objects with getter and setter methods)

Beispiel:

var user = /*[[${session.user}]]*/ null;

Code hinzufügen

Um Code zu einem JavaScript hinzuzufügen, der nur ausgeführt wird, wenn das Thymeleaf Dokument gerendert wird, wird die folgende Syntax verwendet:

/*[+
  var msg = 'This is a working application';
+]*/

Code entfernen

Das ganze funktioniert natürlich auch umgekehrt:

/*[- */
  var msg = 'This is a non-working template';
/* -]*/

results matching ""

    No results matching ""