[英]How to hard code text which are coming from javascript messages
我们的应用程序已国际化并更改为不同的语言。 出于这个原因,我们必须对所有消息进行硬编码。 我们如何为 javascript 中的消息做到这一点?
这就是我们在 html 消息中所做的。
<span th:text="#{listTable.deletedFromTable}">deleted</span>
我们如何对 javascript 消息进行硬编码。(更新表格)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
您需要从一开始就将消息放入DOM
,但不显示它们。 将这些文本放在span
标签中,每个标签都有一个唯一的id
和th:text
属性——您可以将它们添加到文档的末尾:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
这将确保您的国际化模块也将在此元素上发挥作用,并且即使未显示文本也会被翻译。
然后在您想要使用该警报的那一刻,获取隐藏的文本并将其注入您需要的地方:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
您要求提供另一个变体,您目前拥有:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
然后,您将再次将此内容添加为非显示span
,并为计数添加占位符:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
您应该确保您的翻译也使用占位符。 然后按如下方式使用它,在运行时替换占位符:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
您可以创建一个函数来处理此类占位符的替换:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
然后这两个例子将写成如下:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.