[英]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 ?
我们如何为 javascript 中的消息做到这一点?
This is how we are doing in html messages.这就是我们在 html 消息中所做的。
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)我们如何对 javascript 消息进行硬编码。(更新表格)
$('#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.您需要从一开始就将消息放入
DOM
,但不显示它们。 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
和th:text
属性——您可以将它们添加到文档的末尾:
<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
,并为计数添加占位符:
<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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.