【问题标题】:mustache i18n with parameters带参数的小胡子 i18n
【发布时间】: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


【解决方案1】:

I added an i18n example here... 这很俗气,但测试通过了。看起来这和你正在做的几乎一样。您是否有可能使用过时版本的 Mustache?该规范用于指定不同的变量插值规则,这会使该用例无法按预期工作。

【讨论】:

  • 这看起来像我一直在寻找的东西......以及github上的this comment
【解决方案2】:

我代表我建议使用正常的、功能齐全的模板引擎。我明白,小就是伟大的一切,但例如 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 );

这是一个非常丑陋的例子,但你可以自己制作它。正如我所见,Mustache 本身无法做你想做的事。

希望有所帮助。

【讨论】:

  • 感谢您的努力。这并不能真正解决问题,我也不会真正称之为干净。它在某些方面使事情变得更糟,不得不维护所有这些标签和条件等。令人惊讶的是,Mustache 似乎没有内置对模板内国际化的支持。
  • 自己做一个。从来没有说过,这是一个干净的解决方案。我已经在第一个段落中建议使用正常的全功能模板引擎。 ;)
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多