Thymeleaf pass parameter to fragment

Making reusable fragment/UI Components in Thymeleaf

Thymeleaf supports creation of 'function like' mechanism and pass parameters to make the UI components reusable.

In this example we are going to create a reusable alert component using thymeleaf:

The fragment definition is similar to how a function/method is defined:

File: _fragments/_utils.html

<div th:fragment="alertBox(message,type)">
//do stuff with message and type

Let's call with some parameters in another file:

<div th:replace="_fragments/_utils::alertBox ('A message','success')">

The parameter order is not important if you do like this:

<div th:replace="_fragments/_utils::alertBox (type = 'success', message='A message' )">

A complete example:

<div th:fragment="alertBox (message,type)">
${type == 'success' ? 'alert-success': ''}
${type == 'info' ? 'alert-info': ''}
${type == 'danger' ? 'alert-danger': ''} |"
class="alert alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<span th:text="${message}"></span>

Calling it:

<div th:replace="_fragments/_utils :: alertBox ('Hello this is a success!','success')">

<div th:replace="_fragments/_utils :: alertBox ('Danger! danger! .......','danger')">

<div th:replace="_fragments/_utils :: alertBox ( type = 'success', message='Success message' )">


No comments :

Post a Comment

Your Comment and Question will help to make this blog better...