forked from thymeleaf/thymeleaf.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayouts.html
executable file
·1229 lines (1010 loc) · 48.2 KB
/
layouts.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Thymeleaf Page Layouts - Thymeleaf: java XML/XHTML/HTML5 template engine</title>
<link rel="stylesheet" type="text/css" media="all" href="css/thymeleaf.css" />
<link rel="shortcut icon" href="http://www.thymeleaf.org/favicon.ico" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<style type="text/css">
/* ---------------------- */
/* STYLE FOR IMAGES */
/* ---------------------- */
#content img {
display: block;
margin-left: auto;
margin-right: auto;
-moz-box-sizing: border-box;
box-sizing: border-box;
max-width: 100%;
padding-left: 40px;
padding-right: 40px;
}
</style>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1276954-9']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="sh/scripts/shCore.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushXml.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushJava.js"></script>
<link href="sh/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="sh/styles/shThemeThymeleaf.css" rel="stylesheet" type="text/css" />
</head>
<body lang="en" dir="ltr">
<div id="page">
<div id="menu">
<ul>
<li><a href="index.html" title="Home">Home</a></li>
<li><a href="features.html" title="Features">Features</a></li>
<li><a href="download.html" title="Download">Download</a></li>
<li><a href="documentation.html" title="Documentation">Documentation</a></li>
<li><a href="ecosystem.html" title="Ecosystem">Ecosystem</a></li>
<li><a href="http://forum.thymeleaf.org" title="User Forum">User Forum</a></li>
<li><a href="issuetracking.html" title="Issue Tracking">Issue Tracking</a></li>
</ul>
</div>
<div id="header">
<a href="index.html" title="Thymeleaf home"><img src="images/thymeleaflogonameverysmall.png" class="logo" alt="Thymeleaf Template Engine"/></a>
</div>
<div id="breadcrumb">
<a href="index.html">thymeleaf</a>
::
<a href="documentation.html">documentation</a>
::
articles
::
<span class="current">thymeleaf page layouts</span>
</div>
<div id="content">
<h1>Thymeleaf Page Layouts</h1>
<p id="author">
<i>By Rafał Borowiec — <a href="http://blog.codeleak.pl" target="_blank">http://blog.codeleak.pl</a></i>
</p>
<p>
<strong>TABLE OF CONTENTS</strong>
</p>
<ol>
<li><a href="#intro">Introduction</a></li>
<li><a href="#exampleapp">Example Application</a></li>
<li><a href="#standard">Thymeleaf Standard Layout System</a></li>
<li><a href="#tiles">Thymeleaf Tiles Integration</a></li>
<li><a href="#layoutdialect">Thymeleaf Layout Dialect</a></li>
<li><a href="#other">Other Layout Options</a></li>
<li><a href="#future">Future Plans</a></li>
</ol>
<h2 id="intro">Introduction</h2>
<p>
Usually websites share common page components like the header, footer, menu and possibly many more.
These page components can be used by the same or different layouts. There are two main styles of
organizing layouts in projects: <em>include</em> style and <em>hierarchical</em> style. Both styles can be easily
utilized with Thymeleaf without losing its biggest value: <strong>natural templating</strong>.
</p>
<h3>Include-style layouts</h3>
<p>
In this style pages are built by embedding common page component code directly within each view to
generate the final result. In Thymeleaf this can be done using <strong>Thymeleaf Standard Layout System</strong>:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<body>
<div th:include="footer :: copy">...</div>
</body>
]]></script>
<p>
The include-style layouts are pretty simple to understand and implement and in fact they offer flexibility
in developing views, which is their biggest advantage. The main disadvantage of this solution, though, is
that some code duplication is introduced so modifying the layout of a large number of views in big
applications can become a bit cumbersome.
</p>
<h3>Hierarchical-style layouts</h3>
<p>
In hierarchical style, the templates are usually created with a parent-child relation, from the more
general part (layout) to the most specific ones (subviews; e.g. page content). Each component of the
template may be included dynamically based on the inclusion and substitution of template fragments. In
Thymeleaf this can be done using: <strong>Thymeleaf Layout Dialect</strong> and
<strong>Thymeleaf Tiles Integration</strong>.
</p>
<p>
The main advantages of this solution are the reuse of atomic portions of the view and modular design,
whereas the main disadvantage is that much more configuration is needed in order to use them, so the
complexity of the views is bigger than with Include Style Layouts which are more "natural" to use.
</p>
<h2 id="exampleapp">Example Application</h2>
<p>
All the samples and code fragments presented in this article are available on GitHub at
<a target="_blank"
href="https://github.com/thymeleaf/thymeleafexamples-layouts">https://github.com/thymeleaf/thymeleafexamples-layouts</a>
</p>
<h2 id="standard">Thymeleaf Standard Layout System</h2>
<p>
Thymeleaf Standard Layout System offers page fragment inclusion that is similar to <em>JSP includes</em>,
with some important improvements over them:
</p>
<h3>Basic inclusion with <kbd>th:include</kbd> and <kbd>th:replace</kbd></h3>
<p>
Thymeleaf can include parts of other pages as fragments (whereas JSP only includes complete pages)
using <kbd>th:include</kbd> (will include the contents of the fragment into its host tag) or
<kbd>th:replace</kbd> (will actually substitute the host tag by the fragment's). This allows
the grouping of fragments into one or several pages. Look at the example. The
<kbd>home/homeNotSignedIn.html</kbd> template is rendered when the anonymous user enters the home page
of our application.
</p>
<p>
Class <kbd>thymeleafexamples.layouts.home.HomeController</kbd>
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Principal principal) {
return principal != null ? "home/homeSignedIn" : "home/homeNotSignedIn";
}
}
]]></script>
<p>
Template <kbd>home/homeNotSignedIn.html</kbd>
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<div th:replace="fragments/header :: header">
<!-- ============================================================================ -->
<!-- This content is only used for static prototyping purposes (natural templates)-->
<!-- and is therefore entirely optional, as this markup fragment will be included -->
<!-- from "fragments/header.html" at runtime. -->
<!-- ============================================================================ -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Static header</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
<div class="hero-unit">
<h1>Test</h1>
<p>
Welcome to the Spring MVC Quickstart application!
Get started quickly by signing up.
</p>
<p>
<a href="/signup" th:href="@{/signup}" class="btn btn-large btn-success">Sign up</a>
</p>
</div>
<div th:replace="fragments/footer :: footer">© 2013 The Static Templates</div>
</div>
...
</body>
</html>
]]></script>
<p>
You can open the file directly in a browser:
</p>
<img src="images/layouts_homeNotSignedIn.png" alt="Home page when not signed in"/>
<p>
In the above example, we are building a page that consists of page header and page footer. In
Thymeleaf all fragments can be defined in a single file (e.g. <kbd>fragments.html</kbd>) or in a
separate files, like in this particular case.
</p>
<p>
Let's shortly analyze the inclusion statement:
</p>
<script type="syntaxhighlighter" class="brush:xml;gutter:false"><![CDATA[
<div th:replace="fragments/header :: header">...</div>
]]></script>
<p>
The first part of the statement, <kbd>fragments/header</kbd>, is a template name that we are referencing.
This can be a file (like in this example) or it can reference to the same file either by using the
<kbd>this</kbd> keyword (e.g. <kbd>this :: header</kbd>) or without any keyword (e.g.
<kbd>:: header</kbd>). The expression after double colon is a fragment selector (either fragment name
or <em>DOM selector</em>). As you can see also see, the header fragment contains a markup that is used
for static prototyping only.
</p>
<p>
Header and footer are defined in the following files:
</p>
<p>
Template <kbd>fragments/header.html</kbd>
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" th:fragment="header">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">My project</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#" th:href="@{/}">Home</a></li>
<li><a href="#" th:href="@{/message}">Messages</a></li>
<li><a href="#" th:href="@{/task}">Tasks</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li th:if="${#authorization.expression('!isAuthenticated()')}">
<a href="/signin" th:href="@{/signin}">Sign in</a>
</li>
<li th:if="${#authorization.expression('isAuthenticated()')}">
<a href="/logout" th:href="@{/logout}">Logout</a>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
]]></script>
<p>
...which we can open directly in a browser:
</p>
<img src="images/layouts_header.png" alt="Footer page"/>
<p>
And template <kbd>fragments/footer.html</kbd>
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div th:fragment="footer">
© 2013 Footer
</div>
</body>
</html>
]]></script>
<p>
Note how that the referenced fragments are specified with <kbd>th:fragment</kbd> attributes. This way
we can define multiple fragments in one template file, as it was mentioned earlier.
</p>
<p>
What is important here, is that all the templates can still be natural templates and can be viewed in a
browser without a running server.
</p>
<h3>Including with DOM Selectors</h3>
<p>
In Thymeleaf, fragments don't need to be explicitly specified using <kbd>th:fragment</kbd> at the
page they are extracted from. Thymeleaf can select an arbitrary section of a page as a fragment (even a
page living on an external server) by means of its DOM Selector syntax, similar to XPath expressions
and CSS selectors.
</p>
<script type="syntaxhighlighter" class="brush:xml;gutter:false"><![CDATA[
<div th:include="http://www.thymeleaf.org :: p.notice" >...</div>
]]></script>
<p>
The above code will include a paragraph with <kbd>class="notice"</kbd> from
<kbd>thymeleaf.org</kbd>. In order to make it happen, the template engine must be configured
with <kbd>UrlTemplateResolver</kbd>:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver());
templateEngine.addTemplateResolver(urlTemplateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
]]></script>
<p>
For the DOM Selector syntax reference checkout this section in Thymeleaf documentation:
<a target="_blank"
href="http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#appendix-c-dom-selector-syntax">DOM Selector syntax</a>.
</p>
<h3>Using expressions</h3>
<p>
In <kbd>templatename :: domselector</kbd>, both <kbd>templatename</kbd> and
<kbd>domselector</kbd> can be fully-featured expressions. In the below example we want to include
different fragments depending on a condition. If the authenticated user is an Admin, we will show a different footer than for a regular user:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<div th:replace="fragments/footer :: ${#authentication.principal.isAdmin()} ? 'footer-admin' : 'footer'">
© 2013 The Static Templates
</div>
]]></script>
<p>
<kbd>fragments/footer.html</kbd> has slightly changed, as we need to have two footers defined:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<!-- /* Multiple fragments may be defined in one file */-->
<div th:fragment="footer">
© 2013 Footer
</div>
<div th:fragment="footer-admin">
© 2013 Admin Footer
</div>
</body>
</html>
]]></script>
<h3>Parameterized inclusion</h3>
<p>
Fragments can specify arguments, just like methods. Whenever they are explicitly specified
with a <kbd>th:fragment</kbd> attribute, they can provide an argument signature that can then be
filled in with arguments from the calling <kbd>th:include</kbd> or <kbd>th:replace</kbd> attributes.
</p>
<p>
Examples talk best. We can use parameterized inclusion in many contexts but one real life context
is displaying messages on different pages of our application after successful form submission. Let's
look at the signup process in the application:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@RequestMapping(value = "signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute SignupForm signupForm,
Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return SIGNUP_VIEW_NAME;
}
Account account = accountRepository.save(signupForm.createAccount());
userService.signin(account);
// see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
MessageHelper.addSuccessAttribute(ra, "signup.success");
return "redirect:/";
}
]]></script>
<p>
As you can see, after a successful signup the user will be redirected to the home page with a
flash attribute filled in. We want to create a reusable and parameterized fragment. This can be
done as follows:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div th:fragment="alert (type, message)"
class="alert alert-dismissable" th:classappend="'alert-' + ${type}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<span th:text="${message}">Test</span>
</div>
</body>
</html>
]]></script>
<p>
The above <kbd>alert</kbd> fragment takes two arguments: <kbd>type</kbd> and <kbd>message</kbd>. The
<kbd>type</kbd> is the message type used for styling a message whereas the <kbd>message</kbd> is a text
that will be shown to the user. If we wanted, we could have even ensured that arguments existed or met
certain conditions using a <kbd>th:assert</kbd> attribute.
</p>
<p>
In order to include <kbd>alert</kbd> in any template we may write the following code (please note,
that the value of a variable can be an expression):
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<div th:replace="fragments/alert :: alert (type='danger', message=${errorMessage})">...</div>
]]></script>
<p>
Parameterized fragments let developers create functional-like fragments that are easier to reuse. Read
more about parameterized fragments in the Thymeleaf documentation:
<a target="_blank"
href="http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#parameterizable-fragment-signatures">Parameterizable fragment signatures</a>.
</p>
<h3>Fragment inclusion from Spring <kbd>@Controller</kbd></h3>
<p>
Fragments can be directly specified from a Spring MVC controller, i.e.
<kbd>signup :: signupForm</kbd>; which can be useful for AJAX controllers that return only a
small fragment of HTML to the browser. In the example below, the signup form fragment will be loaded
upon AJAX request and the whole signup view - on regular request:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@RequestMapping(value = "signup")
public String signup(Model model,
@RequestHeader("X-Requested-With") String requestedWith) {
model.addAttribute(new SignupForm());
if (AjaxUtils.isAjaxRequest(requestedWith)) {
return SIGNUP_VIEW_NAME.concat(" :: signupForm");
}
return SIGNUP_VIEW_NAME;
}
]]></script>
<p>
The fragment is defined in <kbd>signup/signup.html</kbd>:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<form method="post"
th:action="@{/signup}" th:object="${signupForm}" th:fragment="signupForm">
...
</form>
</body>
</html>
]]></script>
<p>
The above fragment is loaded when a new user wants to signup from a home page. The modal dialog
will be shown upon clicking <kbd>Signup</kbd> button and the content will be loaded via AJAX call (see
<kbd>home/homeNotSignedIn.html</kbd>).
</p>
<h3>References</h3>
<p>
Please check Thymeleaf documentation that describes this topic very thoroughly. You can find it
here: <a target="_blank"
href="http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#template-layout">Template Layout</a>.
</p>
<p>
Natural templating is greatly explained in
<a target="_blank" href="http://www.thymeleaf.org/petclinic.html">Bringing Thymeleaf and Natural
Templates to the Spring PetClinic</a> article in <kbd>And what about the Natural Templates thing?</kbd>
chapter. The example can be found on
<a target="_blank" href="https://github.com/thymeleaf/thymeleafexamples-petclinic/blob/thymeleafexamples-petclinic-20131104/src/main/webapp/WEB-INF/thymeleaf/owners/ownersList.html">GitHub</a>.
</p>
<h3>Thymol</h3>
<p>
When a Thymeleaf template is used as a static prototype, we cannot see the fragments we are including
using the <kbd>th:include/th:replace</kbd> host tags. We can only see the fragments aside, opening
their own template documents.
</p>
<p>
However, there is a way to see the real fragments included into our pages while prototyping. This
can be done using <a target="_blank" href="http://www.thymeleaf.org/ecosystem.html#thymol">Thymol</a>, an unofficial
JavaScript library that is an implementation of Thymeleaf's standard fragment inclusion functionality,
providing static support for some Thymeleaf attributes like <kbd>th:include</kbd> or
<kbd>th:replace</kbd>, conditional display with <kbd>th:if</kbd>/<kbd>th:unless</kbd>, etc.
</p>
<p>
As Thymol's author states:
<em>
Thymol was created in order to provide a more accurate static representation of Thymeleaf's dynamic
templating capabilities by offering support for Thymeleaf attributes through a statically accessible
javascript library
</em>
</p>
<p>
Thymol documentation and examples can be found on the official project site here:
<a target="_blank" href="http://sourceforge.net/u/jjbenson/wiki/thymol/">Thymol at SourceForge.net</a>.
</p>
<h2 id="tiles">Thymeleaf Tiles Integration</h2>
<p>
The <a target="_blank" href="https://github.com/thymeleaf/thymeleaf-extras-tiles2">Apache Tiles 2 Dialect</a> was created
in order to provide a more comfortable migration path to all those developers who are currently using
Apache Tiles 2 with JSP. <a target="_blank" href="http://tiles.apache.org/">Tiles</a> is one of the most used Java
templating frameworks, and a lot of JSP users are used to thinking in terms of Tiles when it comes
to layout.
</p>
<p>
Tiles dialect offers the possibility to go on doing layouts in the same way with Thymeleaf! In
addition, The Tiles dialect allows mixing JSPs and Thymeleaf, so that migrating JSP applications
gets much easier.
</p>
<h3>Configuration</h3>
<p>
To get started with Tiles Dialect we need to include it into the <kbd>pom.xml</kbd>. The dependency is:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-tiles2</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- Only if you use Spring (can be -spring3 if using that version) -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-tiles2-spring4</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
]]></script>
<p>
We will also need to configure the integration by adding a view resolver bean that will resolve Tiles views, a Tiles Configurer bean and of course the additional dialect to our template engine. Let's go through it really quickly:
</p>
<h4>Tiles view resolver</h4>
<p>
This view resolver will resolve Tiles views. We will configure it to have lower precedence, meaning that
it will be used when the previous one cannot resolve the views. We also need to set the
<kbd>viewClass</kbd> property of the resolver to <kbd>ThymeleafTilesView.class</kbd>.
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public ViewResolver tilesViewResolver() {
ThymeleafViewResolver vr = new ThymeleafViewResolver();
vr.setTemplateEngine(templateEngine());
vr.setViewClass(ThymeleafTilesView.class);
vr.setCharacterEncoding("UTF-8");
vr.setOrder(Ordered.LOWEST_PRECEDENCE);
return vr;
}
]]></script>
<h4>Basic view resolver</h4>
<p>
The basic view resolver will <strong>not</strong> resolve the views whose names start with
<kbd>message/*</kbd> — those are our Tiles-based views, and they will be resolved by the previous
<kbd>ViewResolver</kbd> bean. This is very important, if we want to have several view resolvers in
the application working alongside:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public ViewResolver thymeleafViewResolver() {
ThymeleafViewResolver vr = new ThymeleafViewResolver();
vr.setTemplateEngine(templateEngine());
vr.setCharacterEncoding("UTF-8");
vr.setOrder(Ordered.HIGHEST_PRECEDENCE);
// all message/* views will not be handled by this resolver;
vr.setExcludedViewNames(new String[]{"message/*"});
return vr;
}
]]></script>
<h4>Template Engine</h4>
<p>
We need to add the <kbd>Tiles Dialect</kbd> to the template engine:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
...
templateEngine.addDialect(new TilesDialect());
return templateEngine;
}
]]></script>
<h4>Tiles Configurer</h4>
<p>
The Tiles configurer bean will configure the Tiles container by adding Tiles definition files to it:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public ThymeleafTilesConfigurer tilesConfigurer() {
ThymeleafTilesConfigurer ttc = new ThymeleafTilesConfigurer();
ttc.setDefinitions(new String[]{"/WEB-INF/views/message/tiles-defs.xml"});
return ttc;
}
]]></script>
<p>
The complete configuration of the application lives in
<kbd>WebMvcConfig</kbd>, a Spring <em>java configuration</em> class.
</p>
<h3>Tiles definition</h3>
<p>
The Tiles definition is a standard XML file. In our example it looks like this:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
<!--
Main definition that uses layout.html to put title and content attributes from
Thymeleaf fragments; {1} will be evaluated to either 'list', 'form' or 'view'.
-->
<definition name="message/*" template="message/layout">
<put-attribute name="title" value="title/{1}"/>
<put-attribute name="content" value="content/{1}"/>
</definition>
<!--
Fragments that are included by messages/* definition above;
'template' attribute is a template file stored in /WEB-INF/views/message folder;
{1} will be evaluated to either 'list', 'form' or 'view'.
-->
<definition name="title/*" template="message/{1} :: title"/>
<definition name="content/*" template="message/{1} :: content"/>
</tiles-definitions>
]]></script>
<p>
In the above example, the <kbd>message/*</kbd> views will use a <kbd>message/layout.html</kbd>. In the
layout file we use two Tiles attributes that will be evaluated to <kbd>message/{1} :: title</kbd> and
<kbd>message/{1} :: content</kbd> fragments accordingly.
</p>
<p>
The layout file reads as follows:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
<!-- Tiles attribute will be put here at runtime -->
<title tiles:include="title">Title</title>
...
</head>
<body>
<!--/* Standard layout can be mixed with Tiles */-->
<div th:replace="fragments/header :: header">
<!-- ============================================================================ -->
<!-- This content is only used for static prototyping purposes (natural templates)-->
<!-- and is therefore entirely optional, as this markup fragment will be included -->
<!-- from "fragments/header.html" at runtime. -->
<!-- ============================================================================ -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Static header</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
<!--/* Tiles attribute will be put here at runtime */-->
<div tiles:replace="content">
<!-- ============================================================================ -->
<!-- This content is only used for static prototyping purposes (natural templates)-->
<!-- and is therefore entirely optional, as this markup fragment will be included -->
<!-- from "fragments/header.html" at runtime. -->
<!-- ============================================================================ -->
<h1>Static content for prototyping purposes only</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Praesent scelerisque neque neque, ac elementum quam dignissim interdum.
Phasellus et placerat elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Praesent scelerisque neque neque, ac elementum quam dignissim interdum.
Phasellus et placerat elit.
</p>
</div>
<div th:replace="fragments/footer :: footer">© 2014 The Static Templates</div>
</div>
</body>
</html>
]]></script>
<p>
We can see several things in the above example. Firstly, the layout is a natural template and it
is a valid UI design prototype (in this example the layout is very simple):
</p>
<img src="images/layouts_layouttiles.png" alt="Layout page"/>
<p>
Secondly, we can mix standard layout (<kbd>th:include/th:replace</kbd>) with Tiles dialect.
Thirdly, Thymeleaf has ability to include a template fragment instead of the whole template.
</p>
<h2 id="layoutdialect">Thymeleaf Layout Dialect</h2>
<p>
<a target="_blank"
href="https://github.com/ultraq/thymeleaf-layout-dialect">Layout Dialect</a> gives people the
possibility of using hierarchical approach, but from a Thymeleaf-only perspective and without the
need to use external libraries, like Apache Tiles. Thymeleaf Layout Dialect uses layout/decorator
templates to style the content, as well as it can pass entire fragment elements to included pages.
Concepts of this library are similar to
<a target="_blank" href="http://wiki.sitemesh.org">SiteMesh</a> or JSF with Facelets.
</p>
<h3>Configuration</h3>
<p>
To get started with Layout Dialect we need to include it into the <kbd>pom.xml</kbd>. The dependency is:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>1.2.1</version>
</dependency>
]]></script>
<p>
We will also need to configure the integration by adding an additional dialect to our template engine:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
...
templateEngine.addDialect(new LayoutDialect());
return templateEngine;
}
]]></script>
<p>
No other changes are required.
</p>
<h3>Creating a layout</h3>
<p>
The layout file is defined in <kbd>/WEB-INF/views/task/layout.html</kbd>:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html>
<head>
<!--/* Each token will be replaced by their respective titles in the resulting page. */-->
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">Task List</title>
...
</head>
<body>
<!--/* Standard layout can be mixed with Layout Dialect */-->
<div th:replace="fragments/header :: header">
...
</div>
<div class="container">
<div layout:fragment="content">
<!-- ============================================================================ -->
<!-- This content is only used for static prototyping purposes (natural templates)-->
<!-- and is therefore entirely optional, as this markup fragment will be included -->
<!-- from "fragments/header.html" at runtime. -->
<!-- ============================================================================ -->
<h1>Static content for prototyping purposes only</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Praesent scelerisque neque neque, ac elementum quam dignissim interdum.
Phasellus et placerat elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Praesent scelerisque neque neque, ac elementum quam dignissim interdum.
Phasellus et placerat elit.
</p>
</div>
<div th:replace="fragments/footer :: footer">© 2014 The Static Templates</div>
</div>
</body>
</html>
]]></script>
<p>
We can open the file directly in a browser:
</p>
<img src="images/layouts_layoutlayoutdialect.png" alt="Layout page"/>
<p>
The above file is our decorator for content pages we will be creating in the application.
The most important thing about the above example is <kbd>layout:fragment="content"</kbd>. This is the
<em>heart</em> of the decorator page (layout). You can also notice, that header and footer are included using
Standard Thymeleaf Layout System.
</p>
<p>
The content page looks as follows (<kbd>WEB-INF/views/task/list.html</kbd>):
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!DOCTYPE html>
<html layout:decorator="task/layout">
<head>
<title>Task List</title>
...
</head>
<body>
<!-- /* Content of this page will be decorated by the elements of layout.html (task/layout) */ -->
<div layout:fragment="content">
<table class="table table-bordered table-striped">
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Text</td>
<td>Due to</td>
</tr>
</thead>
<tbody>
<tr th:if="${tasks.empty}">
<td colspan="4">No tasks</td>
</tr>
<tr th:each="task : ${tasks}">
<td th:text="${task.id}">1</td>
<td><a href="view.html" th:href="@{'/' + ${task.id}}" th:text="${task.title}">Title ...</a></td>
<td th:text="${task.text}">Text ...</td>
<td th:text="${#calendars.format(task.dueTo)}">July 11, 2012 2:17:16 PM CDT</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
]]></script>
<p>
And in the browser it looks like this:
</p>
<img src="images/layouts_layoutlayoutdialectlist.png" alt="Layout page"/>
<p>
Content of this <kbd>task/list</kbd> view will be decorated by the elements of
<kbd>task/layout</kbd> view. Please note <kbd>layout:decorator="task/layout"</kbd> attribute in
<kbd><html></kbd> element. This attribute signals to the Layout Dialect which layout should
be used to decorate given view.
</p>
<p>
And what about <em>Natural Templates</em> using the Layout Dialect? Again, possible! In just the
same way as with Tiles Dialect, you simply need to add some prototyping-only markup around the
fragments being included in your templates and that's it!
</p>
<h3>Include style approach with Layout Dialect</h3>
<p>
Layout Dialect supports not only hierarchical approach — it also provides a way to use it