In yii2, due to the upgrade of yii2 version, many usages of yii2 are very different from yii1. I have been wandering around the view interface of the view layer these days. What problems have I encountered? The problem is that I can’t figure out how to introduce CSS and JS files! I also read the tutorials of other experienced masters in the community and followed them, but there are still some problems. For example, after the yii2 project is opened, the header and tail are public. How to remove them? And how to introduce JS and CSS files without changing the original main.php file. Maybe one way is to write a configuration file of xxxAsset.php, and then import the file through xxx Asset::register($this). But this time I encountered a problem again. This code was invalid and did not work. After opening firebug, no CSS or JS files were introduced in the head, and the style became messy. Later I checked the relevant Information, coincidentally, I downloaded a yii2 backend template posted by someone else, so this morning I took a look at how the backend style is laid out, and summarized it:
1. The simplest thing in the front view is like File by file is imported as before, so use use to call the code segment at the top
use yiihelpersHtml;
Then in the Html below, you can call it like this
<?=Html::jsFile('@web/***/js/***.js')?>//这里***代表你的目录名或者文件名 <?=Html::cssFile('@web/***/css/***.css')?>//***同上
In this way, you don’t need to touch other files, just import the file directly Which one needs to be imported? Of course, if you write it this way, you have to write a lot of lines of code to load it every time. It is best to write it in the configuration file, but I have not figured out the problem of using the configuration file to introduce it. I will find out the reason later. I will share it with you
2. The front desk is introduced in this way, so how to customize the style file in the controller
Add the following code to the controller
public $layout = 'layout';//Define a variable in the class, It’s called $layout
Note that this layout has a directory called layouts in your view. In this directory, I created a new file named layout.php, and added a code in it
php echo $content; ?>
In this way, the controller will automatically find the php file that loads the view file in the layouts directory of the current view directory
The above few lines of short code will solve the problem that novices don’t know how to do. Regarding the problem of loading CSS and JS files, if you think there will be problems writing ***Asset.php files, just use my method. Later, after you become familiar with yii2, you can use other methods to load them
In addition, I will add Next, how to jump links to other view files in the view? Also introduce the class library at the top first. toRoute('post/index');?>//Post is your current controller name, index is the view template