It's a memorandum because I happened to touch JavaScript with Thymeleaf.
OpenJDK 11.0.2 SpringBoot 2.3.4 Thymeleaf 3.0.11
AppConfig.java
@Configuration
public class AppConfig {
@Bean
public TemplateEngine scriptTemplateEngine() {
final TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setDialect(new SpringStandardDialect());
templateEngine.setTemplateResolver(scriptTemplateResolver());
return templateEngine;
}
private ITemplateResolver scriptTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/scripts/");
templateResolver.setSuffix(".js");
templateResolver.setTemplateMode(TemplateMode.JAVASCRIPT);
templateResolver.setCharacterEncoding("utf-8");
templateResolver.setCacheable(false);
templateResolver.setCheckExistence(true);
return templateResolver;
}
}
resources/templates/scripts/sample.js
'use strict';
(() => {
const rawData = [# th:text="${rawData}" /];
const jsonData = [# th:text="${jsonData}" /];
console.log(rawData);
console.log(jsonData);
})();
Pass two variables.
SampleController.java
@Controller
@RequiredArgsConstructor
public class SampleController {
private final TemplateEngine scriptTemplateEngine;
private final ObjectMapper objectMapper;
@GetMapping(value = "/app.js", produces = "text/javascript")
@ResponseBody
public String sample() throws JsonProcessingException {
String path = "sample";
Map<String, Object> map = new HashMap<>();
map.put("id", 1);
map.put("name", "Takeshi");
List<Map<String, Object>> list = new ArrayList<>();
list.add(map);
Context ctx = new Context();
ctx.setVariable("rawData", list);
ctx.setVariable("jsonData", objectMapper.writeValueAsString(list));
return scriptTemplateEngine.process(path, ctx);
}
}
Create the data with sample (), and pass the data itself and the data converted to JSON string with the same name as the variable name to the process method and return it. Note that if you add a thymeleaf-spring5 dependency, a bean for automatically returning a View will be created with the name templateEngine. When using the bean created in the configuration file, it is necessary to DI with the bean name used at that time.
Start the app and try to access /app.js.
I was able to create it safely. I don't think there are many opportunities to create JS dynamically, but for reference.
It seems that Thymeleaf hasn't been updated for about two years. Did development stop?
Recommended Posts