【发布时间】:2012-01-01 22:22:11
【问题描述】:
我正在尝试将 Mustache 与 i18n(php,在 Wordpress 中)一起使用。我的基本 __ 功能运行良好,就像这样
class my_i18n {
public function __trans($string) {
return __($string, 'theme-name');
}
}
class mytache {
public function __()
{
return array('my_i18n', '__trans');
}
}
然后输出一个带有 i18n 字符串的模板,我可以这样做
$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}}{{/__}} 之类的操作,它就不起作用了。我猜是因为内部标签首先被转换,因此无法找到该短语的翻译。
任何想法如何用 Mustache 干净地实现这一目标?
更新:这是最终结果 sn-p(在 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');
}
}
【问题讨论】:
-
您使用什么关键字从 mustache 模板中提取字符串?
标签: php wordpress internationalization mustache