Layouts and asset bundles
A layout is the common frame of all pages: the header, the menu, the footer. It is described once, and the view of a page is inserted inside. Styles and scripts are attached to the layout through an asset bundle, a class with a list of files.
Where the layout lives
The default layout is the file views/layouts/main.php, and it already exists in the project. Simplified, it looks like this:
<?php
// views/layouts/main.php
use app\assets\AppAsset;
use yii\helpers\Html;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="utf-8">
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<header><?= Html::a('My blog', ['post/index']) ?></header>
<main><?= $content ?></main>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>The $content variable holds the rendered markup of the page view. The calls head(), beginBody() and endBody() mark the places where Yii inserts style and script tags. If you remove them, the styling disappears.
Another layout
To give some pages a different frame, create a second file, for example views/layouts/admin.php, and name it in the controller:
// controllers/AdminController.php
class AdminController extends Controller
{
public $layout = 'admin';
}All actions of this controller are rendered in the admin layout. For a single action the layout is changed with the line $this->layout = 'admin'; before render(). The method renderPartial('index') renders a view with no layout at all.
An asset bundle
An asset bundle is a class that lists CSS and JavaScript files. The project already has one, assets/AppAsset.php:
// assets/AppAsset.php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset',
];
}The paths are relative to the web folder: the line css/site.css means the file web/css/site.css. The depends property lists bundles that must be loaded earlier; here these are the Yii scripts and the Bootstrap styles.
Your own style or script file
Create the file web/js/app.js and add it to the bundle:
public $js = [
'js/app.js',
];The line AppAsset::register($this) in the layout attaches the bundle, and every page gets a script tag with the address /js/app.js.
A script for one page
A small script needed by one view is registered right in it:
<?php
// views/post/index.php
$this->registerJs('console.log("The posts page is open");');Yii inserts this code before the closing body tag.
Common mistake
link and script tags typed into the layout by hand bypass the asset system: the loading order breaks, and a script may load before the library it depends on. Add files to AppAsset and list dependencies in depends.