DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Why Angular and ASP.NET Core Make a Winning Team
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular v16: A New Era of Angular Development
  • Angular Best Practices For Developing Efficient and Reliable Web Applications

Trending

  • Application Integration for IoT Devices: A Detailed Guide To Unifying Your Ecosystem
  • Supercharge Your Software Development Journey With DevOps, CI/CD, and Containers
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • Log Analysis: How to Digest 15 Billion Logs Per Day and Keep Big Queries Within 1 Second
  1. DZone
  2. Coding
  3. Frameworks
  4. Thymeleaf: fragments and angularjs router partial views

Thymeleaf: fragments and angularjs router partial views

Biju Kunjummen user avatar by
Biju Kunjummen
·
Jun. 16, 14 · Interview
Like (2)
Save
Tweet
Share
29.28K Views

Join the DZone community and get the full member experience.

Join For Free
One more of the many cool features of thymeleaf is the ability to render fragments of templates - I have found this to be an especially useful feature to use with AngularJs.

AngularJS $routeProvider or AngularUI router can be configured to return partial views for different "paths", using thymeleaf to return these partial views works really well.

Consider a simple CRUD flow, with the AngularUI router views defined this way:

app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("list");

    $stateProvider
        .state('list', {
            url:'/list',
            templateUrl: URLS.partialsList,
            controller: 'HotelCtrl'
        })
        .state('edit', {
            url:'/edit/:hotelId',
            templateUrl: URLS.partialsEdit,
            controller: 'HotelEditCtrl'
        })
        .state('create', {
            url:'/create',
            templateUrl: URLS.partialsCreate,
            controller: 'HotelCtrl'
        });
});

The templateUrl above is the partial view rendered when the appropriate state is activated, here these are defined using javascript variables and set using thymeleaf templates this way(to cleanly resolve the context path of the deployed application as the root path):

<script th:inline="javascript">
    /*<![CDATA[*/
    var URLS = {};
    URLS.partialsList = /*[[@{/hotels/partialsList}]]*/ '/hotels/partialsList';
    URLS.partialsEdit = /*[[@{/hotels/partialsEdit}]]*/ '/hotels/partialsEdit';
    URLS.partialsCreate = /*[[@{/hotels/partialsCreate}]]*/ '/hotels/partialsCreate';
    /*]]>*/
</script>

Now, consider one of the fragment definitions, say the one handling the list:

file: templates/hotels/partialList.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout/sitelayout">
<head>
    <title th:text="#{app.name}">List of Hotels</title>
    <link rel="stylesheet" th:href="@{/webjars/bootstrap/3.1.1/css/bootstrap.min.css}"
          href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
    <link rel="stylesheet" th:href="@{/webjars/bootstrap/3.1.1/css/bootstrap-theme.css}"
          href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.css"/>
    <link rel="stylesheet" th:href="@{/css/application.css}" href="../../static/css/application.css"/>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h1 class="well well-small">Hotels</h1>
        </div>
    </div>
    <div th:fragment="content">
        <div class="row">
            <div class="col-xs-12">
                <table class="table table-bordered table-striped">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Zip</th>
                        <th>Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr ng-repeat="hotel in hotels">
                        <td>{{hotel.id}}</td>
                        <td>{{hotel.name}}</td>
                        <td>{{hotel.address}}</td>
                        <td>{{hotel.zip}}</td>
                        <td><a ui-sref="edit({ hotelId: hotel.id })">Edit</a> | <a
                                ng-click="deleteHotel(hotel)">Delete</a></td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <a ui-sref="create" class="btn btn-default">New Hotel</a>
            </div>
        </div>
    </div>
</div>
</body>
</html>

The great thing about thymeleaf here is that this view can be opened up in a browser and previewed. To return the part of the view, which in this case is the section which starts with "th:fragment="content"", all I have to do is to return the name of the view as "hotels/partialList::content"!

The same approach can be followed for the update and the create views.

One part which I have left open is about how the uri in the UI which is "/hotels/partialsList" maps to "hotels/partialList::content", with Spring MVC this can be easily done through a View Controller, which is essentially a way to return a view name without needing to go through a Controller and can be configured this way:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

 @Override
 public void addViewControllers(ViewControllerRegistry registry) {
  registry.addViewController("/hotels/partialsList").setViewName("hotels/partialsList::content");
  registry.addViewController("/hotels/partialsCreate").setViewName("hotels/partialsCreate::content");
  registry.addViewController("/hotels/partialsEdit").setViewName("hotels/partialsEdit::content");
 }

}

So to summarize, you create a full html view using thymeleaf templates which can be previewed and any rendering issues fixed by opening the view in a browser during development time and then return the fragment of the view at runtime purely by referring to the relevant section of the html page.

A sample which follows this pattern is available at this github location: https://github.com/bijukunjummen/spring-boot-mvc-test

Thymeleaf Fragment (logic) AngularJS

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why Angular and ASP.NET Core Make a Winning Team
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular v16: A New Era of Angular Development
  • Angular Best Practices For Developing Efficient and Reliable Web Applications

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: