How to Load templates from external folder using Thymeleaf - spring

I'm working with spring boot and thymeleaf to generate Documents from html templates.
As the templates continuously changes, i want ti to load templates from an external just to add or remove templates from there instead of redeploy the application.
As a POC, when using /resources folder works fine.
This is the error:
Error resolving template "voucher", the template might not exist or might
not be accessible by any of the configured Template Resolvers
This is the context:
applycation.yml
spring:
thymeleaf:
prefix: file:///${PARAMETERS_DIRECTORY_TEMPLATES:/home/app/templates/}
check-template-location: true
suffix=: .html
mode: HTML
encoding: UTF-8
This is my Method:
Where templateName is the template filename and parameters is just a map who has the values to be replaced by the engine.
#Override
public String buildHtmlFromTemplate(String templateName, Map<String, String> parameters) {
TemplateEngine templateEngine = new TemplateEngine();
FileTemplateResolver templateResolver = new FileTemplateResolver ();
templateResolver.setOrder(templateEngine.getTemplateResolvers().size());
templateResolver.setCacheable(false);
templateResolver.setCheckExistence(true);
templateEngine.setTemplateResolver(templateResolver);
return templateEngine.process(templateName, this.resolveHtmlTemplateAttributesContext(parameters));
}
NOTE:
I removed tha applycation yml thymeleaf configs and implemented next code but the error persists.
#Override
public String buildHtmlFromTemplate(String templateName, Map<String, String> parameters) {
TemplateEngine templateEngine = new TemplateEngine();
FileTemplateResolver templateResolver = new FileTemplateResolver ();
templateResolver.setPrefix("/home/skeeter/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
templateResolver.setOrder(templateEngine.getTemplateResolvers().size());
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
templateResolver.setCheckExistence(true);
templateEngine.setTemplateResolver(templateResolver);
return templateEngine.process(templateName, this.resolveHtmlTemplateAttributesContext(parameters));
}

0
Curiously, the issue was solved using this code and the /usr/app/templates created with sudo.
I think it was only a permissions issue
.....
#Value("${parameters.directory.templates}")
private String templatesDirectory;
.....
#Override
public String buildHtmlFromTemplate(String templateName, Map<String, String> parameters) {
TemplateEngine templateEngine = new TemplateEngine();
FileTemplateResolver templateResolver = new FileTemplateResolver ();
templateResolver.setPrefix(templatesDirectory);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
templateResolver.setOrder(templateEngine.getTemplateResolvers().size());
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
templateResolver.setCheckExistence(true);
templateEngine.setTemplateResolver(templateResolver);
return templateEngine.process(templateName, this.resolveHtmlTemplateAttributesContext(parameters));
}

In my case I was using the ClassLoaderTemplateResolver, but after I changed it to FileTemplateResolver I can use the absolute path and it works fine.
Double check that you have read permissions in the directory where you have the templates.

Related

Spring Boot, Thymeleaf and strings

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>");
}

Spring Boot: process a html file with thymeleaf without controller

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;
}

spring boot calling thymeleaf template failed

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

Thymeleaf : template might not exist or might not be accessible by any of the configured Template Resolvers

I have this code:
private static final String EMAIL_INLINEIMAGE_TEMPLATE_NAME = "templateemail.html";
#Bean
public TemplateEngine emailTemplateEngine() {
templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(this.htmlTemplateResolver());
)
templateEngine.setTemplateEngineMessageSource(this.messageSource);
return templateEngine;
}
private static ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(Integer.valueOf(0));
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateResolver.DEFAULT_TEMPLATE_MODE);
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
return templateResolver;
}
public void sendEmail(String emailAddress, String title, String body, Locale local, String image) {
if (Boolean.parseBoolean(isEmailServiceActivated)) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage);
try {
mailMsg.setFrom(EMAIL_USERNAME);
mailMsg.setTo(emailAddress);
mailMsg.setSubject(title);
// Prepare the evaluation context
ctx.setLocale(local);
ctx.setVariable("imageHeaderResourceName", HEADER_LOGO_IMAGE);
ctx.setVariable("body", body);
ctx.setVariable("imageResourceName", image);
final String htmlContent = this.templateEngine.process(new ClassPathResource(EMAIL_INLINEIMAGE_TEMPLATE_NAME).getPath(), ctx);
mailMsg.setText(htmlContent, true );
mailMsg.addInline(HEADER_LOGO_IMAGE, new ClassPathResource(HEADER_LOGO_IMAGE ) , PNG_MIME);
mailMsg.addInline(image, new ClassPathResource(image) , PNG_MIME);
} catch (MessagingException e) {
e.printStackTrace();
}
mailSender.send(mimeMessage);
}
}
I have templateemail.html file under /templates/ directory. when I launch the sending email method I have this exception :
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "templateemail.html", template might not exist or might not be accessible by any of the configured Template Resolvers
I dont know if it's because the templateEngine can't find my file (I try even with tomcat absolute path and /bin directory but no way ) or I haven't configure the right Template Resolver.
Thank you very much for your help. I
It work now by deleting ".html" in the name of template (the file has the html extension)
private static final String EMAIL_INLINEIMAGE_TEMPLATE_NAME = "templateemail"
Note the non-cross-platform behavior that can occure: on Windows the CamelCase.html template was resolved, but not on Ubuntu linux! There I had to rename it to camelcase.html, all chars in lower case
I had the same issue recently. My problem was that my template had references to other templates that started with /.
For example:
<html ... th:include="/internal/layout-normal :: page"> <-- failed
<html ... th:include="internal/layout-normal :: page"> <-- worked
Both variants worked without problems when I run the application from IntelliJ. However, when packaged and run via java -jar the first line failed.
Removing the / solved the problem for me
Thymeleaf picks up the html files from resources/templates path by using the name of html file.
Hence in this case just removing .html extension from the filename would work!

Programmatically resolve Thymeleaf templates

I'm trying to render XML/JSON using Thymeleaf templates. I don't want to render a view using the template name, just want to resolve the template as shown below. Trouble is all I get back is the template name, not it's content.
Set up:
#Bean
SpringResourceTemplateResolver xmlTemplateResolver(ApplicationContext appCtx) {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(appCtx);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".xml");
templateResolver.setTemplateMode(XML);
templateResolver.setCharacterEncoding(UTF_8.name());
templateResolver.setCacheable(false);
return templateResolver;
}
#Bean
SpringTemplateEngine templateEngine(ApplicationContext appCtx) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(xmlTemplateResolver(appCtx));
return templateEngine;
}
Template (src/main/resources/templates/breakfast-menu.xml):
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>${item['name']}</name>
<price>${item['price']}</price>
<description>${item['description']}</description>
<calories>${item['calories']}</calories>
</food>
</breakfast_menu>
Usage:
#Autowired
SpringTemplateEngine templateEngine;
someMethod() {
Context context = new Context();
context.setVariable("item", item);
item.put("name", "Waffle");
String content = templateEngine.process("breakfast-menu", context);
// content == "breakfast-menu". WTH?
}
Using Thymeleaf 3.0.0.BETA01.
I solved this issue with help from the Thymeleaf user forum. For reasons unbeknownst to me, templateEngine.addTemplateResolver doesn't work but templateEngine.setTemplateResolver does. The templates for XML and JSON output are shown below:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name th:text="${item['name']}"></name>
<price th:text="${item['price']}"></price>
<description th:text="${item['description']}"></description>
<calories th:text="${item['calories']}"></calories>
</food>
</breakfast_menu>
JSON:
{
"food": {
"name": "[[${item['name']}]]",
"price": "[[${item['price']}]]",
"description": "[[${item['description']}]]",
"calories": "[[${item['calories']}]]"
}
}
Just for the sake of completeness is here some code to resolve a Thymeleaf template with plain-Thymeleaf without Spring.
This is for HTML but you can adapt it to some other template mode by setting another parameter for the setTemplateMode call:
Maven dependency:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
Java class:
import java.util.Map;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;
public class ThymeleafResolver {
public static String resolveHTMLWithThymeleaf(String html, Map<String, Object> variables) {
TemplateEngine templateEngine = new TemplateEngine();
StringTemplateResolver templateResolver = new StringTemplateResolver();
templateResolver.setTemplateMode(TemplateMode.HTML);
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context();
context.setVariables(variables);
return templateEngine.process(html, context);
}
}
Testcase Java code:
Map<String, Object> variables = new HashMap<>();
variables.put("mytext", "Hello World");
String result = ThymeleafInterpreter.interpretHTMLWithThymeleaf("<html><body><span th:text=\"${mytext}\"></span></body></html>", variables);
Assert.assertEquals("<html><body><span>Hello World</span></body></html>", result);

Resources