Utilizing Thymeleaf With JavaScript in Spring Boot: A Comprehensive Guide

Within my Spring Boot project, I am attempting to utilize Thymeleaf for injecting data into a JavaScript file that undergoes preprocessing with babel via WebPack.

The Thymeleaf setup is outlined as follows:

@Bean
public SpringTemplateEngine templateEngine(MessageSource webTemplateMessageSource) {
    // Code snippet here
}

@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
    // Code snippet here
}

public SpringResourceTemplateResolver htmlTemplateResolver() {
    // Code snippet here
}

public SpringResourceTemplateResolver javaScriptTemplateResolver() {
    // Code snippet here
}

An example of an HTML page structure is provided below:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Secrets</title>
</head>

<body>

    <button id="secret-button">Tell me the secret</button>

    <script th:src="@{/js/scripts.js}"></script>
</body>
</html>

In this scenario, I aim to populate the secretMessage variable in a JavaScript file using ThymeLeaf with the following message property:

const secretMessage = [[#{secret}]];
document.querySelector("#secret-button").addEventListener("click", ev => {
    alert(secretMessage);
});

The message content resides within a dedicated message source as shown:

secret=Elvis 'still alive

Lastly, the relevant segment of the WebPack configuration is detailed below:

let babelConfig = {
    test: /\.js$/i,
    exclude: /(node_modules)/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-react', '@babel/preset-env']
        }
    }
};

Despite the efforts put into this setup, there are issues encountered. Specifically, babel throws errors concerning the line:

const secretMessage = [[#{secret}]];
within the JavaScript file.

Furthermore, uncertainties remain as to whether additional configurations are necessary. Resources or examples demonstrating proper implementation of Thymeleaf in conjunction with Spring Boot for JavaScript parsing are sought after for guidance and assistance.

Edit

For experimentation purposes, attempts were made to process the JavaScript file without relying on webpack bundling. Despite placing the JS file directly within the static/build/js directory, it fails to be processed by the Thymeleaf engine when requested by the HTML page.


Hence, aside from the webpack preprocessing challenge, an obstacle persists in terms of Thymeleaf processing. Limited resources and tutorials addressing this hurdle have led to a trial-and-error predicament, unsure of the feasibility of the desired outcome.

Edit 2:

Deleted

Edit 3:

Following suggestions from M. Deinum, a `ViewController` was implemented by overriding `addViewControllers` within the `WebMvcConfigurer` interface:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("*.js");
}

In addition, to address lingering issues persisting despite these changes, the

templateResolver.setPrefix("/js/");
line within the relevant javaScriptTemplateResolver was removed in hopes of eliminating any potential limitations. Despite these adjustments, Thymeleaf still does not process the JavaScript file as intended.

Answer №1

To properly configure your template engine, make sure to include both resolvers:

templateEngine.addTemplateResolver(htmlTemplateResolver());
templateEngine.addTemplateResolver(javaScriptTemplateResolver());

If you are utilizing Thymeleaf, don't forget to create a controller with a mapping for your JavaScript file:

@GetMapping("/js/index.js")
public String indexJs() {
  return "index";
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

Implement a select element with an onchange event that triggers an AJAX

As a newcomer to Javascript, I've been struggling to find a solution to my issue. The goal is to add an additional select option when the previous select option is changed. I attempted to implement the code below, but it's not functioning correct ...

Accessing Facebook through the React create app login

I recently developed a React Webapp using the create-react-app module. My current challenge involves integrating Facebook login, but I'm encountering some obstacles. I am unsure about where to incorporate the Facebook JavaScript SDK asynchronously to ...

Formulate a targeted search request according to the selected radio button option

I'm working on a form that looks like this: <form> <input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/> <button type="submit" id="f ...

Can context be passed into a component that is created using ReactDOM.render()?

TL;DR In this given example code: ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode); Can one manually provide React context to the instance of MyComponent? This might seem like an unusual question considering React's usual behavio ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

The module script failed to load due to an unexpected response from the server, which was MIME type of text/jsx instead of a javascript module script

I have recently set up an express server and created an API, as well as installed React using Vite for my frontend. However, when I attempt to connect or load my main HTML file to the server, an error is displayed in the console. This is all new to me as I ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Harmonizing database with AJAX-powered webpage

When using ajax calls to update data on a web page, what is the most effective way to synchronize changes with a database? For example, if I have a comment form that needs to work asynchronously. I write JS code to submit the form data to the database, but ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Troubles with AJAX comment system validation issues

Having created a webpage that displays articles with a textarea under each article for user comments, I implemented AJAX successfully. The validation also works fine - if the textarea is empty, it will display an error and not submit the comment. However, ...

Having trouble transferring ASP server control value to a Javascript function

Currently working with ASP.NET 2.0. My Entry Form contains various ASP.NET Server Controls, such as TextBoxes. I want to pass the value of a TextBox on the onBlur event. Here is an example of a TextBox code: <asp:TextBox ID="txtTotalTw" Width="80px" r ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

Difficulty encountered while implementing mouseover event listener for an SVG component

I'm having trouble triggering an event for an svg element. Here's the link to my jsfiddle example: https://jsfiddle.net/r1ahq5sa/ Here's the HTML code: <div class="row"> <div class="col-md-8"> <svg class="video-nav-bar ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Error encountered while attempting to define a method in a class component in React.js

Can you tell me if these two code snippets are equivalent? async onSearchSubmit(term) { const response = await axios.get('https://api.somewebsite.com/search/photos', { params: {query: term}, headers:{ ...

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...