Using traits in view

Hello everyone.

I am studying yii 2.0 and i have a doubt.

In a comparision with the yii 1,i created a trait in /components/Translate.php




Code in YII 1.0

trait Translate{

	public function translate($message, $params = array()){

		return Yii::t(Yii::app()->language,$message,$params);

	}

}



In components/controller.php i set




use Translate;



So will be ready for use in all application

i can to call


$this->translate('test')

in my controllers and views. Its works

In Yii 2.0

I create my trait




namespace common\components;


trait Translate{

	public function translate($message, $params = array()){

		return \Yii::t('app',$message,$params);

	}

}



In my controller




use common\components\Translate;

...


class SiteController extends Controller

{

    use Translate;

    public function init()

	{

		echo $this->translate('testing'); exit;

	}

}




The Code above works, but when i try to call


$this->translate('testing')

In my view, displays an error




Calling unknown method: yii\web\View::translate()



Someone to help me? how can i pass translate() directly

Yii2 use autoloading so you need to follow PSR-4 standard.

I see a few thing wrong with your code.

  • You did not specify the namespace in the trait file

  • The way you access the yii app is wrong, it changed in yii2 (It’s Yii::$app now but I removed it in the code sample below since it wasn’t needed)

  • The way you use the t() function is also wrong, first parameter is the category of the translation, not the language

Here’s how it should look (Assuming you are using the basic application template)




namespace app\components;


trait Translate{

    public function translate($message, $params = array()){

        return \Yii::t('app', $message, $params);

    }

}



and then in the file you want to use your trait in (in this case your controller)




use app\components\Translate;



I did not test this but it should work.

Also you might want to take a look at the docs/guide. It will help you greatly in your study of Yii2.

i try here and it is not works. =/

someone?

In Yii 2 $this in views points to View class, not Controller. You should use something like that:


$this->context->translate('test');

Isn’t it better to use just plain functions instead of traits for this purpose?

give me an example? i use this just for esthetic… i dont know :P

Well, functions.php:




function t($message, $params = array()) { ... }



View:




<?= t('test') ?>