### Product Service Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md A simple Java service class for retrieving product information from a repository. ```java public class ProductService { ... public List findAll() { return ProductRepository.getInstance().findAll(); } public Product findById(Integer id) { return ProductRepository.getInstance().findById(id); } } ``` -------------------------------- ### WebContext Instantiation Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Example of creating a WebContext instance, which is required for WebApplicationTemplateResolver and needs IWebExchange information. ```java WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ``` -------------------------------- ### HTML Template Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md A simple HTML template structure for the 'home' page, including a welcome message. ```html Good Thymes Virtual Grocery

¡Bienvenido a nuestra tienda de comestibles!

``` -------------------------------- ### HomeController Implementation Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Example of a HomeController class implementing IGTVGController to process templates using WebContext and ITemplateEngine. ```java public class HomeController implements IGTVGController { public void process( final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception { WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); templateEngine.process("home", ctx, writer); } } ``` -------------------------------- ### Complete TEXT Template Example for Email Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md A practical example of a plain text email template using Thymeleaf's textual syntax for iterating over products and displaying their details. ```text Dear [(${customer.name})], This is the list of our products: [# th:each="prod : ${products}"] - [(${prod.name})]. Price: [(${prod.price})] EUR/kg [/] Thanks, The Thymeleaf Shop ``` -------------------------------- ### Initialize WebApplicationTemplateResolver Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Instantiates a WebApplicationTemplateResolver for a given application. This is the starting point for configuring template resolution. ```java final WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application); ``` -------------------------------- ### FileTemplateResolver Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Java code snippet demonstrating how to resolve templates as files from the file system using FileTemplateResolver. ```java return new FileInputStream(new File(template)); ``` -------------------------------- ### UrlTemplateResolver Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Java code snippet demonstrating how to resolve templates as URLs using UrlTemplateResolver. ```java return (new URL(template)).openStream(); ``` -------------------------------- ### Example HTML using Custom Attribute Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/sayhelloextendingthymeleaf5minutes.md Demonstrates the usage of a custom attribute within an HTML template after integrating a custom Thymeleaf dialect. This example assumes a 'SayToAttributeTagProcessor' is defined and associated with the 'hello' dialect prefix. ```html

Hello World!

``` -------------------------------- ### Create and Configure Template Engine Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Instantiate the TemplateEngine and set the required TemplateResolver. This is the basic setup for using Thymeleaf. ```java templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); ``` -------------------------------- ### Decoupled Template Logic Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf3migration.md Shows an example of a Thymeleaf logic file ('home.th.xml') that injects attributes into a corresponding HTML template using markup selectors. ```xml ``` -------------------------------- ### Signup Controller Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/layouts.md A Spring MVC controller method demonstrating a signup process. It handles form validation, account creation, user signin, and setting flash attributes for success messages. ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ModelAttribute; import javax.validation.Valid; import org.springframework.validation.Errors; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @PostMapping("signup") 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:/"; } ``` -------------------------------- ### Improved Inlining Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf3migration.md Demonstrates the improved inlining mechanism for outputting data without extra tags or attributes in HTML mode. ```html

This product is called [[${product.name}]] and it's great!

``` -------------------------------- ### Server-Relative URL Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standardurlsyntax.md Creates a URL that is relative to the server root, ignoring the current application's context. Useful for linking to other applications on the same server. ```html ``` ```html ``` -------------------------------- ### StringTemplateResolver Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Java code snippet demonstrating how to resolve templates directly as a String using StringTemplateResolver. ```java return new StringReader(templateName); ``` -------------------------------- ### ClassLoaderTemplateResolver Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Java code snippet demonstrating how to resolve templates as classloader resources using ClassLoaderTemplateResolver. ```java return Thread.currentThread().getContextClassLoader().getResourceAsStream(template); ``` -------------------------------- ### Logic-less HTML Template Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf3migration.md Presents a clean HTML template file that is intended to be processed by Thymeleaf using a separate logic file. ```html
Jeremy Grapefruit Normal User
Alice Watermelon Administrator
``` -------------------------------- ### th:include vs th:insert - th:insert Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Demonstrates the usage of th:insert, which inserts the fragment including the tag it is defined on. This is the recommended replacement for th:include. ```html
...
...

something

``` -------------------------------- ### Expression Preprocessing Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Demonstrates expression preprocessing where a variable expression is evaluated first, and its result is used as part of a subsequent expression, such as internationalization. ```html #{selection.__${sel.code}__} ``` -------------------------------- ### Attribute Precedence Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Demonstrates the execution order of attributes within the same tag, where th:each executes before th:text. ```html ``` -------------------------------- ### Lazy Loading Context Variable in Java Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Example of implementing ILazyContextVariable to defer loading of context variables, such as collections, until they are actually needed. ```java context.setVariable( "users", new LazyContextVariable>() { @Override protected List loadValue() { return databaseRepository.findAllUsers(); } }); ``` -------------------------------- ### Context-Relative URL Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standardurlsyntax.md Generates a URL relative to the web application's context root. This is the most common type of URL for internal application links. ```html
``` ```html ``` -------------------------------- ### Fragment Definition Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf3migration.md Defines a fragment named 'common_header' that accepts 'title' and 'links' as parameters, demonstrating how to use passed fragments. ```html The awesome application ``` -------------------------------- ### th:include vs th:insert - th:block Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Demonstrates using th:block with th:fragment to insert content. The th:block tag disappears after evaluation, offering flexibility. ```html
...
... something ``` -------------------------------- ### Dynamic Table with Rows Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Example of a dynamic table where rows can be added or removed. It uses `th:each` to iterate over rows and binds fields using index notation. ```html
Row Variety Seeds per cell
1
``` -------------------------------- ### JSP to Thymeleaf Conversion Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/petclinic.md Illustrates the transformation of a JSP file to a Thymeleaf HTML file, replacing JSP directives and include tags with Thymeleaf attributes like th:substituteby. ```html <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="datatables" uri="http://github.com/dandelion/datatables" %>
``` ```html PetClinic :: a Spring Framework demonstration ``` ```html ``` -------------------------------- ### Accessing Map Properties Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Illustrates accessing map properties using both dot and bracket syntax, which are equivalent to calling the map's get(...) method. ```java ${countriesByCode.ES} ${personsByName['Stephen Zucchini'].age} ``` -------------------------------- ### Check String Start and End Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Verifies if a String, array, list, or set starts or ends with a specified fragment. ```java /* * Check whether a String starts or ends with a fragment * Also works with arrays, lists or sets */ ${#strings.startsWith(name,'Don')} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set* ``` -------------------------------- ### Complex Variable Expression Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md This example illustrates how to combine conditional operators and default values within a Thymeleaf variable expression for complex logic. ```html 'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown')) ``` -------------------------------- ### th:include vs th:insert - th:include Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Demonstrates the usage of th:include, which inserts only the content of a fragment. This attribute is deprecated and will be removed in a future version. ```html
...
...

something

``` -------------------------------- ### JAVASCRIPT Template Mode Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md An example of a JavaScript file processed as a Thymeleaf textual template. It demonstrates inlining expressions and loops within a JS context. ```javascript var greeter = function() { var username = [[${session.user.name}]]; [# th:each="salut : ${salutations}"] alert([[${salut}]] + " " + username); [/] }; ``` -------------------------------- ### Match Day Today Model Processor Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md Example of a model processor that checks the day of the week and conditionally adds a banner. It extends AbstractAttributeModelProcessor and applies only to HTML mode. ```java public class MatchDayTodayModelProcessor extends AbstractAttributeModelProcessor { private static final String ATTR_NAME = "match-day-today"; private static final int PRECEDENCE = 100; public MatchDayTodayModelProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's own precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IModel model, final AttributeName attributeName, final String attributeValue, final IElementModelStructureHandler structureHandler) { if (!checkPositionInMarkup(context)) { throw new TemplateProcessingException( "The " + ATTR_NAME + " attribute can only be used inside a " + "markup element with class \"leaguetable\""); } final Calendar now = Calendar.getInstance(context.getLocale()); final int dayOfWeek = now.get(Calendar.DAY_OF_WEEK); // Sundays are Match Days!! if (dayOfWeek == Calendar.SUNDAY) { // The Model Factory will allow us to create new events final IModelFactory modelFactory = context.getModelFactory(); // We will be adding the "Today is Match Day" banner just after ``` -------------------------------- ### Basic HTML Template with Thymeleaf Namespace Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md An example of an HTML5 template using Thymeleaf's standard 'th:*' namespace attributes for dynamic content and URL resolution. Browsers ignore unknown 'th:*' attributes. ```html Good Thymes Virtual Grocery

Welcome to our grocery store!

``` -------------------------------- ### Spring Bean Definition Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/springmvcaccessdata.md Example of defining a Spring Bean with a specific name ('urlService') in a Spring configuration class. This bean can then be accessed via Thymeleaf. ```java @Configuration public class MyConfiguration { @Bean(name = "urlService") public UrlService urlService() { return () -> "domain.com/myapp"; } } public interface UrlService { String getApplicationUrl(); } ``` -------------------------------- ### Product List Template (Initial) Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Displays a list of products with details like name, price, stock status, and comments. Includes a link to view comments if available. ```html
NAME PRICE IN STOCK COMMENTS
Onions 2.41 yes 2 comment/s view
``` -------------------------------- ### Thymeleaf Template Usage Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md An example of how to use a custom Thymeleaf attribute processor in an HTML template. The 'score:classforposition' attribute is applied to a 'tr' tag, demonstrating the integration of custom logic. ```html ``` -------------------------------- ### Create Model and Add Elements Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md Demonstrates creating a new model and adding text and element tags to it using the Model Factory. Models are sequences of events, not DOM nodes. ```java final IModelFactory modelFactory = context.getModelFactory(); final IModel model = modelFactory.createModel(); model.add(modelFactory.createOpenElementTag("div", "class", "headlines")); model.add(modelFactory.createText(HtmlEscape.escapeHtml5(headlineText))); model.add(modelFactory.createCloseElementTag("div")); ``` -------------------------------- ### Create Server Root Relative URLs Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Use the `@{::~/path/to/something}` syntax to create server-root-relative URLs. This allows linking to different contexts on the same server. ```html @{::~/path/to/something} ``` -------------------------------- ### Configure SpringTemplateEngine in Java Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Sets up the SpringTemplateEngine, configuring a template resolver and enabling the SpringEL compiler for potential performance gains. ```java SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine; } ``` -------------------------------- ### Calling Methods Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows how to call methods on objects, including methods with and without arguments. ```java ${person.createCompleteName()} ${person.createCompleteNameWithSeparator('-')} ``` -------------------------------- ### Rendering a Specific Fragment by ID Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Example of a Thymeleaf template where only the div with the ID 'content' will be rendered. ```html ... ...
Only this div will be rendered!
... ``` -------------------------------- ### Build Jakarta Servlet Web Application Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Instantiate a Jakarta Servlet Web Application implementation using the provided servlet context. This is typically done at initialization time. ```java final JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(servletContext); ``` -------------------------------- ### Using th:insert and th:replace Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Demonstrates how to include a fragment using both `th:insert` and `th:replace`. ```html
``` -------------------------------- ### Thymeleaf Assertion Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Uses `th:assert` to validate expressions, useful for checking fragment parameters. ```html
...
``` -------------------------------- ### Build Web Exchange and Request Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Create an IWebExchange object for handling an incoming request, from which the IWebRequest can be obtained. This models the request handling process. ```java final HttpServletRequest request = ...; final HttpServletResponse response = ...; ... final IWebExchange webExchange = this.application.buildExchange(request, response); final IWebRequest webRequest = webExchange.getRequest(); ... final String path = webRequest.getPathWithinApplication(); ``` -------------------------------- ### Spanish Externalized Message Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Example of a Spanish message for the 'home.welcome' key in a properties file. This allows for internationalization. ```properties home.welcome=¡Bienvenido a nuestra tienda de comestibles! ``` -------------------------------- ### Rendering a Specific Fragment from a Template Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Example of a Thymeleaf template where only the div with the 'content' fragment attribute will be rendered. ```html ... ...
Only this div will be rendered!
... ``` -------------------------------- ### URL with Dynamic Parameters Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standardurlsyntax.md Illustrates using variable expressions and conditionals for URL parameter values. ```html
``` -------------------------------- ### Basic Fragment Insertion Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/layouts.md Demonstrates the basic syntax for inserting a fragment from another template using `th:insert`. ```xml
...
``` -------------------------------- ### Create java.util.Calendar Objects Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows how to create new Calendar instances from components (year, month, day, hour, minute, second, millisecond) and with specific time zones. Also includes methods for creating current date/time and today's date instances. ```java /* * Create calendar (java.util.Calendar) objects from its components */ ${#calendars.create(year,month,day)} ${#calendars.create(year,month,day,hour,minute)} ${#calendars.create(year,month,day,hour,minute,second)} ${#calendars.create(year,month,day,hour,minute,second,millisecond)} ${#calendars.createForTimeZone(year,month,day,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)} /* * Create a calendar (java.util.Calendar) object for the current date and time */ ${#calendars.createNow()} ${#calendars.createNowForTimeZone()} /* * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00) */ ${#calendars.createToday()} ${#calendars.createTodayForTimeZone()} ``` -------------------------------- ### Format Date in Thymeleaf Template Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Example of formatting a date using the `#calendars.format` utility in a Thymeleaf HTML template. ```html

Today is: 13 May 2011

``` -------------------------------- ### Parse Markup into Model Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md Illustrates creating an IModel by parsing a string of HTML markup using the Model Factory. ```java final IModel model = modelFactory.parse( context.getTemplateData(), "
Some headlines
"); ``` -------------------------------- ### ITemplateBoundariesProcessor Interface Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md Implement this interface to execute logic at the start and end of template processing. It allows initialization or disposal of resources. ```java public interface ITemplateBoundariesProcessor extends IProcessor { public void processTemplateStart( final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler); public void processTemplateEnd( final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler); } ``` -------------------------------- ### Calling Parameterizable Fragments Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows two ways to call a parameterizable fragment, by order and by name. ```html
...
...
...
``` -------------------------------- ### Merged Template Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows the resulting HTML after Thymeleaf merges the logic-less HTML template with its corresponding decoupled logic file. ```html
Jeremy Grapefruit Normal User
Alice Watermelon Administrator
``` -------------------------------- ### Applying Data Conversion with Double-Brace Syntax Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows how to use the double-brace syntax ${{...}} to pass expression results to a configured conversion service for formatting, such as converting a Calendar object to a String. ```html ... ``` -------------------------------- ### HTML boolean attribute example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Demonstrates the HTML syntax for boolean attributes like `checked`. In XHTML, these attributes can be set to their own name. ```html ``` ```html ``` -------------------------------- ### Build Template Engine Configuration Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Configures a WebApplicationTemplateResolver and TemplateEngine for processing HTML templates. ```java private static ITemplateEngine buildTemplateEngine(final IWebApplication application) { // Templates will be resolved as application (ServletContext) resources final WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application); // HTML is the default mode, but we will set it anyway for better understanding of code templateResolver.setTemplateMode(TemplateMode.HTML); // This will convert "home" to "/WEB-INF/templates/home.html" templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); // Cache is set to true by default. Set to false if you want templates to // be automatically updated when modified. templateResolver.setCacheable(true); final TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } ``` -------------------------------- ### Equivalent to Nested Object Selection Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows the equivalent of the nested object selection using direct property access, demonstrating the expansion of asterisk syntax. ```html

Name: Frederic Tomato

``` -------------------------------- ### Absolute URL Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standardurlsyntax.md Creates an absolute URL to an external resource. This URL is not modified by Thymeleaf unless URL rewriting is configured. ```html
``` ```html ``` -------------------------------- ### Accessing Context Information with #ctx Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Use #ctx to access the context object, which provides information about the current environment (standalone or web). #vars and #root are synonyms, but #ctx is recommended. ```java /* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IContext * ====================================================================== */ ${#ctx.locale} ${#ctx.variableNames} /* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IWebContext * ====================================================================== */ ${#ctx.request} ${#ctx.response} ${#ctx.session} ${#ctx.servletContext} ``` -------------------------------- ### Build Protocol-Relative URLs Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Construct protocol-relative URLs by starting the link expression with '//'. The browser will use the same protocol (HTTP/HTTPS) as the current page. ```html ... ``` -------------------------------- ### Create and Send a Simple Email with MimeMessageHelper Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/springmail.md Use MimeMessageHelper to easily construct email messages. Set sender, recipient, subject, and text, then send the message using the configured mailSender. ```java final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setFrom("sender@example.com"); message.setTo("recipient@example.com"); message.setSubject("This is the message subject"); message.setText("This is the message body"); this.mailSender.send(mimeMessage); ``` -------------------------------- ### Thymeleaf Text Escaping Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Demonstrates how HTML tags within a Thymeleaf text attribute are escaped by default, resulting in literal display. ```html

Welcome to our <b>fantastic</b> grocery store!

``` -------------------------------- ### URL with Dynamic Base Path Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standardurlsyntax.md Shows how the URL base path can be specified using a variable expression. ```html ``` -------------------------------- ### Creating an HTML Element with Model Factory Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/extendingthymeleaf.md Demonstrates how to use the Model Factory to create and add HTML elements to the template model. This is useful for dynamically generating content within templates. ```java final IModelFactory modelFactory = context.getModelFactory(); model.add(modelFactory.createOpenElementTag("h4", "class", "matchday")); // model.add(modelFactory.createText("Today is MATCH DAY!")); model.add(modelFactory.createCloseElementTag("h4")); ``` -------------------------------- ### Equivalent Dollar Syntax for Object Selection Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Shows the equivalent of the `th:object` and asterisk syntax using the standard dollar syntax `${...}`. ```html

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

``` -------------------------------- ### Selection Expression Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Illustrates selection expressions used with `th:object` to operate on a selected object, like a book's title. ```html
... ... ...
``` -------------------------------- ### Basic Variable Expression Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Used to access context variables or model attributes. Example shows accessing a user's name from the session. ```html ${session.user.name} ``` -------------------------------- ### Configure Conversion Service Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Set a custom conversion service for the Standard Dialect. This enables data conversion and formatting using the double-brace syntax. ```java IStandardConversionService customConversionService = ... StandardDialect dialect = new StandardDialect(); dialect.setConversionService(customConversionService); templateEngine.setDialect(dialect); ``` -------------------------------- ### Processable HTML5 Thymeleaf Template Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf3migration.md Example of a lenient Thymeleaf template that is processable in HTML5 mode, demonstrating support for unclosed tags and unquoted attributes. ```html

Whatever ``` -------------------------------- ### Calling Fragments with Local Variables Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Demonstrates calling a fragment without arguments using named local variables, equivalent to using `th:with`. ```html

...
``` -------------------------------- ### Build Server-Relative URLs Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Use the '~' symbol in link expressions to create server-relative URLs. These are also not prefixed with the application context path. ```html ... ``` -------------------------------- ### th:value Attribute for Input Fields Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Evaluates an expression and sets the value of an input field. This example uses it to set the value of a submit button. ```html ``` -------------------------------- ### Configure Resource Handlers Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Adds resource handlers for static assets like images, CSS, and JavaScript. ```java public void addResourceHandlers(final ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } ``` -------------------------------- ### HTML5-friendly Iteration with data-th-each Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Illustrates using the HTML5-friendly data-th-each syntax for iterating over a collection of users to display their login and name. ```HTML
... ...
``` -------------------------------- ### Configure FlowExecutor for Spring WebFlow Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Configures the FlowExecutor bean, which is necessary for Thymeleaf's integration with Spring WebFlow. Additional setup might be required. ```java @Bean public FlowExecutor flowExecutor() { // NOTE: Additional configuration might be needed in your app return getFlowExecutorBuilder(flowRegistry()).build(); } ``` -------------------------------- ### Recommended Fragment Expression Syntax Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/thymeleaf31whatsnew.md Illustrates the recommended syntax for fragment expressions using the '~{}' envelope. This syntax is preferred for th:insert and th:replace attributes. ```html
...
``` -------------------------------- ### Conditional link to product comments Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md A specific example of a conditional link that appears only when a product has associated comments. The 'th:if' attribute checks if the 'prod.comments' list is not empty. ```html view ``` -------------------------------- ### SayToPlanetAttributeTagProcessor Initialization Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/sayhelloagainextendingthymeleafevenmore5minutes.md Configures a new attribute tag processor for 'saytoplanet', specifying HTML mode, attribute name, precedence, and whether to remove the attribute after processing. ```java import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.model.IProcessableElementTag; import org.thymeleaf.processor.element.AbstractAttributeTagProcessor; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.model.AttributeName; import org.thymeleaf.model.IElementTagStructureHandler; public class SayToPlanetAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "saytoplanet"; private static final int PRECEDENCE = 10000; private static final String SAYTO_PLANET_MESSAGE = "msg.helloplanet"; public SayToPlanetAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) { /* * In order to evaluate the attribute value as a Thymeleaf Standard Expression, * we first obtain the parser, then use it for parsing the attribute value into ``` -------------------------------- ### Appending to an HTML class attribute Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Use `th:attrappend` to append a value to an existing HTML attribute. This example appends a CSS class to the `class` attribute. ```html ``` -------------------------------- ### Checkbox Field with Sequence Suffix Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Example of a checkbox input where Thymeleaf adds a sequence suffix to the ID. The `#ids.prev()` function can retrieve the last sequence value. ```html ``` -------------------------------- ### Using Literal Substitutions Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/usingthymeleaf.md Illustrates literal substitutions using vertical bars '|' for easy string formatting with variables, avoiding manual concatenation. ```html ``` ```html ``` ```html ``` -------------------------------- ### Spring Controller Fragment Inclusion Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/layouts.md Example of a Spring MVC controller returning a specific fragment (`signupForm`) for AJAX requests, otherwise returning the full view. ```java @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; } ``` -------------------------------- ### Build URLs with Parameters Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md Construct URLs with query parameters by specifying them within parentheses in the link expression. Ensure ampersands are HTML-escaped in attributes. ```html ... ``` ```html ... ``` -------------------------------- ### SeedStarterService Implementation Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md A Spring service class for managing SeedStarter entities, including methods to find all starters and add a new one. ```java @Service public class SeedStarterService { @Autowired private SeedStarterRepository seedstarterRepository; public List findAll() { return this.seedstarterRepository.findAll(); } public void add(final SeedStarter seedStarter) { this.seedstarterRepository.add(seedStarter); } } ``` -------------------------------- ### Nested Message and Variable Expressions Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/standarddialect5minutes.md An advanced example showing how variable expressions can be nested within message expressions to dynamically determine message keys or parameters. ```html #{${config.adminWelcomeKey}(${session.user.name})} ``` -------------------------------- ### Controller Mapped Methods for Seed Starter Management Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/tutorials/3.1/thymeleafspring.md Defines request mappings for showing the form page and processing the submission of new SeedStarter objects. ```java @RequestMapping({"/","/seedstartermng"}) public String showSeedstarters(final SeedStarter seedStarter) { seedStarter.setDatePlanted(Calendar.getInstance().getTime()); return "seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"save"}) public String saveSeedstarter( final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) { if (bindingResult.hasErrors()) { return "seedstartermng"; } this.seedStarterService.add(seedStarter); model.clear(); return "redirect:/seedstartermng"; } ``` -------------------------------- ### JSP Datatables Example Source: https://github.com/thymeleaf/thymeleaf-docs/blob/master/docs/articles/petclinic.md Original JSP code snippet demonstrating the use of a datatables tag library to display a list of owners with various columns and export options. ```html ```