What is the place for RegisterCssFile in Yii?

I am new to Yii.

Is it right to place a registerCssFile call inside a controller action?

My opinion is that the right place for this is inside the views

For example, I create some fragment of the user menu and include it inside some of my views. I got a separate css file for the user menu, and I do not want to care about this user_menu.css inside every action or controller that uses this user menu. Therefore, I use this code inside the parts/user_menu.php :

 <?php Yii::app()->getClientScript()->registerCssFile(yii::app()->request->baseUrl.'/css/user_menu.css', 'screen'); ?> <ul class="user-menu"> ...here comes menu 

Is this correct, or should I include this css file inside every action or controller?

Maybe there are some style guides about this? Any links appreciated ...

+4
source share
2 answers

I canโ€™t talk about the โ€œofficialโ€ right place, but I have a custom base controller that expands with all my controllers. I place global calls to registerCssFile() in the init() method of this base controller, so they are automatically registered on the whole site.

If you reuse files with a partial view, I can see how to register CSS in the view, which I assume, but ...

It is probably most appropriate to include all the CSS for the entire site in the init() controller method, and then combine and compress it using extensions like these .

(If in one view there isnโ€™t a lot of custom CSS that is not used anywhere on the site, perhaps.)

EDIT: As indicated below by briiC.lv, using themes means that you want to save all CSS in your view / layout files, separate from the controller code.

+6
source

First of all, if I were you, I would completely forget about registerCssFile and always use only registerPackage . Thus, you can change the whole style by changing one line in one clearly defined place.

Two options:

  • You make a base class for your controller classes and put all the register statements in beforeRender . Thus, you will need a separate controller class for each section of the website, which requires a different style.

  • You are using modules. Then you go and place the register calls in the init call of the module class.

Do not put registerCss calls in views ever. This will affect you very quickly. It doesn't matter if you have a small website or a large one.

I personally prefer to always use beforeRender , as this means that assets will be processed only for your "pages", that is, for those who respond to requests from clients who do something, I hope, as an HTML client.

+1
source

Source: https://habr.com/ru/post/1386310/


All Articles