Internationalization of strings with JavaScript Dynamic variable

浪子不回头ぞ 提交于 2019-12-24 10:46:53

问题


There are two JS strings in my js file.

JS File Before localization:

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' )
) );

I use the above code to localize the script. And then in JS. I write the following

JS File After localization:

var a = storelocatorjstext.nostores;

This works fine. But what if I have a dynamic variable in my JS script? Like following

JS File Before localization:

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
) );

How to internationalize for the string with dynamic variable and how to use it in my JS file? Like we use sprintf and %s or %d in PHP.

JS File After localization:

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

回答1:


Why not use javascript replace, something like:

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
) );

js:

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


来源:https://stackoverflow.com/questions/42088691/internationalization-of-strings-with-javascript-dynamic-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!