thymeleaf , Render view fragments directly, using thymeleaf


Render view fragments directly, using thymeleaf

Question:

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();
resolver.setTemplateMode("HTML5");
resolver.setPrefix("/WEB-INF/templates/");
resolver.setCharacterEncoding("UTF-8");
resolver.setSuffix(".html");
resolver.setCacheable(false);
engine = new TemplateEngine();
engine.setTemplateResolver(resolver);

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

http://www.thymeleaf.org/whatsnew21.html#spfrag

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_' + field.id}" th:class="${field.type + ' row outter'}">
            <input type='hidden' th:id="${'field_' + field.id + '_id'}" id='field_100_id' value='100' />
            <input type='hidden' th:id="${'field_' + field.id + '_type'}" id='field_100_type' th:value='${field.type}' />
            <input type='hidden' th:id="${'field_' + field.id + '_order'}" id='field_100_order' th:value='${field.obj.order}' />
            <input type='hidden' th:id="${'field_' + field.id + '_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>
        </div>
    </div>
</div>

Answer:

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


Related:


Thymeleaf compare #locale expression object with string


conditional,locale,thymeleaf,spring-el
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...

The thymeleaf template now showing inner element from anchor tag


spring,thymeleaf
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...

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


rest,spring-mvc,gradle,spring-security,thymeleaf
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...

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


java,spring-mvc,thymeleaf
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...

Thymeleaf: th:each error


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

Resolve Thymeleaf templates in WEB-INF


java,spring,spring-mvc,thymeleaf
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...

Thymeleaf - Appending
to input tag


html,thymeleaf
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="${brand.name}" th:utext="${brand.name + <br>}" /> </form> If I add the <br> tag...

Spring Form Validation with Two Objects


java,spring,validation,thymeleaf
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...

How to use SpringTemplateEngine when using Spring Boot


java,javamail,spring-boot,thymeleaf
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...

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


spring-mvc,spring-boot,thymeleaf
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...

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


if-statement,thymeleaf,plaintext
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="http://www.thymeleaf.org" th:inline="text" th:remove="tag"> Dear [[${contact.firstname}]] [[${contact.lastname}]], An alert was triggered at location: [[${account.address}]]...

Using static href with query string in Thymeleaf


spring,apache,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...

How to call url which depends on input in Thymeleaf?


html,spring-mvc,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....

HTTP Status 500 - Request processing failed;


spring-mvc,thymeleaf
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...

sec:authorize doesn't work


spring-mvc,spring-security,thymeleaf
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 "org.springframework.security:spring-security-web:$securityVersion" compile "org.springframework.security:spring-security-config:$securityVersion" compile...

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


spring,spring-boot,thymeleaf
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...

How to display list of map values in HTML5 using thymeleaf


html5,list,dictionary,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);...

Spring MVC - form handling with object request params


java,spring,spring-mvc,web,thymeleaf
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;...

Thymeleaf: check if a variable is defined


java,spring,spring-mvc,spring-boot,thymeleaf
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?...

can't reference iteration variable in Thymeleaf


java,spring,thymeleaf
I try to iterate a list of items using th:each, <div class="row" th:each="item : *{items}"> <input type="text" th:field="item.name"/> </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...

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


mysql,spring-security,spring-boot,thymeleaf
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...

Thymeleaf + Spring: get rid of the default element id


spring,spring-mvc,thymeleaf
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="" />...

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


java,spring,spring-mvc,spring-boot,thymeleaf
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


jquery,html5,thymeleaf,modelattribute
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...

Thymeleaf error not displayed Spring 4.x


java,spring,spring-mvc,thymeleaf
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...

Id is not set in form object Thymeleaf Spring


html,spring,forms,jpa,thymeleaf
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="${point.id}" id="pointid" name="pointid"...

Thymeleaf Double Reference to CSS


css,thymeleaf
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...

How to handle form submission in HTML5 + Thymeleaf


html5,forms,spring-boot,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>...

Fields error and globalerrors stay empty in Thymeleaf


spring,spring-mvc,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...


thymeleaf
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....

Thymeleaf HTML5 long variable issue


html5,spring-boot,long-integer,thymeleaf
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...

Spring Boot & Thymeleaf with XML Templates


spring-mvc,configuration,spring-boot,thymeleaf
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...

How can i use for loop in javascript using thymeleaf?


javascript,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="http://www.thymeleaf.org"> <head> <title>Getting Started: Handing Form Submission</title> <meta http-equiv="Content-Type"...

Spring Multipart File Upload


spring,spring-mvc,multipartform-data,thymeleaf
I'm trying to upload a multipart file using Spring mvc, tomcat, Tyhmleaf but can't get it work. java.lang.NullPointerException com.cars.actions.controller.brand.BrandController.persist2(BrandController.java:75) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:483) My controller: @RequestMapping(value =...

Get current date in Thymeleaf


java,spring,date,thymeleaf
How can I print current date (and time, eventually) from Thymeleaf? I'm trying these functions: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#dates but I can't get them work.

Which bean shall I put in the model?


java,spring,spring-mvc,thymeleaf
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...

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


java,spring-mvc,thymeleaf
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....

Dandelion datatables exporting to Excel - missing export links


spring,datatables,apache-poi,thymeleaf,dandelion
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 include message.properties with thymeleaf


java,spring,spring-boot,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) { SpringApplication.run(App.class); } } I have this on my home.leaf.html: <p th:text = "#{username}"></p> But when I run this...

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


spring-mvc,thymeleaf
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...

Dynamic fields thymeleaf list iteration


spring,spring-mvc,spring-boot,thymeleaf
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...

How to get support of thymeleaf for Intellij Idea 13


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

Form parameter is null with Thymeleaf and Spring MVC


java,spring,spring-mvc,model-view-controller,thymeleaf
i'm having a problem with Thymeleaf and Spring MVC. I'm following a tutorial from spring.io website http://spring.io/guides/gs/handling-form-submission/ 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...

Escaping '&' character in thymeleaf


hyperlink,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 Portlet + Thymeleaf: Bind object for ActionMapping


spring,spring-mvc,portlet,thymeleaf
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...

Foreach without first row


spring,thymeleaf
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: How to exclude outer tag when using th:each?


java,template-engine,thymeleaf
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="${prod.name}">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>)....

Use instanceof in Thymeleaf


java,spring,spring-boot,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> ...

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


spring-mvc,thymeleaf
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...

Thymeleaf automatic form generation


html,forms,thymeleaf
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...