Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mustache i18n with parameters

I'm trying to use Mustache together with i18n (php, within Wordpress). I've got the basic __ functionality working nicely, something like this

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

Then to output a template with an i18n string, I can simply do this

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

So far everything is fine. However, I want to be able to translate strings with parameters. i.e. the equivalent of sprint_f(__('Account Balance: %s'), $balance);.

It seems that if I do something like {{#__}}Account Balance: {{balance}}{{/__}} it doesn't work. I'm guessing because the inner tag gets converted first and therefore the translation cannot be found for the phrase.

Any ideas how to achieve this cleanly with Mustache?

UPDATE: here's the end-result snippet (with massive help from 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');
  }   
}   
like image 666
gingerlime Avatar asked Oct 09 '22 02:10

gingerlime


1 Answers

I added an i18n example here... it's pretty cheesy, but the test passes. It looks like that's almost the same as what you're doing. Is it possible that you're using an outdated version of Mustache? The spec used to specify different variable interpolation rules, which would make this use case not work as expected.

like image 153
bobthecow Avatar answered Oct 12 '22 23:10

bobthecow