簡體   English   中英

使用 JavaScript 動態變量對字符串進行國際化

[英]Internationalization of strings with JavaScript Dynamic variable

我的 js 文件中有兩個 JS 字符串。

本地化前的 JS 文件:

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

函數.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.';

函數.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

本地化后的JS文件:

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

為什么不使用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM