2012-01-01 68 views
5

我正在嘗試將鬍子和i18n(php,在Wordpress中)一起使用。我已經得到了基本的功能__很好的工作,像這樣帶參數的鬍子i18n

class my_i18n { 
    public function __trans($string) { 
    return __($string, 'theme-name'); 
    } 
} 
class mytache { 
    public function __() 
    { 
    return array('my_i18n', '__trans'); 
    } 
} 

然後輸出與國際化字符串的模板,我可以簡單地這樣做

$context = new mytache; 
$template = "<div>{{#__}}String to translate{{/__}}</div>"; 
$m = new Mustache; 
echo $m->render($template, $context); 

到目前爲止,一切都很好。但是,我希望能夠使用參數翻譯字符串。即相當於sprint_f(__('Account Balance: %s'), $balance);

看來,如果我做了類似{{#__}}Account Balance: {{balance}}{{/__}}的東西,它就不起作用。我猜是因爲內標籤首先被轉換,因此無法找到該短語的翻譯。

任何想法如何用鬍子乾淨地做到這一點?

更新:這是最終的結果片段(從bobthecow巨大的幫助):

class I18nMapper { 
    public static function translate($str) { 
     $matches = array(); 
     // searching for all {{tags}} in the string 
     if (preg_match_all('/{{\s*.*?\s*}}/',$str, &$matches)) { 
      // first we remove ALL tags and replace with %s and retrieve the translated version 
      $result = __(preg_replace('/{{\s*.*?\s*}}/','%s', $str), 'theme-name'); 
      // then replace %s back to {{tag}} with the matches 
      return vsprintf($result, $matches[0]); 
     } 
     else 
      return __($str, 'theme-name'); 
    } 
} 

class mytache { 
    public function __() 
    { 
    return array('I18nMapper', 'trans'); 
    } 
} 
+1

「it does not work」>。< – 2012-01-01 22:23:08

+0

你用什麼關鍵詞從小鬍子模板中提取字符串? – 2014-01-15 14:47:42

回答

4

I added an i18n example here ......這很俗氣,但測試通過。它看起來與你正在做的幾乎一樣。是否有可能使用過時的Mustache版本?該規範用於指定不同的變量插值規則,這會使該用例無法按預期工作。

+0

這看起來像我一直在尋找...與[此評論](https://github.com/bobthecow/mustache.php/issues/69#issuecomment-3347583)在github上 – gingerlime 2012-01-04 15:16:18

0

在我代表我會建議使用正常的,功能齊全的模板引擎。我明白,小小是偉大的一切,但是例如Twig先進得多。所以我會推薦它。

關於小鬍子。你不能只是擴展你的翻譯方法!比如你通過{{#__}}Account Balance: #balance#{{/__}}

function __($string, $replacement) 
{ 
    $replaceWith = ''; 

    if ('balance' == $replacement) 
    { 
     $replaceWith = 234.56; 
    } 

    return str_replace('#' . $replacement . '#', $replaceWith, $string); 
} 

class my_i18n 
{ 
    public function __trans($string) 
    { 
     $matches  = array(); 
     $replacement = ''; 

     preg_match('~(\#[a-zA-Z0-9]+\#)~', $string, $matches); 

     if (! empty($matches)) 
     { 
      $replacement = trim($matches[0], '#'); 
     } 

     return __($string, $replacement); 
    } 
} 

$Mustache = new Mustache(); 
$template = '{{#__}}Some lime #tag#{{/__}}'; 
$MyTache = new mytache(); 

echo $Mustache->render($template, $MyTache); 

這是一個非常醜陋的例子,但你可以把它看上自己。正如我看到它自己的鬍鬚將無法做到你想要的。

希望有幫助。

+0

感謝您的努力。這不是真的解決了這個問題,我也不會真的叫它乾淨。它在某些方面使情況變得更糟,不得不維護所有這些標籤和條件等。令人驚訝的是,Mustache似乎沒有內置模板內的國際化支持。 – gingerlime 2012-01-02 16:37:01

+0

做一個你自己。從來沒有說過,這是一個乾淨的解決方案。我已經是第一個parargaph了,我建議使用一個普通的全功能模板引擎。 ;) – Eugene 2012-01-02 17:37:20