I want to split js code from php files and I have problem with transfering translate variable from php to js.
CakePhp make translation using __('text {VAR}', [VAR]);
Here is code at the end of php file
$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>
And my external file (only 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++;
});
so the problem is how to match translation from first file into second to get :
Do you really want to delete house No. 1?
Do you really want to delete house No. 5?
Do you really want to delete house No. 8?
Old working code (php and js mix)
<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++;
}
?>
Use I18next and convert your *.po files using gulp-i18next-conv or use i18next-po-loader but the po-loader requires you to add webpack to your stack if you haven't already.
This worked the best and most flawless for us as it allows us the share the translations.
We had the same issue, but only for one time use, so this was my solution:
Replace your translation string function
function strFormat(source, params) {
params.forEach(function (n, i) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
Use translation from cakePhp
function translateMe(param) {
var text = "<?= __('Do you really want to delete order No. {0}?'); ?>";
return strFormat(text, [param]);
}
and use in your 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++;
});
But for constant use https://www.i18next.com/getting-started.html will be my choice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With