This time I want to talk about how to add external assets to the Yii2 project, taking FontAwesome as an example.
Yii2 started to use composer for project dependency management. This thing is similar to npm in NodeJS. It can automatically obtain the latest version of third-party libraries on Github (such as Bootstrap, FontAwesome, etc.). After installing it according to the official tutorial, you can start to initialize the project.
1. Initialization project
Initialize via Composer
php composer.phar create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
Then start coding, the Model Controller View is amazing, click here to see.
2. Install FontAwesome
Finally, your project has developed to the point where you need to reference third-party libraries. We still install them through Composer. Searching the official package list of packagist.org, we found the configuration of FontAwesome. Add FortAwesome/Font-Awesome": "*" to the project's composer.json configuration file.
// ... "require": { "php": ">=5.4.0", "hybridauth/hybridauth": "dev-master", "FortAwesome/Font-Awesome": "*", // <- 这里 "yiisoft/yii2": "*", "yiisoft/yii2-swiftmailer": "*", "yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-debug": "*", "yiisoft/yii2-gii": "*" }, // ...
Then run
php composer.phar update
Pull the FontAwesome package from Github to the project local.
3. Create FontAwesome asset bundle
In order to use these libraries, we need to create a FontAwesomeAsset.php in the /assets directory of the project
namespace assets; use yii\web\AssetBundle; class FontAwesomeAsset extends AssetBundle { // 下面这些资源文件并不在 web 目录下,浏览器无法直接访问。所以我们需要 // 指定 sourcePath 属性。注意 @vendor 这个 alias,表示 vender 目录 public $sourcePath = '@vendor/fortawesome/font-awesome'; public $css = [ 'css/font-awesome.css', ]; }
4. Register files and introduce resources
There are two methods. The first is when you want to introduce this resource package on a specific page
// 这两句直接写在那一页的 view 里 use assets\FontAwesomeAsset; FontAwesomeAsset::register($this);
Second, introduce it globally into your website, or use it as a dependent reference of another resource. Add this to your project's asset/AppAsset.php:
class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', ]; public $js = [ ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', // 在这里加上我们的 FontAwesomeAsset 包类 'assets\FontAwesomeAsset' ]; }
Refresh the page to see if the corresponding css and js resources have been introduced.