我希望将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++;
}
?>