Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Yii2 Bootstrap5 Laravel Package

yiisoft/yii2-bootstrap5

Bootstrap 5 integration for Yii 2 apps. Provides widgets, helpers, and asset bundles to render Bootstrap 5 components with Yii’s view and form APIs, enabling consistent styling and UI elements using Bootstrap 5 in Yii 2 projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/yii2-bootstrap5
    

    Add to your config/web.php:

    'components' => [
        'assetManager' => [
            'bundles' => [
                'yiisoft\yii2-bootstrap5\BootstrapAsset' => [
                    'sourcePath' => null, // Let the package handle CDN/asset loading
                    'js' => [
                        'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js',
                    ],
                    'css' => [
                        'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
                    ],
                ],
            ],
        ],
    ],
    
  2. First Use Case Render a Bootstrap 5 modal in a view:

    use yiisoft\yii2-bootstrap5\Modal;
    
    echo Modal::widget([
        'header' => '<h4>Modal Title</h4>',
        'body' => 'Modal content goes here.',
        'footer' => '<button class="btn btn-primary" data-bs-dismiss="modal">Close</button>',
        'options' => ['id' => 'myModal'],
    ]);
    
  3. Where to Look First

    • Widget Classes: yiisoft\yii2-bootstrap5\* (e.g., Alert, Button, Card, Modal, Dropdown).
    • Asset Management: yiisoft\yii2-bootstrap5\BootstrapAsset for CDN/local asset handling.
    • Helper Methods: Static methods like yiisoft\yii2-bootstrap5\Html::encode() for safe rendering.
    • Documentation: Check the Yii2 Bootstrap 5 Extension docs for component-specific examples.

Implementation Patterns

Common Workflows

  1. Reusable Components Use widgets for consistent UI elements:

    // Button with icon
    echo \yiisoft\yii2-bootstrap5\Button::widget([
        'label' => 'Submit',
        'options' => ['class' => 'btn btn-success'],
        'icon' => ['name' => 'save', 'position' => 'left'],
    ]);
    
  2. Form Integration Combine with Yii2 ActiveForm for Bootstrap 5 styling:

    echo $form->field($model, 'username')->textInput(['class' => 'form-control']);
    

    Add Bootstrap validation states:

    if ($model->hasErrors()) {
        echo \yiisoft\yii2-bootstrap5\Alert::widget([
            'type' => 'danger',
            'body' => $model->getErrors()[0][0],
        ]);
    }
    
  3. Dynamic Content with JavaScript Use Bootstrap 5 JS components (e.g., tooltips, popovers) via Yii2 helpers:

    use yii\helpers\Html;
    
    echo Html::a(
        'Hover me',
        '#',
        [
            'data-bs-toggle' => 'tooltip',
            'title' => 'This is a tooltip',
            'data-bs-placement' => 'right',
        ]
    );
    
  4. Layout Templates Extend Yii2 base layout with Bootstrap 5 classes:

    // views/layouts/main.php
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3">
                <?php echo $this->render('_sidebar.php'); ?>
            </div>
            <div class="col-md-9">
                <?php echo $content; ?>
            </div>
        </div>
    </div>
    
  5. Asset Management Override default assets in config/web.php:

    'bundles' => [
        'yiisoft\yii2-bootstrap5\BootstrapAsset' => [
            'js' => [
                '@web/js/bootstrap.bundle.min.js', // Local file
            ],
            'css' => [
                '@web/css/bootstrap.min.css',
                '@web/css/custom.css', // Add custom styles
            ],
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Asset Loading Conflicts

    • Issue: Bootstrap JS fails if jQuery is not loaded or loaded after Bootstrap.
    • Fix: Ensure jQuery is included before Bootstrap JS in BootstrapAsset:
      'js' => [
          'https://code.jquery.com/jquery-3.6.0.min.js',
          'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js',
      ],
      
  2. Widget Initialization Order

    • Issue: Dynamic widgets (e.g., modals, tooltips) may not work if initialized after DOM load.
    • Fix: Use Yii2's yii\web\View::registerJs() to defer initialization:
      $this->registerJs(<<<JS
      document.addEventListener('DOMContentLoaded', function() {
          var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
          tooltipTriggerList.map(function (tooltipTriggerEl) {
              return new bootstrap.Tooltip(tooltipTriggerEl);
          });
      });
      JS
      );
      
  3. CSS Specificity

    • Issue: Custom styles may be overridden by Bootstrap's utility classes.
    • Fix: Use more specific selectors or !important sparingly:
      /* In your custom.css */
      .custom-class .btn-primary {
          background-color: #yourcolor !important;
      }
      
  4. Yii2 Bootstrap 4 Migration

    • Issue: Widgets may behave differently (e.g., Modal options changed).
    • Fix: Review the migration guide and update widget configurations.

Debugging Tips

  1. Check Asset URLs Use browser dev tools to verify assets are loading:

    // Debug asset paths
    echo \yiisoft\yii2-bootstrap5\BootstrapAsset::register($this)->js[0];
    
  2. Enable Bootstrap JS Debugging Replace minified JS with unminified for debugging:

    'js' => [
        'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.js', // Unminified
    ],
    
  3. Inspect Widget Output Use var_dump() to debug widget configurations:

    $modal = \yiisoft\yii2-bootstrap5\Modal::widget([...]);
    var_dump($modal); // Inspect rendered HTML
    

Extension Points

  1. Custom Widgets Extend the package by creating your own widgets:

    namespace app\widgets;
    
    use yii\base\Widget;
    use yii\web\View;
    
    class CustomCard extends Widget {
        public $title;
        public $body;
    
        public function run() {
            return $this->render('customCard', [
                'title' => $this->title,
                'body' => $this->body,
            ]);
        }
    }
    

    Register in config/web.php:

    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'customCard' => 'app\widgets\CustomCardRenderer',
            ],
        ],
    ],
    
  2. Override Default Assets Create a custom asset bundle:

    namespace app\assets;
    
    use yii\web\AssetBundle;
    
    class CustomBootstrapAsset extends AssetBundle {
        public $sourcePath = '@vendor/yiisoft/yii2-bootstrap5/assets';
        public $css = ['css/bootstrap-custom.css'];
    }
    

    Use in config/web.php:

    'bundles' => [
        'app\assets\CustomBootstrapAsset' => ['sourcePath' => null],
    ],
    
  3. Hook into Bootstrap Events Use Yii2 behaviors or JavaScript events:

    // Example: Add custom behavior to a modal
    echo \yiisoft\yii2-bootstrap5\Modal::widget([
        'options' => [
            'data-bs-custom-event' => 'myEvent',
        ],
        // ...
    ]);
    
    $this->registerJs(<<<JS
    document.addEventListener('myEvent', function() {
        console.log('Modal opened!');
    });
    JS
    );
    
  4. Localization Override Bootstrap translations:

    // config/i18n.php
    'translations' => [
        'bootstrap5' => [
            'class' => 'yii\i18n\PhpMessageSource',
            'sourceLanguage' => 'en-US',
            'fileMap' => [
                'bootstrap5' => 'path/to/custom-bootstrap-messages.php',
            ],
        ],
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope