getkirby-v2 / toolkit

This is the deprecated toolkit for Kirby v2.
http://getkirby.com
81 stars 50 forks source link

Add replacements to the L class #208

Closed sebsel closed 7 years ago

sebsel commented 7 years ago

For translation purposes it would be nice if you can use %s (or similar) to replace certain words in certain phrases.

Example from Dutch: 'likes %s' > 'vindt %s leuk'

In Dutch (and German and many other languages) word-order is not always what it is in English. Replacements are very useful then :)

Here's a bit of what could work:

class L extends Silo {
  public static $data = array();

  public static function get($key = null, $default = null, $replacements = array()) {
    if(empty($key)) return static::$data;
    if(empty($replacements)) {
      return isset(static::$data[$key]) ? static::$data[$key] : $default;
    } else {
      if(isset(static::$data[$key])) {
        array_unshift($replacements, static::$data[$key]);
      } else {
        array_unshift($replacements, $default);
      }
      return call('sprintf', $replacements);
    }
  }
}
lukasbestle commented 7 years ago

I agree that we should introduce some kind of placeholders. However I think we should use MessageFormatter here to make it even more flexible. What do you think?

sebsel commented 7 years ago

I never heard of MessageFormatter, but sure! Does it do strings? I see only numbers as replacements.

lukasbestle commented 7 years ago

MessageFormat is a pretty powerful language, it can do all sorts of language-specific formatting such as numbers, money, plurals etc.

Of course it also supports simple strings:

{name} likes {item}
bastianallgeier commented 7 years ago

I already have a first version ready, but what would you do when MessageFormatter is not available? Fall back to simple string replacements or throw an error?

lukasbestle commented 7 years ago

As far as I can tell it's bundled with PHP. But you are right, there might be situations where users have disabled the extension.

I think we shouldn't try to emulate it though. It's waay to powerful and there is no way we would get that right. Maybe we should require it when using replacements. If replacements are not used, it doesn't matter anyway and this is an optional feature.

bastianallgeier commented 7 years ago

At least the default PHP installation on macOS comes without the extension. I think you are right though. We throw an error if you try to use it for replacements. Otherwise it will be ignored. It's pretty brilliant btw. Haven't heard about it before.

bastianallgeier commented 7 years ago

Just pushed my version to the develop branch. Works great!