1

Is there a way to pass through a variable to Kohana messages, which can then be picked up by the il8n translation e.g.:

Kohana::message('user', 'greeting')

messages/user.php:

return array
(
    'greeting' => __('user.greeting', array(':user' => $name ))
);

i18n/en.php:

return array
(
    'greeting' => 'Hello, :user'
);

I grabbed the method of linking the il8n to message from i18n and Error messages in Kohana 3

Community
  • 1
  • 1
xylar
  • 7,433
  • 17
  • 55
  • 100

1 Answers1

2

I don't have the exact answer you are looking for, but I could suggest a solution if you don't mind overwriting the current Kohana::message() method. I have done something similar in my own app.

Just create a Kohana.php file in your 'applications/classes' with the following code:

class Kohana extends Kohana_Core {

    public static function message($file, $path = NULL, $default = NULL, $replacements = array())
    {
        static $messages;

        if ( ! isset($messages[$file]))
        {
            // Create a new message list
            $messages[$file] = array();

            if ($files = Kohana::find_file('messages', $file))
            {
                foreach ($files as $f)
                {
                    // Combine all the messages recursively
                    $messages[$file] = Arr::merge($messages[$file], Kohana::load($f));
                }
            }
        }

        if ($path === NULL)
        {
            // Return all of the messages
            $message = $messages[$file];
        }
        else
        {
            // Get a message using the path
            $message = Arr::path($messages[$file], $path, $default);
        }

        return !empty($replacements) ? strtr($message,$replacements) : $message;
    }
}

Basically the only notable change is the addition of $replacements argument and return !empty($replacements) ? strtr($message,$replacements) : $message; which replaces the contents of your message with those that are in your replacements array.

So you can now do this:

Kohana::message('user', 'greeting', NULL, array(':user' => $name));

messages/user.php:

return array
(
    'greeting' => __('user.greeting'),
);
ephemeron
  • 396
  • 2
  • 12
  • Thanks, that works great. In your example the :user value is not being passed through to the i18n e.g. `'greeting' => __('user.greeting', array(':user'=>':user')` - added for reference. – xylar May 31 '12 at 16:07
  • Why not use `parent::message()` to take advantage of inheritance and turn this function into a single line? – None Jul 04 '14 at 12:20