简体   繁体   中英

How to use a Thymeleaf message from message.properties inside of my javascript file?

Pretty straightforward question. I was wondering if there were any capabilities to allow me taking a message from my message.properties file and insert that into my javascript file like I would with an html file.

For instance, I have aa title on my home page listed as:

<h1 th:text="#{home.screen.title}"></h1>

Where home.screen.title = Home

In my javascript file I have a function that accepts two strings and I'd like to have those as these thymeleaf messages. So, it would sort of be like:

statusCode: {
       404: function() {
           PISAlert(th:text="#{encounter.error.notFound}", th:text="#{encounter.error.notFound.content}");
       }
   }

Where encounter.error.notFound.title = Encountered a 404 error. and encounter.error.notFound.content = Object not found

There are two ways I can see to achieve this - but they both make some assumptions about the wider context of your question. If those assumptions are wrong, then these aproaches may not work.

Option 1 of 2

Pass Thymeleaf-provided parameters to your function (which is in a separate JS file) from the Thymeleaf template.

This simplifies the solution. The assumption (which diverges from your question) is that you only call this function from within Thymeleaf templates - and therefore you do not need to render the message strings directly into the JS code (in its separate JS file).

Example:

I use the following message file - jsdemo.properties:

demo.error1=Error message one
demo.error2=Error message two

Here is the JS file in my example - js_demo.js:

function getErrorMessagesA(msg1, msg2) {
  console.log('parameter A1 = ' + msg1);
  console.log('parameter A2 = ' + msg2);
}

Here is the Thymeleaf template which calls getErrorMessagesA :

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>JS Demo</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script src="js/js_demo.js"></script>
    </head>
    <body>
        <h2 id="derf">JS Demo</h2>
    </body>

    <!-- option 1: call the function in an external script with parameters: -->
    <script th:inline="javascript">
        $(document).ready(function() {
            getErrorMessagesA( [[#{welcome.error1}]], [[#{welcome.error2}]] );
        });
    </script>

</html>

The Thymeleaf template uses the [[#{...}]] syntax to embed Thymeleaf variables into JavaScript. See expression inlining .

When the web page is rendered, the console displays the two messages as follows:

parameter A1 = Error message one
parameter A2 = Error message two

Option 2 of 2

This uses a different approach, wherein the JS is added to the HTML template as a fragment (meaning it can be re-used in different templates. In this case, the function is called with no parameters.

The fragment is embedded in the main template using this (which replaces the "option 1" section in the above code):

    <!-- option 2: process the function as a Thymeleaf fragment: -->
    <th:block th:replace="jsdemo_jscode.html :: js_fragment_1" ></th:block>
    <script th:inline="javascript">
        $(document).ready(function() {
            getErrorMessagesB();
        });
    </script>

The Thymeleaf fragment file:

<th:block th:fragment="js_fragment_1">

    <script th:inline="javascript">
        function getErrorMessagesB() {
            console.log('parameter B1 = ' + /*[[#{demo.error1}]]*/ '[msg not found]');
            console.log('parameter B2 = ' + /*[[#{demo.error2}]]*/ '[msg not found]');
        }
    </script>

</th:block>

This uses the natural templating syntax of Thymeleaf: /*[[#{demo.error1}]]*/ , to ensure the JavaScript is valid. Note also the th:inline="javascript" directive.

When the web page is rendered, the console displays the two messages as follows:

parameter B1 = Error message one
parameter B2 = Error message two

The main difference here is that the call to the JS in the fragment has no parameters - it's just getErrorMessagesB(); .

Option 3 of 2

There is theoretically a third option - but I've never done this. I think it would be complicated.

You can use a parameter-free call in your Thymeleaf template getErrorMessagesB(); - but instead of using a JS fragment as in option 2, you use the external JS file as in option 1.

Here, the JS would be as follows:

function getErrorMessagesB() {
    console.log('parameter B1 = ' + /*[[#{demo.error1}]]*/ '[msg not found]');
    console.log('parameter B2 = ' + /*[[#{demo.error2}]]*/ '[msg not found]');
}

The complexity with this is that you need to process this file in addition to - but separately from - the HTML file - and make it available to the HTML file. I've used textual templates, but never where they were a dependency on related HTML templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM