This time to say how to add an external resource (external assets) to the YII2 project to Fontawesome as an example.
Yii2 started using composer to do project dependency management, which is similar to the Nodejs inside NPM, can automatically get the latest version of the Github of Third-party libraries (such as Bootstrap, Fontawesome, and so on). After the official tutorial is installed, you are ready to start initializing the project.
First, the initialization of the project
Initialized by Composer.
PHP composer.phar create-project--prefer-dist--stability=dev yiisoft/yii2-app-basic Basic
Then start code code, Model Controller View god horse, here press not table.
Second, install Fontawesome
Finally, your project has developed to the need to refer to the Third-party library, we still install through Composer. Search the packagist.org official package list, we found the Fontawesome configuration. Add Fortawesome/font-awesome ": *" to the project's Composer.json configuration file.
// ...
" Require ": {"
php ":" >=5.4.0 ",
" Hybridauth/hybridauth ":" Dev-master ",
" Fortawesome/font-awesome ":" * ",//<-here
" Yiisoft/yii2 ":" * ",
" Yiisoft/yii2-swiftmailer ":" * ",
" Yiisoft/yii2-bootstrap ":" * ",
"Yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*"
},
///...
And then run
Pull the Fontawesome package from the Github to the project Local.
Third, create the Fontawesome resource bundle (Asset bundle)
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
{
//The following resource files are not in the Web directory and cannot be accessed directly by the browser. So we need
//Specify the SourcePath attribute. Note @vendor This alias, indicating that the vender directory is public
$sourcePath = ' @vendor/fortawesome/font-awesome ';
Public $css = [
' Css/font-awesome.css ',
];
}
Iv. registration documents, introduction of resources
There are two ways of doing this. First, when you want to introduce this resource bundle on a particular page
These two sentences are written directly in the view of that page use
assets\fontawesomeasset;
Fontawesomeasset::register ($this);
The second is a global introduction to your site, or a dependency reference to another resource. Add it to the asset/appasset.php of the project:
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 ',
//Here Add our Fontawesomeasset Package class
' Assets\fontawesomeasset '
];
Refresh the page to see if you have introduced the corresponding CSS, JS resources.