I am using spring boot 2.2.4 and using the thymealeaf text templates for the first time with spring boot.
Belowis the texttemplate I am trying to use and I am trying to print the current date and time but it is printing blank on screen.
CurrentDate:[#th:block th:utext="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}"/]
I have added the Java8 date time dependency in pom.xml and also added the java8dialect in the template resolver bean.
pom.xml
--------
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
ThymeleafConfig.java
----------------------
#Configuration
public class ThymeleafConfig {
#Bean(name = "textTemplateEngine")
public TemplateEngine textTemplateEngine() {
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.addTemplateResolver(textTemplateResolver());
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}
private ITemplateResolver textTemplateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/text/");
templateResolver.setSuffix(".txt");
templateResolver.setTemplateMode(TemplateMode.TEXT /* https://github.com/thymeleaf/thymeleaf/issues/395 */);
templateResolver.setCharacterEncoding("UTF8");
templateResolver.setCheckExistence(true);
templateResolver.setCacheable(false);
return templateResolver;
}
}
Can anybody please tell me what am I doing wrong in thymealeaf text template that it is not printing the date?
You can use a Thymeleaf utility method to print various date and time variants.
For example:
<div th:text="${#dates.createNow()}"></div>
I think that may answer your specific question.
However, I suspect your question is more about the wider topic of binding Java objects to Thymeleaf templates in Spring - and I have not used Spring with Thymeleaf.
Related
I have migrated existing project Swagger to Swagger3 using dependency springdoc-openapi-ui 1.6.8 version .
Getting issue while added the global header parameter in Swagger config file, it was not showing at Swagger dashboard
Please advised me if any issue in mentioned code.
Code:
**
#Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.components(new Components()
.addSecuritySchemes("basicScheme",
new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
.addParameters("myHeader1",
new Parameter().in("header").schema(new StringSchema()).name("myHeader1"))
.addHeaders("myHeader2",
new Header().description("myHeader2 header").schema(new StringSchema())))
.info(new Info().title("eWallet API Sandbox").description("eWallet API Sandbox").version("v1.0")
.contact(new Contact().name("WOW Finstack").url("https://wowdigital.ai/")
.email("info#wowdigital.ai"))
.termsOfService("WOW Finstack").license(new License().name("License").url("#")));
//
};
**
Dependency :
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.8</version>
</dependency>
I recently upgraded to springdoc-openapi-ui and struggled a bit to make global headers work on Spring boot 2.6.3.
I managed to make global header work if it's defined as a Parameter (using new Parameter()...) but I did not make it work when defined as a Header (using new Header()...)
I guess that you already defined a GroupedOpenApi Spring Bean. So what you have to do is add a OpenApiCustomiser to this GroupedOpenApi, see addOpenApiCustomiser(globalHeaderCustomizer()) below:
#Bean
public GroupedOpenApi publicGroup() {
return GroupedOpenApi.builder()
.packagesToScan("com.my.package")
.pathsToMatch("/**")
.group("public")
.addOpenApiCustomiser(globalHeaderCustomizer()) // --> you need this!
.build();
}
where globalHeaderCustomizer() is:
private OpenApiCustomiser globalHeaderCustomizer() {
return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
.forEach(operation -> operation.addParametersItem(
new HeaderParameter().$ref("#/components/parameters/myHeader1")));
}
I think that should fix your issue.
Hello I'm using spring boot 2.4.x and I want to use thymeleaf as my template engine.
I've added the thymeleaf starter and I've the following test
#Test
void name() {
StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(stringTemplateResolver);
Context ctx = new Context();
ctx.setVariable("franco", "prova");
String processedTemplate = templateEngine.process("<html>${franco}</html>", ctx);
Assertions.assertThat(processedTemplate).isEqualTo("<html>prova</html>");
}
but the templateEngine is not substituting the variable and the value of the processedTemplate variable is the same as the input string.
What's my fault?
Thank you
Thymeleaf won't process variables directly in HTML. You either have to use the text inlining syntax:
<html>[[${franco}]]</html>
or do it the standard way (which is to use attributes prefixed with th:) like this:
<html th:text="${franco}" />
or
<html><span th:text="${franco}" /></html>
(Also, as a side note StringTemplateResolver is the default resolver, so you don't have to configure it. Your complete code can look like this.)
#Test
void name() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
Context ctx = new Context();
ctx.setVariable("franco", "prova");
String processedTemplate = templateEngine.process("<html>[[${franco}]]</html>", ctx);
Assertions.assertThat(processedTemplate).isEqualTo("<html>prova</html>");
}
I have a project and I need users to be able to add content without recompiling the application or using a database. What I want to achieve is for spring to look in a directory called modules / for all folders containing a thymeleaf html file and render them according to their name from a single controller. it's possible?.
I have looked for information on how to render a fragment of thymeleaf from java in real time but I have not found any information.
with the help of this, we can navigate our template path as per our desired location.
#Bean
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver().setPrefix("file://C:/test/");// this is
templateResolver.setCacheable(false);
templateResolver.setTemplateMode("HTML5");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(1);
return templateResolver;
}
This is also a solution.
use this in application properties file
project.base-dir=file:///E:/Work/WorkSpace/RND WorkSpace/sk
spring.thymeleaf.prefix=${project.base-dir}/src/main/resources/templates/
I would like to serve internationalized html pages with my Spring Boot application and I am using Thymeleaf with messages_XX.properties for i18n. I would prefer accessing these as http://localhost:8080/some/path/test.html and having them in e.g. /src/main/resources/html but I am unable to configure Spring Boot to process a page using thymeleaf by default.
As a temporary workaround I have a controller with
#RequestMapping(value="**/*.html")
public String serve(HttpServletRequest req) {
String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);
res = res.substring(1);
return res;
}
This works for me now: http://localhost:8080/some/path/file.html processes and serves src/templates/some/path/file.html but can I just configure somewhere that src/resources/html are to be PROCESSED by thymeleaf and then served?
So far I have tried
spring.thymeleaf.prefix=classpath:/html/
in application.properties but it does not seemed to work for me.
Environment:
spring-boot-starter-2.0.0.RELEASE,
spring-webmvc-5.0.4.RELEASE,
thymeleaf-spring5-3.0.9.RELEASE
Since you are cutting of the .html in:
String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);
You should probably set
spring.thymeleaf.suffix=.html
Or with Configuration:
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:/html/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}
im getting this error i searched on the same issues like mine on stack and i have foudn that i shouldn t put .html when calling it but im getting the same error :
`Caused by: org.thymeleaf.exceptions.TemplateInputException: Error resolving template "orderConfirmationEmailTemplate", template might not exist or might not be accessible by any of the configured Template Resolver`s
my mail constructor :
#Component
public class MailConstructor {
#Autowired
private Environment env;
#Autowired
private TemplateEngine templateEngine;
public SimpleMailMessage constructNewUserEmail(User user, String password) {
String message="\nPlease use the following credentials to log in and edit your personal information including your own password."
+ "\nUsername:"+user.getUsername()+"\nPassword:"+password;
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(user.getEmail());
email.setSubject("Le's Bookstore - New User");
email.setText(message);
email.setFrom(env.getProperty("support.email"));
return email;
}
public MimeMessagePreparator constructOrderConfirmationEmail (User user, Order order, Locale locale) {
Context context = new Context();
context.setVariable("order", order);
context.setVariable("user", user);
context.setVariable("cartItemList", order.getCartItemList());
String text = templateEngine.process("orderConfirmationEmailTemplate.html", context);
MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper email = new MimeMessageHelper(mimeMessage);
email.setTo(user.getEmail());
email.setSubject("Order Confirmation - "+order.getId());
email.setText(text,true);
email.setFrom(new InternetAddress("alaaeddinezammel1993#gmail.com"));
}
};
return messagePreparator;
}
and im calling it from rest service:
mailSender.send(mailConstructor.constructOrderConfirmationEmail(user, order, Locale.ENGLISH));
shoppingCartService.clearShoppingCart(shoppingCart);
and im putting the file .html under package in the project
In your question, the TemplateEngine is auto wired so I cannot see how it is configured but it in order to discover your template from the location com.bookstore.domain.security.templates the configuration should look something like this:
#Bean
public TemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver());
return templateEngine;
}
private ITemplateResolver templateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix(“/com/bookstore/domain/security/templates“);
templateResolver.setSuffix(".html");
…
return templateResolver;
}
In this code I am configuring the TemplateEngine in code, perhaps you are using XML. Regardless of how you are configuring the TemplateEngine, you are clearly using Spring to do so (since you inject it into your MailConstructor), the key point here is that regardless of how you configure it you need to tell it where to find your template and the way to do that is to invoke the ITemplateResolver's setPrefix() method.
Plenty more details in the article titled Sending email in Spring with Thymeleaf in the Thymeleaf docs.
actually with my configuration putted in my question i just put the .html file under file called templates under resources and it works the mail is sent , spring boot is apparently auto configured with this path without configuring the
templateResolver