Drupal 中文化字串 functions [t(), format_plural(), JavaScript]

在 Drupal 當中,包含一些處理文字界面的 FUNCTIONs,其實這不只為本地化語言而製造的,在英文中也起了防止 XSS 的作用。

最簡單的: t()

t($string, array $args = array(), array $options = array())

例如:

t('I am Kay.L.')
t("I am !name.", array('!name' => 'Kay.L'));

好了,在 Drupal 中我們常見 !variable / @variable / %variable,這是什麼?其實它們用作格式化我們傳入的內容,甚至有起 XSS 作用。

  • !variable: 原封不動傳遞給 Drupal
  • @variable: 透過 Drupal 內置 check_plain() Function 將 HTML 轉換 (== PHP htmlspecialchars)
  • %variable: 經過 drupal_placeholder() 處理,跟 @variable 差不多,不同的是前後增加了一個 HTML tag: <em>你的內容</em>

複數字串呢? Drupal 有 format_plural()

format_plural($count, '只有 1 個', '這有 @count 個');

聰明的你應該也理解到,在這裏 $count == @count

一字多譯又怎麼辦?

在 Drupal 7 引入 context 概念嘗試解決這問題

比如 "order",

  • 整理排序時,譯為 "次序"
  • 電子商務時,譯為 "訂單"
t('order', array(), array('context' => 'sorting'));
t('order', array(), array('context' => 'ecart'));

我們在不同的模組中,作不同的定義,以示區別。在 PO 翻譯中格式為:

msgctxt "sorting"
msgid "order"
msgstr "次序"

msgctxt "ecart"
msgid "order"
msgstr "訂單"

在 Javascript 當中,也有一樣的 Functions

例如:

Drupal.t('I am Kay.L.')
Drupal.t('I am !name.', {'!name' : 'Kay.L'})
var count = '10';
Drupal.formatPlural(count, '只有 1 個', '這有 @count 個');
var count = '10';

var args = {};
args['!apple'] = '蘋果';

Drupal.formatPlural(count, '只有 1 個!apple', '這有 @count 個!apple', args);

像上面只傳入一個變量,可以更直接,你應該知道的:

var count = '10';
Drupal.formatPlural(count, '只有 1 個!apple', '這有 @count 個!apple', {'!apple' : '蘋果'});

打開你瀏覽器的 Console (Firebug console, Chrome console..etc) 立刻試試吧。

(值得留意,Drupal 中幾乎 100% 字串都經過 t() 處理,但在寫程式碼時,有一些不必自我增加的,比如 hook_menu 中的 title / description,這預設就必經過 t() 處理。)

寫下您的回覆

電子郵件不會公開