CakePhp将变量翻译为JS变量

3

我希望将JS代码从PHP文件中分离出来,但是我在将翻译变量从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++;
  }
  ?>
2个回答

3
使用I18next,并使用gulp-i18next-conv将*.po文件转换,或者使用i18next-po-loader,但如果您还没有使用webpack,则需要添加webpack到您的堆栈中。
对我们来说,这是最好、最无缝的方法,因为它允许我们共享翻译。

1
我们也遇到了同样的问题,但只是一次性使用,这是我的解决方案:
替换您的翻译字符串函数
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 将是我的选择


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接