简体   繁体   中英

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?

This is how we are doing in html messages.

<span th:text="#{listTable.deletedFromTable}">deleted</span>     

How do we hard code for javascript messages.(update the table)

$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');

You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:

<span id="alertUpdateTable" th:text="#{listTable.updateTable}" 
     style="display:none">Update the Table.</span>

This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.

Then at the moment you want to use that alert, get that hidden text and inject it where you need it:

$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');

You asked for another variant of this, where you currently have:

$successSpan.html(tableItemCount + " item was deleted from the table.", 2000); 

You would then add this content again as a non-displayed span with a placeholder for the count:

<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}" 
     style="display:none">{1} item(s) were deleted from the table.</span>

You should make sure that your translations also use the placeholder. Then use it as follows, replacing the placeholder at run-time:

$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));

You could make a function to deal with the replacement of such placeholders:

function getMsg(id) {
    var txt = $('#' + id).html();
    for (var i = 1; i < arguments.length; i++) {
        txt = txt.replace('{' + i + '}', arguments[i]);
    }
    return txt;
}

And then the two examples would be written as follows:

$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');

$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

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