thymeleaf , Render view fragments directly, using thymeleaf

Render view fragments directly, using thymeleaf


Tag: thymeleaf

I am trying to get just a part of the view(fragment) from a template, i just end up getting the following error

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "path/to/template::fragment", template might not exist or might not be accessible by any of the configured Template Resolvers

And this is the current configuration:

TemplateResolver resolver = new ServletContextTemplateResolver();
engine = new TemplateEngine();

It soud be possible as it is given as a feature(but using spring-mvc, which I am not):

The site application works using jsp, and the code that is failing looks like this:

render("surveys/survey", params,request,response);//This works
render("surveys/survey::surveyBody", params,request,response);//This fails

public static String render(String template,Map<String,?> context,HttpServletRequest request, HttpServletResponse response){
    IContext iContext = new WebContext(request,response,request.getServletContext(),Locale.US, context);
    return engine.process(template, iContext);

inside the template there is something like this

<div th:fragment="surveyBody">
        <div th:each="field,idx : ${survey.fields}" th:id="${'field_' +}" th:class="${field.type + ' row outter'}">
            <input type='hidden' th:id="${'field_' + + '_id'}" id='field_100_id' value='100' />
            <input type='hidden' th:id="${'field_' + + '_type'}" id='field_100_type' th:value='${field.type}' />
            <input type='hidden' th:id="${'field_' + + '_order'}" id='field_100_order' th:value='${field.obj.order}' />
            <input type='hidden' th:id="${'field_' + + '_outstanding'}" id='field_100_outstanding' value='-1' />
            <h3 th:utext="${field.obj.title[0].title}">title</h3>
            <h4 th:if="${!field.obj.subTitle.isEmpty()}" th:utext="${field.obj.subTitle[0].title}">subtitle</h4>
            <div class="answers row">
                <div th:replace="surveys/questions::${field.type}(${field},${disabled},${idx.index})"></div>


th:fragment is called in template using th:replace or th:include attributes.

Try to create a clear file (surveys/surveyfragment) and write there:

<div th:replace="surveys/survey::surveyBody"/>

And then call it:

render("surveys/surveyfragment", params,request,response);

Should work


The thymeleaf template now showing inner element from anchor tag

I have a strange problem while populating anchor tag attributes i.e. href using thymeleaf template, the inner element of a tag are not displayed. My code looks like below:- <li class="" th:each="aMenu : ${adminMenu}"> <a href="#" th:href="@{${aMenu.url}}" th:title="${aMenu.menuName}" th:text="${aMenu.menuName}"> <em th:class="${aMenu.menuCss}"/> <span th:text="${aMenu.menuName}"></span> </a> </li> The anchor tag is displayed...

Spring Boot + Thymeleaf: Bind empty form input to NULL-string

I have a very simple Spring Boot + Thymeleaf application with a single form and a pojo as backing model for the form. The backing model has a single string property that is null by default: public class Model { private String text = null; public String getText() { return...

How can i use for loop in javascript using thymeleaf?

I am using thymeleaf so when I run this application ,it gives me an error in (for(int i=0;i<10;i++) It means I have to respect the syntaxe of thymeleaf.My question is howa can I write this script using thymeleaf. <!DOCTYPE html> <html xmlns:th=""> <head> <title>Getting Started: Handing Form Submission</title> <meta http-equiv="Content-Type"...

Spring MVC + Thymeleaf: adding variable to all templates' context

How can I add a "global" variable such as username to be used all around my template context? Currently I am setting these explicitly to each ModelAndView object in my TemplateController....

Thymeleaf compare #locale expression object with string

I want to set a th:class attribute depending on the context locale using the expression object #locale. I have tried th:class="${#locale}=='en'?'active':''" th:class="${#locale=='en'}?'active':''" Both of them results in false, but whent I print it with th:text="${#locale}, I got the correct locale code (en,es). Any idea of how to compare the #locale...

Foreach without first row

I use this code <li th:each="r : ${data}">...</li> to get list of elements. Can I get a list without first row. Thanks....

Thymeleaf HTML5 long variable issue

I am new to Thymeleaf and HTML5. I have a variable order number of data type long. There is an input text field in the HTML for searching order number (assigned to order number variable), which always initialise to zero everytime when we load the HTML page. Also, I am...

Dandelion datatables exporting to Excel - missing export links

I've asked question on Dandelion forum but I did not recieve any answer so I am trying here. AFAIK the creator of Dandelion answers here as well so maybe I will be lucky this time. My stack is Spring 4, Thymeleaf and Dandelion Datatables 0.10.1. What I am trying to...

How to call url which depends on input in Thymeleaf?

I have a form in Thymeleaf in which there is a drop down list and a button. I want to call an URL when the button is clicked which depends on the value of drop down selected. From the dropdown, serviceId is selected and then the URL also uses serviceId....

Escaping '&' character in thymeleaf

I need an image loaded onto a html img tag using thymeleaf. The problem is, the image itself is obtained from a url which takes in two parameters. Sample: <img src="/products/images?categoryId=1&image=1" /> The trouble is, the image parameter is generated dynamically and hence I need to use a thymeleaf expression...

Spring Multipart File Upload

I'm trying to upload a multipart file using Spring mvc, tomcat, Tyhmleaf but can't get it work. java.lang.NullPointerException sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke( sun.reflect.DelegatingMethodAccessorImpl.invoke( java.lang.reflect.Method.invoke( My controller: @RequestMapping(value =...

can't reference iteration variable in Thymeleaf

I try to iterate a list of items using th:each, <div class="row" th:each="item : *{items}"> <input type="text" th:field=""/> </div> it works if I access the iteration variable using th:text, but throws java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'item' available as request attribute when I use th:field...

Form parameter is null with Thymeleaf and Spring MVC

i'm having a problem with Thymeleaf and Spring MVC. I'm following a tutorial from website and when I've tried to expand this tutorial, I ran into a problem. If I add another parameter to my model class (on my example, I've added a Date parameter and a long...

Adding external static files (css, js, png …) in spring boot

Background I have a spring boot application which has the logo.png file added to the static folder of the resource file, which is eventually built into the jar file which is used in the execution. This jar application need to be run in multiple instances for different clients. So what...

How to access model attribute in jQuery

I need to pass a model attribute from controller to HTML. My application is using HTML5, thymeleaf & springboot. I am using the below code snippet: $(document).ready(function() { var modelAttributeValue = '${modelAttribute}'; } Code snippet from my controller: model.addAttribute("modelAttribute", "viewEmployee") But I am not able to get the value assigned...

Spring Form Validation with Two Objects

Got a complicated problem with a Spring Boot application that I've been trying to solve for a while now and I'm hoping someone can help me. I've removed all the other parts of the project and tried to make it as simple as possible. If you go to localhost:8080, there'll...

Spring Portlet + Thymeleaf: Bind object for ActionMapping

I've a problem with a Spring 4 Portlet using the template engine Thymeleaf. I want to convert an existing servlet which is working fine to a portlet. I use Thymeleaf for editing objects in forms in JSP-files. <form method="POST" th:object="${object}" th:action="${portletActionURL}"> <input th:field="*{objField}"/> ... <input type="submit"/> </form> portletActionURL is a...

Thymeleaf: th:each error

I want to do this in thymeleaf template, but I got error <tr th:each="user : ${userList}" th:id="${}}"> <td th:text="${}"></td> <td th:text="${}"></td> <td th:text="${user.gender}"></td> <td th:text="${user.level}"></td> </tr> error Could not parse as expression: "${}}" Please tell me how to deal with this problem :) Thanks,...

Thymeleaf - Appending
to input tag

I'm trying to append a <br> after every input line in a form, but Thymeleaf keeps giving me parsing error. Here is the code piece that I'm having trouble with: <form th:if="${not #lists.isEmpty(brands)}"> <input th:each="brand : ${brands}" type="checkbox" th:value="${}" th:utext="${ + <br>}" /> </form> If I add the <br> tag...

Thymeleaf automatic form generation

I'd like to create form in specific way. The form should be able to render itself based on received data, should be used like that: <form action="#" th:action="@{/blahblah}" th:formDefinition="${formDef}" th:object="${formData}"method="post"> This should render the necessary input elements in some way, fill in the data etc. Is there a way how...

Use instanceof in Thymeleaf

Is there a way to use the Java instanceof operator in Thymeleaf? Something like: <span th:if="${animal} instanceof my.project.Cat" th:text="A cat"></span> <span th:if="${animal} instanceof my.project.Dog" th:text="A dog"></span> ...

Using static href with query string in Thymeleaf

I have a html prototype of an application, this prototype is on an Apache server, I used Apache Server Side Includes to include different pages for the template layouts. Now I'm adding labels Thymeleaf that prototype for use in an application with Spring. The problem is that many of the...

not able to savedata to mysql db, in gradle project, Neither BindingResult nor plain target object for bean name 'goal' available as request attribute

I was watching tutorial and i created user-login and verifying the user, when i created addGoal, my goal was not entering in my mysql database, since i am able to login so my database connection are correct, and i am using thymeleaf with javaconfig for my annotations, please help me...

Get current date in Thymeleaf

How can I print current date (and time, eventually) from Thymeleaf? I'm trying these functions: but I can't get them work.

Use thymeleaf template for some pages and rest for some for building gradle project

I am new to this please someone tell me whether I can use Thymeleaf template for some pages and REST for some for building Gradle project? I created my login page retrieving through MySQL database using Thymeleaf template now for adding other information in my database I want to use...

HTTP Status 500 - Request processing failed;

This is my model of consent @Entity @Table(name = "consents") public class Consent extends BaseEntity { /** */ @OneToOne @JoinColumn(name = "provider_id") private Provider provider; @OneToOne @JoinColumn(name = "user_id") private User user; @OneToOne @JoinColumn(name = "friend_id") private User friend; @OneToOne @JoinColumn(name = "document_id") private Document document; @Column(name = "status") private...

Fields error and globalerrors stay empty in Thymeleaf

I am currently using the following code in a project, the issue I have is that even when there are errors in the bindingresult (bindingResult.hasErrors() is true), it's rendered false in the thymeleaf result. This makes me think the bindingResult isn't "injected" correctly. Did I do anything wrong in the...

Spring Boot & Thymeleaf with XML Templates

I have a Spring Boot application with a controller that returns a ModelAndView and Thymeleaf to render templates, where the templates live in /src/main/resources/templates/*.html This works fine, but How can I configure Spring and/or Thymeleaf to look for xml files instead of html? If it helps, I'm using Gradle with...

Not loading static Resources in Spring boot, Thymeleaf and AngularJs app

I have a Spring Boot project which has to start an angular spa. The structure of the resource folder is the following: In the templates/src folder there is the index.html file I start with the controller: @RequestMapping("/") String index() { return "src/index"; } in this way I successfully start the...

Thymeleaf error not displayed Spring 4.x

I'm actually following the Spring validation tutorial and I can make it work properly except for one thing. In fact, tlhe redirections/template return work great if I validate or don't validate the rules. The thing is that I don't even see the error message in my template. I don't know...

How to get the dynamic data from one page into another page using thyme leaf?

I want to get the information(which is dynamically generated) from one html page into another html page. I used a tag th:fragment in first html page and th:include in second html page. But i am getting only static content of first page, it is possible to get the dynamic data...

How to get support of thymeleaf for Intellij Idea 13

I am searching support of thymeleaf for Intellij Idea 13. what is the elegant procedure to add support in Intellij Idea?

How to handle form submission in HTML5 + Thymeleaf

I have to submit a form with around 30 input parameters(text, select, datepicker ). The fields are mapped to two classes. How to map each field to get the value in the controller. HTML: <form id="searchPersonForm" action="#" th:object="${person}" method="post"> <input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input> <input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input> </form>...

Resolve Thymeleaf templates in WEB-INF

I want to send email using thymeleaf to render the email message. Here is my configuration in Spring 4 applicationContext.xml: <bean id="thymeleafMailEngine" class="org.thymeleaf.TemplateEngine"> <property name="templateResolver" ref="thymeleafMailResolver" /> </bean> <bean id="thymeleafMailResolver" class="org.thymeleaf.templateresolver.FileTemplateResolver"> <property name="templateMode" value="XHTML" /> <property name="prefix" value="src/main/webapp/WEB-INF/templates/" /> <property...

Dynamic fields thymeleaf list iteration

I'm getting a really weird error ! while iterating on list thymeleaf identified index as a property of my bean and not an index value ! <div th:each="phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field col s4" > <input th:field="*{phones[__${phoneStat.index}__].number}" th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text" class="validate" /> <label...

Spring MVC - form handling with object request params

Assume I have the following entities in my application: public class Payment { private Long id; private Service service; private User user; private BigDecimal amount; } public cass Service { private Long id; private String name; private BigDecimal minAmount; private BigDecimal maxAmount; } public class User { private Long id;...

Conditional text in ThymeLeaf : how to do it in plain text?

I understand how th:if works for html templates, but I don't find any clue on how to do it when you expect plain text (use case : plain text e-mail templating). So far I tried : <html xmlns:th="" th:inline="text" th:remove="tag"> Dear [[${contact.firstname}]] [[${contact.lastname}]], An alert was triggered at location: [[${account.address}]]...

Thymeleaf Double Reference to CSS

In many Thymeleaf examples (such as a Spring Boot Thymeleaf example, links to stylesheets are referenced twice in the link where the first reference uses the Thymeleaf th:ref and the second uses a standard href: <link rel="stylesheet" th:href="@/css/bootstrap.min.css}" href="../../css/bootstrap.min.css" /> Removing the href="../../css/bootstrap.min.css" does not seem to break anything. Is...

Thymeleaf: Use #dates.format() function for format date with internatinalization.

I am using Thymeleaf #dates.format() function for format date in view layer. I create one internatinalization properties file for pic the date format. i am using #dates.format(date, (#{app.dateformat})) function like this. but Thymeleaf throw an parse exception. Because thymeleaf now resolve the app.dateformat. How i use date format internationalization way...

How to use SpringTemplateEngine when using Spring Boot

I am using Thymeleaf SpringTemplateEngine to create a HTML e-mail on my Spring application. When I was using pure Spring MVC everything was perfect. Now with Spring Boot the class can't find my .html template. I think the problem is with ServletContext that is not returning the right path, but...

Thymeleaf: How to exclude outer tag when using th:each?

The Thymeleaf 2.1.4 official doc demonstrates the for each usage as below: <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'"> <td th:text="${}">Onions</td> <td th:text="${prod.price}">2.41</td> ... </tr> It generates one <tr> in each iteration, which is perfect fit in this situation. However in my case I don't need the outer tag (here, <tr>)....

I want to do something like <option value="value1,value2"> in thymleaf. I know for one value all i have to do is <option th:value="${value1}"> How to pass two values in select option in Thyemleaf....

How to display list of map values in HTML5 using thymeleaf

I need to display values in map in HTML using thymeleaf. Here is my java code List<Object> searchResultsList = searchService.searchPerson(id); List<String> list = new ArrayList<String>(); Map<Integer, List<String>> mapResults = new HashMap<Integer, List<String>>(); for (int i = 0,; i < searchResultsList.size(); i++) { list.add(0, row[0].toString()); list.add(1, row[1].toString()); list.add(2, row[2].toString()); mapResults.put(i, list);...

the array list from database is not displaying on browser but i can see it on the eclipse console

this is my controller @RequestMapping(value = "/users/{userId}/providers/{providerId}/check", method = RequestMethod.GET) public String initNewDocumentForm121(@PathVariable("userId") int userId,@PathVariable("providerId") int providerId, Model model) { List<JdbcDocument> documents = this.clinicService.findByProviderIdAndUserId(providerId, userId); System.out.print("findByProviderIdAndUserId"); System.out.print(documents); return "users/myproviders"; } I can see documents array on the eclipse console but not on browser. <select...

How to include with thymeleaf

I am using spring boot with thymeleaf. This is my project structure: And this is my App start class: @EnableAutoConfiguration @Configuration @ComponentScan public class App { public static void main(String[] args) {; } } I have this on my home.leaf.html: <p th:text = "#{username}"></p> But when I run this...

Thymeleaf + Spring: get rid of the default element id

Is there any way to suppress auto-generating ID attribute for elements while using th:field in Thymeleaf (2.1.4.RELEASE)? For example, given code: <input type="text" th:field="*{year}" /> will produce the following HTML: <input type="text" id="year" name="year" value="" /> What I want to achieve is (no id attribute): <input type="text" name="year" value="" />...

Thymeleaf: check if a variable is defined

How can I check if a variable is defined in Thymeleaf? Something like this in Javascript: if (typeof variable !== 'undefined') { } or this in PHP: if (isset($var)) { } Is there an equivalent in Thymeleaf?...

Id is not set in form object Thymeleaf Spring

I am trying to edit a previous filled form using Thymeleaf and Spring Server. This is the "previous form" which is POST in a Spring Server which saves correctly. <form id="addingnovoatributo" action="#" th:action="@{'/addingoextraattributes/'}" th:object="${new_point_attributes}" method="post"> <p>Id do Attribute: <input type="text" th:field="*{id}" readonly="readonly"/></p> <p>Id do Point: <input type="text" th:value="${}" id="pointid" name="pointid"...

Which bean shall I put in the model?

I have a controller that receives data from different forms. I manually bind this data to the corresponding Java object. I obtain the correct class using an additional path variable. I also validate the submitted data. Now I want to see the errors in my Thymeleaf template, but I don't...

sec:authorize doesn't work

Recently I have started a new project and decided to use the latest versions of spring, spring security and thymeleaf I have included these packets def springVersion = '4.1.6.RELEASE' def securityVersion = '4.0.1.RELEASE' def thymeleafVersion = '2.1.2.RELEASE' compile "org.springframework:spring-core:$springVersion" compile "org.springframework:spring-webmvc:$springVersion" compile "$securityVersion" compile "$securityVersion" compile...