Wednesday, October 9, 2019

How to access model attributes inside JavaScript present in Thymeleaf templates?

The prime objective of this write up is to discuss "the how" of accessing model attributes inside JavaScript present in Thymeleaf templates. But I would also be touching on the situation in which I required to access the model attributes inside JavaScript present in Thymeleaf templates which would surely help one to design their web pages in a better manner.

1. Introduction

Thymeleaf offers a series of “scripting” modes for its inlining capabilities so that one can access their exposed Controller's model data inside scripts created in some script languages. Current available scripting modes are javascript (th:inline="javascript") and dart (th:inline="dart").
         I personally believe that it's good to know about the available features in any language like Thymeleaf but it's equally important to know exactly when to use which features? If you are only interested in knowing about Thymeleaf's Script Inlining feature then you could check out section 2 only but if you are also keen to know the instances where I have used this feature while developing a digital learning platform then you should also see section 3.

2. Script Inlining

Below is the sample code snippet which needs to be added in the Thymeleaf page for accessing our exposed Controller's model data inside JavaScripts:
<script th:inline="javascript" type="text/javascript">

    var username = /*[[${}]]*/ 'Anshul';
    var isbn = /*[[${titleModel.isbn}]]*/ 0;
    var assignmentId = /*[[${#httpServletRequest.getParameter('assignmentid')}]]*/ 0;

    $(document).ready(function() {
 if ( assignmentId != 0 && assignmentId != null ) {
 } else {
where The /*[[...]]*/ syntax, instructs Thymeleaf to evaluate the contained expression.

Few pointers to note here:
  • 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). This expression evaluation is intelligent and not limited to Strings. Thymeleaf will correctly convert and write it in corresponding Javascript/Dart syntax. The following kinds of objects conversion are allowed: Strings, Numbers, Booleans, Arrays, Collections, Maps, Beans (objects with getter and setter methods).
  • Being a javascript comment (/*...*/), our expression will be ignored when displaying the page statically in a browser.
  • The code after the inline expression ('Anshul' or  0) will be executed when displaying the page statically.
  • One can also do it without comments with the same effects, but that will make the script to fail when loaded statically. 

3. Requirement & Design Discussion for a module

Recently I have participated in the design & development of a powerful digital learning platform using Microservice architecture. Today we would first know one of the module's requirements at very high level and then discuss different design approaches for developing that. It would give you an idea about when to use Thymeleaf's Script Inlining feature. 


  1. Provide the capability to teachers for managing their created assignments whereas allowing students to view their assigned assignments.
  2. The teacher could click on any assignment from the list of assignments and would see the assignment details page containing details like assignment status, assignment user details, etc in a tab beside the Manage Assignment tab. 
  3. There would be an option(button or Call To Action) in the assignment details tab to preview the questions present in the assignment. 

Design Discussion:

As usual, we too received the requirements gradually i.e. initially we got #1 then much later stage received #2 & #3. Since the layout of both the teacher's Manage Assignments page and student's My Assignments page was almost similar(both shows all the subtopic, multi-subtopic, topic, multi-topic assignments in list views for a title using accordion ) with only one subtle  difference that teacher would see all assignments with some additional details and extra privileges whereas students could see only their assignments. We discussed among us and agreed that we would create a single controller method and single Thymeleaf page for this requirement and would conditionally & dynamically form the page. We implemented this and it worked perfectly fine.

Now at a later stage, we received #2. Now we have to think about its design & implementation approach. Some facts are pretty clear like:
  •  One needs to make a service call to fetch the required assignment, add it in model attributes and dynamically form the Assignment Details tab. 
  • The current Manage Assignment/ My Assignments page data would now appear in a tab and besides that, we would have another tab called Assignment Details. One question pops up, is it a good idea to reload the whole page on click of the assignment and show both Manage Assignment and Assignment Details tab?  You are right Obviously not. So what we had in our hand then, two tabs on the page and same @RequestMapping path in the URL with one additional data i.e. query parameter "assignmentid". So the option for making direct service call was off the chart and it was evident that one needs to make an Ajax call from JavaScript to get assignment details and add the fetched data to the Assignment details tab.

Some more questions regarding the Thymeleaf's capability and implementation appeared like
  • Are Thymeleaf templates smart enough to detect the presence of assignment id in the URL and accordingly make Ajax call to fetch and add respective assignment data in the Assignment Details tab?
  • Do we have all the required parameters like ISBN of a title, "assignmentid" available in the JavaScript to make the service call?  
Now we needed to have the access to our exposed controller's model attributes inside JavaScript to make the service call. We came to know that one can use Thymeleaf's script inlining features to integrate our data inside scripts. 

One thing to note here that after receiving the #2 & #3, we have revisited our implementation for #1 and restructured it. What we did?

We have created a layout HTML page using Thymeleaf which contains
  • HTML article tag having Thymeleaf's th:replace attribute to add the fragments that would form the actual content of the page. This fragment contains multiple empty article tags having a unique id attribute to distinguish between the data for Manage Assignment/My assignments & Assignment Details tab. 
  • Using Thymeleaf's script inlining, we have made the controller's method required parameter available inside JavaScript and then conditionally made the corresponding service calls depending upon the presence of assignment id in the URL and populated the data using jQuery in the respective article tag.
  • One more interesting thing to note here, suppose a user directly wants to view particular assignment details only and not interested in viewing list of assignments then do you think is it a good idea to make two service calls, i.e. one for Manage Assignment/My assignments tab and one for Assignment Details tab? Obviously not right? Therefore we have applied the concept of lazy loading here using JavaScript and by adding a loaded flag. Initially loaded flag would be set to false which means Manage Assignment/My assignments tab is not loaded.  Manage Assignment/My assignments related controller's method would be called only if someone loaded it explicitly, closes the Assignment Details tab, switch to it from any other tabs. 
  • Later we received another requirement where we needed to show some other data in a separate tab on click of some Call to action buttons. Due to the above design approach, it has become very easy. We just added one more blank article tag in the fragment, made the Ajax call and added the data in the newly added article tag using jQuery. 

3. Conclusion

For developers, designers or architects, it's common to think about reusability, redundancy, modularity, readability, scalability while designing any software systems or a web-applications. Thymeleaf provides many features if used carefully could lead to better design of the maintainable, reliable software system. Today we have learned about the Script Inlining feature of Thymleaf and instances where it could be used. I hope it would surely help you while development. Happy Learning !!

No comments:

Post a Comment