CakePhp将变量翻译为JS变量



我想从php文件中拆分js代码,但是将翻译变量从php传输到js时遇到问题。 CakePhp使用__('text {VAR}', [VAR])进行翻译;

这是php文件末尾的代码

$orders = [1=>...,2=>...., 3=>..., 4=>...];
<script>
var allOrders = <?= json_encode($orders ?? null) ?>;
var text_ok = '<?= __('OK') ?>';
.
.
.
var text_doYouWantToDeleteOrder = '<?= __('Do you really want to delete house No. {0}?', [json_encode($order->id)]); ?>';
</script>

还有我的外部文件(仅限 JS(:

<script type="text/javascript">
var i = 0;
$.each(allOrders, function (index, order) {
$('#delete-order-' + order.id).click(function () {
swal({
title: text_doYouWantToDeleteOrder,
...
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
...
}
});
});
i++;
});

所以问题是如何将第一个文件的翻译匹配到第二个文件以获得:

你真的要删除1号房子吗?
你真的要删除5号房子吗?
你真的要删除8号房子吗?

旧的工作代码(php和js混合(

<script type="text/javascript">
<?php
$i = 0;
foreach ($orders as $order) {
?>
$('#delete-order-<?= $order->id ?>').click(function () {
swal({
title: "<?= __('Do you really want to delete house No. {0}?', [$order->id]); ?>",
...
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
...
}
});
});
<?php
$i++;
}
?>

使用 I18next 并使用 gulp-i18next-conv 转换您的 *.po 文件或使用 i18next-po-loader 但 po-loader 要求您将 webpack 添加到您的堆栈中(如果您还没有的话(。

这对我们来说是最好和最完美的,因为它允许我们分享翻译。

我们遇到了同样的问题,但只使用一次,所以这是我的解决方案:

替换翻译字符串函数

function strFormat(source, params) {
params.forEach(function (n, i) {
source = source.replace(new RegExp("\{" + i + "\}", "g"), n);
});
return source;

使用cakePhp的翻译

function translateMe(param) {
var text = "<?= __('Do you really want to delete order No. {0}?'); ?>";
return strFormat(text, [param]);
}

并在您的 SWAL 中使用

var i = 0;
$.each(orderData, function (key, order) {
$('#delete-order-' + order.id).click(function () {
swal({
title: translateMe(order.id),
...
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
...
}
});
});
i++;
});

但是对于不断使用 https://www.i18next.com/getting-started.html 将是我的选择

最新更新