Entire Messages into javascript object

I needed all messages with their translation into javascript. This is my solution:

1- Extend CPhpMessageSource, creating MPhpMessageSource into protected/components :

class MPhpMessageSource extends CPhpMessageSource
{
    public function init()
    {
		parent::init();
    }

    public function getLoadedMessages($category = 'core') 
    {
        return $this->loadMessages($category, Yii::app()->language);
    }
}

2- You add this to protected/config/main.php into components array:

'messages' => array(
            'class' => 'APhpMessageSource'
        ),

3- You add this code into your view:

<script type="text/javascript">
	var messages = <?php echo CJSON::encode(Yii::app()->messages->getLoadedMessages()) ?>;

        function t(key) {
            return (messages[key]) ? messages[key] : key;
        }

        //utilization
        alert(t('Message'));
</script>
1 0
3 followers
Viewed: 8 449 times
Version: 1.1
Category: How-tos
Written by: markux
Last updated by: markux
Created on: Aug 24, 2012
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles