Bootstrap is a popular front-end framework that helps in designing responsive and visually appealing web applications. Yii2 provides built-in support for Bootstrap, making it easy to integrate and use Bootstrap components in Yii2 applications.
This tutorial covers:
Yii2 provides an official extension for Bootstrap. To install it, run the following command in your project:
composer require yiisoft/yii2-bootstrap5After installation, update your config/web.php to ensure Bootstrap is loaded properly:
'components' => [
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
],
],
],
],If you prefer to use Bootstrap via a CDN, include the following links in your layout file (views/layouts/main.php):
<?php
$this->registerCssFile('https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css');
$this->registerJsFile('https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js', ['depends' => [yii\web\JqueryAsset::class]]);
?>Once Bootstrap is installed, you can directly use Bootstrap classes in your views. Example:
<div class="container">
<h1 class="text-primary">Welcome to Yii2 with Bootstrap</h1>
<button class="btn btn-success">Click Me</button>
</div>Yii2 provides built-in Bootstrap widgets that make it easy to use Bootstrap components. Here are some commonly used widgets:
use yii\bootstrap5\Button;
echo Button::widget([
'label' => 'Click Me',
'options' => ['class' => 'btn btn-primary']
]);use yii\bootstrap5\Modal;
Modal::begin([
'title' => 'My Modal',
'toggleButton' => ['label' => 'Open Modal', 'class' => 'btn btn-info'],
]);
echo "Hello, this is modal content!";
Modal::end();use yii\bootstrap5\Alert;
echo Alert::widget([
'options' => ['class' => 'alert alert-warning'],
'body' => 'This is a warning message!'
]);If you need to override Bootstrap styles, you can create a custom CSS file and include it in your asset bundle.
Create a file web/css/custom.css and add your styles:
body {
background-color: #f8f9fa;
}Modify AppAsset.php to include the custom CSS file:
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $css = [
'css/custom.css',
];
}If you are using Yii2 modules, you can create a separate asset bundle for each module.
Example: Creating a module-specific Bootstrap asset:
namespace app\modules\admin\assets;
use yii\web\AssetBundle;
class AdminAsset extends AssetBundle
{
public $sourcePath = '@app/modules/admin/assets';
public $css = ['admin.css'];
public $js = ['admin.js'];
public $depends = ['yii\bootstrap5\BootstrapAsset'];
}Then, register it in your module layout:
use app\modules\admin\assets\AdminAsset;
AdminAsset::register($this);Integrating Bootstrap in Yii2 is simple and enhances the UI/UX of applications. Whether using the Yii2 Bootstrap extension or a CDN, you can easily include Bootstrap components, customize styles, and manage Bootstrap assets efficiently.
Sign in to join the discussion and post comments.
Sign in