使用JavaScript动态变量对字符串进行国际化

时间:2017-02-07 11:27:10

标签: javascript wordpress localization internationalization

我的js文件中有两个JS字符串。

JS文件在本地化之前:

    GetRequest request = Unirest.get(url);
    // add any extra headers if so sent in for the request
    request = request.headers(headers);

    // Add any extra request parameters if any required for the request.
    request = (GetRequest) addRequestParams(request, queryParams);
    System.out.println(request.getUrl()); // NOPMD let the URL get printed out on the console
    return request.asStringAsync();
}

的functions.php

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

我使用上面的代码来本地化脚本。然后在JS中。我写下面的

本地化后的JS文件:

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

这很好用。但是如果我的JS脚本中有动态变量怎么办?喜欢以下

JS文件在本地化之前:

var a = storelocatorjstext.nostores;

的functions.php

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

如何使用动态变量对字符串进行国际化以及如何在我的JS文件中使用它?就像我们在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 ) ); sprintf%s一样。

本地化后的JS文件:

%d

1 个答案:

答案 0 :(得分: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
) );

JS:

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