使用JavaScript动态变量对字符串进行国际化 [英] Internationalization of strings with JavaScript Dynamic variable
本文介绍了使用JavaScript动态变量对字符串进行国际化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的js文件中有两个JS字符串.
There are two JS strings in my js file.
本地化之前的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中.我写了以下
I use the above code to localize the script. And then in JS. I write the following
本地化后的JS文件:
var a = storelocatorjstext.nostores;
这很好.但是,如果我的JS脚本中有一个动态变量,该怎么办?就像关注
This works fine. But what if I have a dynamic variable in my JS script? Like following
本地化之前的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文件中使用它?就像我们在PHP中使用sprintf
和%s
或%d
一样.
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文件:
var dynamic = 5;
var a = storelocatorjstext.nostores;
var b = ???;
推荐答案
为什么不使用javascript替换,例如:
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);
这篇关于使用JavaScript动态变量对字符串进行国际化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文