[Help]how to set the parameters to message in javascript

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[Help]how to set the parameters to message in javascript

Richard
Hi....

message.properties -------

member.login = hi, {0}


javasxript -------------------

$.ajax({
   ...
   success: function(data){
        var name = data.member.name;
        var msg =/*[[#{member.login(name)}]]*/;
        ...

but "name" couldn't be parsing to value....
show as "hi, name"

so, how to pass the javascript var to message
thanks...
Reply | Threaded
Open this post in threaded view
|

Re: [Help]how to set the parameters to message in javascript

yvanavermaet
Simple: You can't. Thymleaf is Server-Side. Javascript is Client-Side. You can't mix them like this.

So, how can you do this?

Assumption 1: Your javascript code is located in a HTML page (which would be bad, separation of HTML and JS is advised. But let's suppose it is like this)

When Thymeleaf returns the page (and the javascript code), it'll have rendered:

$.ajax({
   ...
   success: function(data){
        var name = data.member.name;
        var msg = "hi, {0}";
        ...

Or it would have rendered "hi, null" or "hi, ", depending on the value of name. It definitely won't be "data.member.name", because that's done on the Client-Side.

Solution:
Update #{member.login(name)} to #{member.login}

Then in your javascript add behind the Thymeleaf tags: .replace('{0}', name)

Code would be: var msg =/*[[#{member.login}]]*/.replace('{0}', name);

Assumption 2: Your code is inside a .js file
In this case, you'll have to create a JavaScript variable in your HTML page that contains the message

Solution:
var greetingMessage = /*[[#{member.login}]]*/;

In your js file, you'd then do the following

var msg = greetingMessage.replace('{0}', name);


So your main issue is that you're trying to mix Server-Side code (Thymeleaf) with Client-Side code (JavaScript). You can't pass JavaScript variables directly in Thymeleaf code (the var "name" inside the Thymeleaf i18n property)