Generate JavaScript with Thymeleaf

Overview

It's a memorandum because I happened to touch JavaScript with Thymeleaf.

environment

OpenJDK 11.0.2 SpringBoot 2.3.4 Thymeleaf 3.0.11

Template Engine settings

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

Template file creation

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.

Controller settings

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.

result

Start the app and try to access /app.js. Screen Shot 2020-10-16 at 6.36.38.png

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

Generate JavaScript with Thymeleaf
Generate barcode with Spring Boot
Use Thymeleaf with Azure Functions
Programmably generate Logger with logback
Handle dates with Javascript (moment.js)
Draw screen with Thymeleaf in SpringBoot
Implement text link with Springboot + Thymeleaf
Output JavaScript in Thymeleaf 3 without escaping
Authentication / authorization with Spring Security & Thymeleaf
Timeless search with Rails + JavaScript (jQuery)
Convert C language to JavaScript with Emscripten
How to switch thumbnail images with JavaScript
Let's try WebSocket with Java and javascript!
Hello world with Java template engine Thymeleaf
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Implement paging function with Spring Boot + Thymeleaf
Run WEB application with Spring Boot + Thymeleaf