.. _thymeleaf-commands: Thymeleaf Commands ================== Thymeleaf is a template engine, and Thymeleaf templates make up the views of our MVC application. In order to create our templates, we use attributes to pass data from the model, through the controllers, and to our views. Attributes ---------- Thymeleaf has many attributes that we could use. In this book, we focus on a few key ones. Displaying Data ^^^^^^^^^^^^^^^ ``th:text`` dynamically populates the contents of an HTML element. .. sourcecode:: html
If we want to pull in a value of a variable from the controller, we can use the **variable expressions** syntax, ``${}``. Let's say we want to pull in the value of a variable called ``hello``. .. sourcecode:: html Conditionally Displaying Data ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In order to conditionally display data, we need to use ``th:if`` and ``th:unless``. ``th:if`` will display the value of the element if the expression evaluates to ``true``. If the expression evaluates to ``false``, then the value of the element is NOT displayed. ``th:unless`` will display the value of the element if the expression evaluates to ``false``. If the expression evaluates to ``true``, then the value of the element is NOT displayed. .. admonition:: Example Let's say we want to conditionally display our grocery list. We do have a variable, ``pantryStatus``, that is a String. If ``pantryStatus`` is ``empty``, we want to display a list that includes staples like flour, sugar, and rice. If ``pantryStatus`` is not ``empty``, we want our grocery list to include our favorite fresh fruits and veggies, like bananas, strawberries, and broccoli. .. sourcecode:: html :linenos:We are at 123 N. 4th Avenue
Call us at (123) 456-7890
If we want to use the fragment, ``groceryStoreInfo``, in a separate template, ``index.html``, we could use ``th:replace``. .. sourcecode:: html :linenos: ``th:replace`` tells Thymeleaf to *replace* the ``div`` element in ``index.html`` with the one in ``fragments.html`` named ``groceryStoreInfo``. Static Resources ^^^^^^^^^^^^^^^^ We can use ``th:src`` to include static resources such as JavaScript files or images in your template. To include external URLs, we can use ``th:href``. .. admonition:: Example For our grocery store application, we have a few things we want to add. #. A link to our favorite grocery store's site so we can order online. #. A link to our styles, ``styles.css``. #. A picture of our local grocery store. .. sourcecode:: html :linenos: