2017-02-07 6 views
1

В моем js-файле есть две строки JS.Интернационализация строк с JavaScript Динамическая переменная

JS файла Перед локализацией:

var a = 'There are no stores in this area.'; 

functions.php

wp_localize_script('store-locator', 'storelocatorjstext', array(
    'nostores' => __('There are no stores in this area.', 'storelocator') 
)); 

Я использую приведенный выше код для локализации сценария. И затем в JS. Я пишу следующую

JS файла После локализации:

var a = storelocatorjstext.nostores; 

Это прекрасно работает. Но что, если у меня есть динамическая переменная в моем JS-скрипте? Как следующий

JS файл Перед локализацией:

var dynamic = 5; 
var a = 'There are no stores in this area.'; 
var b = 'There are '+ dynamic +'stores in this area.'; 

functions.php

wp_localize_script('store-locator', 'storelocatorjstext', array(
    'nostores' => __('There are no stores in this area.', 'storelocator'), 
    'existingstores' => __('There are 5 stores in this area.', 'storelocator') //I know this is wrong. How to add dynamic variable here like we do with PHP sprintf 
)); 

Как интернационализацию для строки с динамической переменной и как использовать его в моем файле JS ? Как мы используем sprintf и %s или %d в PHP.

JS файла После локализации:

var dynamic = 5; 
var a = storelocatorjstext.nostores; 
var b = ???; 

ответ

1

Почему бы не использовать Javascript заменить, что-то вроде:

PHP:

wp_localize_script('store-locator', 'storelocatorjstext', array(
    'nostores' => __('There are no stores in this area.', 'storelocator'), 
    'existingstores' => __('There are %s stores in this area.', 'storelocator') //I know this is wrong. How to add dynamic variable here like we do with PHP sprintf 
)); 

ЯШ:

var dynamic = 5; 
var a = storelocatorjstext.nostores; 
var b = storelocatorjstext.existingstores.replace("%s", dynamic); 
+1

Awe некоторые. Спасибо за идею. –