first commit

This commit is contained in:
2026-01-25 18:18:09 +08:00
commit 509312e604
8136 changed files with 2349298 additions and 0 deletions

View File

@ -0,0 +1,30 @@
Twitter Bootstrap Erweiterung für Yii 2
=======================================
Diese Erweiterung enthält Unterstützung für das [Bootstrap 5 Framework](https://getbootstrap.com/) (auch bekannt als "Twitter Bootstrap")
Markup und dessen Komponenten. Bootstrap ist eine exzellentes, reponsives Framework welches den clientseitigen
Entwicklungsprozess vehement zu verkürzen vermag.
Die Basis von Bootstrap ist unterteilt in folgende 2 Bereiche:
- CSS Basics: Grid Layout System, Typography, Helper-Klassen, Responsive Funktionen.
- "Ready to use"-Komponenten: Formulare, Menus, Paginationen, Modals, Tabs etc.
Loslegen
--------
* [Installation](installation.md)
* [Assets Setup](assets-setup.md)
* [Basic Usage](basic-usage.md)
Verwendung
----------
* [Yii widgets](usage-widgets.md)
* [Html helper](helper-html.md)
* [Asset Bundles](asset-bundles.md)
Weitere Themen
--------------
* [Using the .sass files of Bootstrap directly](topics-sass.md)
* [Migration von yii2-bootstrap](migrating-yii2-bootstrap.md)

View File

@ -0,0 +1,18 @@
Asset Bundles
=============
Bootstrap ist eine komplexe Front-End-Lösung, welche CSS, Javascript, Schriften usw. beinhaltet.
Um Ihnen die flexibelste Kontrolle über die einzelnen Komponenten zu ermöglichen, enthält diese Erweiterung verschiedene Asset Bundles.
Das sind:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - enthält nur das hauptsächliche CSS.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - enthält das Javascript. Abhängig von [[yii\bootstrap5\BootstrapAsset]].
- [[yii\bootstrap5\BootstrapIconAsset|BootstrapIconAsset]] - enthält die Bootstrap Icons.
Verschiedene Anwendungsanforderungen erfordern verschiedene Bundles (bzw. Kombinationen).
Falls Sie nur auf das CSS angewiesen sind, reicht es wenn Sie [[yii\bootstrap5\BootstrapAsset]] laden.
Wenn Sie das Javascript verwenden möchten, müssen Sie [[yii\bootstrap5\BootstrapPluginAsset]] auch laden.
Falls Sie die Icons von Bootstrap 5 verwenden möchten, fügen Sie `twbs/bootstrap-icons` zu ihrem `composer.json` in die
`require` Sektion ein und registrieren Sie [[yii\bootstrap5\BootstrapIconAsset]] in Ihrer Applikation
> Tipp: Die meisten Widgets laden [[yii\bootstrap5\BootstrapPluginAsset]] automatisch.

View File

@ -0,0 +1,170 @@
Asset-Konfiguration
===================
Diese Erweiterung beruht auf [Bower](https://bower.io/) und/oder [NPM](https://www.npmjs.org/) Packages für die Asset Installation.
Bevor Sie diese Erweiterung einsetzen, sollten Sie entscheiden, auf welche Weise Sie diese Packages installieren möchten.
## Verwendung des asset-packagist Repository
Sie können [asset-packagist.or](https://asset-packagist.org) als Package-Quelle für die Bootstrap-Assets angeben.
Fügen Sie dazu folgende Zeilen zur `composer.json`-Datei ihres Projekts hinzu:
```json
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
```
Passen Sie `@npm` und `@bower` in der Konfiguration ihrer Applikation wie folgt an:
```php
return [
//...
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
//...
];
```
## Verwendung des composer asset Plugins
Installieren Sie das [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) global durch das Ausführen folgendes Befehls:
```
composer global require "fxp/composer-asset-plugin:^1.4.0"
```
Fügen Sie folgende Zeilen zur `composer.json`-Datei ihres Projekts hinzu um das Verzeichnis der Installation von Assets anzupassen
falls Sie möchten, das Yii sie verwaltet:
```json
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
```
Daraufhin können Sie den composer install bzw. update Befehl ausführen um die Boostrap Assets zu installieren.
> Warnung: Das Plugin `fxp/composer-asset-plugin` verlangsamt den `composer update` Befehl signifikant verglichen zur
"asset-packagist"-Methode.
## Direkte Verwendung des Bower/NPM Clients
Sie kännen die Bootstrap Assets direkt via Bower oder NPM Client installieren.
Fügen Sie dafür folgende Zeilen zur `package.json`-Datei Ihres Projekts hinzu:
```json
{
...
"dependencies": {
"bootstrap": "5.1",
...
}
...
}
```
Fügen Sie zur `composer.json`-Datei Ihres Projekts folgende Zeilen hinzu zum Verhindern von redundanten Bootstrap-Installationen:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
## Verwendung des CDN
Sie können die Bootstrap Assets vom [offiziellen CDN](https://www.bootstrapcdn.com) laden.
Fügen Sie zur `composer.json`-Datei Ihres Projekts folgende Zeilen hinzu zum Verhindern von redundanten Bootstrap-Installationen:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
Konfigurieren Sie die 'assetManager'-Komponente wie folgt (überschreibt die Bootstrap Asset mit den CDN Links):
```php
return [
'components' => [
'assetManager' => [
// override bundles to use CDN :
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'css' => [
'css/bootstrap.min.css'
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'js' => [
'js/bootstrap.bundle.min.js'
],
],
],
],
// ...
],
// ...
];
```
## Kompilieren von den .sass Dateien
Falls Sie den Bootstrap Quelltext direkt anpassen möchten, können Sie das CSS direkt von den Quell *.sass-Dateien kompilieren.
In diesem Fall macht die Installation der Bootstrap Assets via composer bzw. Bower/NPM kein Sinn, da Sie keine Dateien innerhalb
des 'vendor'-Verzeichnisses bearbeiten können.
Sie müssen die Bootstrap-Assets manuell herunterladen und sie irgendwo in Ihrem Projekt platzieren (z.B. 'assets/source/bootstrap').
Fügen Sie zur `composer.json`-Datei Ihres Projekts folgende Zeilen hinzu zum Verhindern von redundanten Bootstrap-Installationen:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
Konfigurieren Sie die 'assetManager'-Komponente wie folgt (überschreibt die Bootstrap Assets):
```php
return [
'components' => [
'assetManager' => [
// override bundles to use local project files :
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'css' => [
YII_ENV_DEV ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'js' => [
YII_ENV_DEV ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
]
],
],
],
// ...
],
// ...
];
```
Nach dem Verändern des Bootstrap Quellcodes, stellen Sie sicher, dass sie neu [kompiliert werden](https://getbootstrap.com/docs/5.1/getting-started/contribute/#using-npm-scripts), z.B. mittels `npm run dist`.

View File

@ -0,0 +1,17 @@
Grundlegende Verwendung
=======================
Yii verpackt die Bootstrap Basics nicht in PHP Code, da dass HTML selbst sehr einfach aufgebaut ist. Sie finden mehr
Informationen zur Verwendung der Basics unter [bootstrap documentation website](https://getbootstrap.com/docs/). Yii bietet
aber eine einfache Methode zur Einbindung der Bootstrap Assets in Ihre Seite durch das Hinzufügen einer Zeile zu `AppAsset.ph`
im `@app/assets` Verzeichnis:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // Diese Zeile
];
```
Die Verwendung von Bootstrap mittels des Yii Asset Manager erlaubt die Komprimierung und Kombinierung der Bootstrapressourcen
mit den Applikationsressourcen (falls nötig).

View File

@ -0,0 +1,30 @@
HTML helper
===========
Bootstrap führt viele konsistente HTML Strukturen ein, welche es erlauben, verschiedene visuelle Effekte einfach zu verwenden.
Ausschliesslich die komplexesten von ihnen sind mittels Widgets in dieser Erweiterung umgesetzt worden. Der Rest kann manuell
mittels HTML zusammengestellt werden.
Einige spezielle Bootstrap Markups sind implementiert im [[\yii\bootstrap5\Html]]-Helper.
Die [[\yii\bootstrap5\Html]]-Klasse ist eine Erweiterung der regulären [[\yii\helpers\Html]]-Klasse mit Anpassungen zur
Verwendung mit Bootstrap. Sie bietet verschiedene nützliche Methoden wie z.B.
- `staticControl()` - erlaubt das erstellen von "[statischen Feldern](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)"
Die [[\yii\bootstrap5\Html]]-Klasse erbt von der [[\yii\helpers\Html]]-Klasse und ersetzt diese dadurch vollumfänglich.
Sie benötigen folglich **nicht** beide in Ihren Views.
Beispiel:
```php
<?php
use yii\bootstrap5\Button;
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::tag('i', ['class' => 'fas fa-check']) . Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> Vorsicht: Verwechseln Sie [[\yii\bootstrap5\Html]] und [[\yii\helpers\Html]] Klassen nicht und bedenken Sie jeweils
welche Sie in Ihren Views verwenden.

View File

@ -0,0 +1,20 @@
Installation
============
## Mittels Composer Package
Der empfohlene Weg zur Installation dieser Erweiterung ist mittels [composer](https://getcomposer.org/download/).
Führen Sie entweder folgenden Befehlt aus
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
oder fügen Sie folgendes
```
"yiisoft/yii2-bootstrap5": "~1.0.0"
```
zur `require`-Sektion Ihrer `composer.json`-Datei hinzu.

View File

@ -0,0 +1,48 @@
Migration von yii2-bootstrap4
=============================
yii2-bootstrap4 ist eine komplette Überarbeitung des Projekts (siehe den Bootstrap 4 von Bootstrap 3 Migrationsguide).
Die größten Änderungen finden Sie hier zusammengefasst:
## Allgemein
* Der Namespace ist nun `yii\bootstrap5` anstatt `yii\bootstrap4`
* Die PHP Kompatibilität **ist beschränkt auf** `>=7.0`
* Der "Schließen"-Button von Widgets wie [[yii\bootstrap5\Alert|Alert]] oder [[yii\bootstrap5|Modal|Modal]] wird neu
via CSS dargestellt und hat keinen Inhalt mehr. Es ist daher beim Überschreiben sicherzustellen, dass die `btn-close`
Klasse entfernt wird und die benötigten Stile manuell gesetzt werden.
## Widgets / Klassen
### BaseHtml
### ActiveField
### ActiveForm
Es gibt eine neue Konstante [[yii\bootstrap5\ActiveForm::LAYOUT_FLOATING]]. Sie repräsentiert ein
[neues Formular-Layout](https://getbootstrap.com/docs/5.1/forms/floating-labels/) in Bootstrap 5.
### Breadcrumbs
### ButtonDropdown
### ButtonToolbar
### Carousel
### LinkPager
### Modal
### Nav
### NavBar
Es gibt nun die Möglichkeit der Erstellung einer [Offcanvas Navbar](https://getbootstrap.com/docs/5.1/components/navbar/#offcanvas).
Dies ist zu erreichen, indem man die Eigenschaft `$collapseOptions` des Widgets [[yii\bootstrap5\NavBar|Navbar]] auf `false`
und die Eigenschaft `$offcanvasOptions` auf ein array setzt (auch wenn leer).
### Tabs
### ToggleButtonGroup

View File

@ -0,0 +1,17 @@
Direkte Verwendung der .sass Dateien von Bootstrap
==================================================
Falls Sie das [Bootstrap CSS direkt in Ihre SASS-Dateien integerieren](https://getbootstrap.com/docs/4.1/getting-started/theming/#sass)
möchten, müssen Sie unter Umständen das Laden der Orginal Bootstrap-CSS-Dateien verhindern.
Dies können Sie durch das Leeren des `css`-Property in der [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]]-Datei bewerkstelligen.
Konfigurieren Sie dazu die `assetManager`-[Komponente](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md) wie folgt:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,97 @@
Yii widgets
===========
Die komplexesten Bootstrap Komponenten sind umgesetzt mittels Yii-Widget zur vereinfachten Verwendung und Integration
von Framework-Funktionen. Alle Widgets gehören zum `\yii\bootstrap5` Namespace:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## ActiveField: Weitere Input-Typen <span id="additional-fields"></span>
- [Range](https://getbootstrap.com/docs/5.1/forms/range/): `$form->rangeInput(['min' => 0, 'max' => 100, 'step' => 1])`
- [Color picker](https://getbootstrap.com/docs/5.1/forms/form-control/#color): `$form->colorInput()`
- [Switch](https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches): `$form->checkbox(['switch' => true])`
## Anpassen der Widget CSS-Klassen <span id="customizing-css-classes"></span>
Die Widgets erlauben die schnelle Erstellung von HTML-Markup der Bootstrap Komponenten.
Die Standard-CSS-Klassen einer bestimmten Komponente wird automatisch vom Widget hinzugefügt. Alle weiteren (optionalen)
Klassen können Sie mittels der Attribute des Widgets anpassen.
Verwenden Sie z.B. [[yii\bootstrap5\Button::options]] zur Anpassung des Aussehens des Buttons. Die Klasse `btn`, welche
benötigt vom Button Widget benötigt wird, wird automatisch hinzugefügt. Sie müssen lediglich die besondere Button-Klasse
hinzufügen:
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // produces class "btn btn-primary"
]);
```
Manchmal möchte man aber die Standard-Klasse ersetzen.
Das [[yii\bootstrap5\ButtonGroup]]-Widget beispielsweise verwendet standardmässig die 'btn-group' Klasse für den Container,
es müsste aber 'btn-group-vertical' erhalten zur vertikalen Ausrichtung.
Würden Sie wie oben nur die 'class'-Option verwenden, würde die 'btn-group-vertical'-Klasse zur 'btn-group'-Klasse hinzugefügt.
Zum Überschreiben der Standard-Klassen eines Widgets, müssen Sie die 'class'-Option unter dem Array-Schlüssel 'widget' angeben:
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // replaces 'btn-group' with 'btn-group-vertical'
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```
## Navbar widget <span id="navbar-widget"></span>
Das Navbar Widget hat so seine Eigenheiten. Bei der Verwendung des Widgets sollten Sie darauf achten, dass der Breakpoint,
ab welchem die Navigation zugeklappt wird (Mobile Navigation) sowie das Farbschema definiert sind.
Diese Definition geschieht über CSS Klassen. Die Standartwerte lauten `navbar-light bg-light` fürs Farbschema und
`navbar-expand-lg` für den brakpoint. Für weitere Informationen, konsultieren Sie die [Bootstrap Dokumentation](https://getbootstrap.com/docs/5.1/components/navbar/):
```php
Navbar::begin([
'options' => [
'class' => ['navbar-dark', 'bg-dark', 'navbar-expand-md']
]
]);
[...]
Navbar::end();
```
Falls Sie die Reihenfolge des Logos und des "Toggle Buttons" ändern möchten, können Sie dies wie folgt tun:
```php
Navbar::begin([
'brandOptions' => [
'class' => ['order-1']
],
'togglerOptions' => [
'class' => ['order-0']
]
]);
[...]
Navbar::end();
```

View File

@ -0,0 +1,29 @@
Extensión Twitter Bootstrap para Yii 2
======================================
La extensión incluye soporte para el marcado de [Bootstrap 5](https://getbootstrap.com/) y los componentes del framework
(también conocido como "Twitter Bootstrap"). Bootstrap es un excelente framework responsivo que puede acelerar
enormemente el proceso de desarrollo del lado del cliente.
El núcleo de Boostrap está representado por dos partes:
- Bases de CSS, tales como un sistema de cuadriculas, tipografía, clases de ayuda, y utilidades responsivas.
- Componentes listos para usar, tales como formularios, menús, paginación, cajas modales, tabs, etc.
Pasos Iniciales
---------------
* [Instalación](installation.md)
* [Uso Básico](basic-usage.md)
Uso
---
* [Yii widgets](usage-widgets.md)
* [Html helper](helper-html.md)
* [Asset Bundles](asset-bundles.md)
Temas Adicionales
-----------------
* [Usando directamente los ficheros .sass de Bootstrap](topics-sass.md)

View File

@ -0,0 +1,16 @@
Asset Bundles
=============
Bootstrap es una completa solución front-end, que incluye CSS, JavaScript, fuentes y mucho más.
Con el fin de permitir un control más flexible sobre los componentes de Bootstrap, esta extensión proporciona
varios asset bundles.
Ellos son:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - contiene unicamente los ficheros CSS principales.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - depende de [[yii\bootstrap5\BootstrapAsset]], contiene ficheros javascript.
Particularmente las aplicaciones pueden necesitar requerir diferentes usos de bundle (o combinación de bundle).
Si necesitas unicamente estilos CSS, [[yii\bootstrap5\BootstrapAsset]] será suficiente para ti. Sin embargo, si
quieres usar el JavaScript de Bootstrap, necesitas registrar [[yii\bootstrap5\BootstrapPluginAsset]].
> Consejo: la mayoría de los widgets registran automaticamente [[yii\bootstrap5\BootstrapPluginAsset]].

View File

@ -0,0 +1,16 @@
Uso Básico
==========
Yii no se ajusta a los conceptos básicos de bootstrap dentro del código PHP, desde el HTML es muy simple en si mismo
en este caso. Puedes encontrar los detalles sobre el uso de los conceptos básicos en la [web de bootstrap](https://getbootstrap.com/docs/). Yii proporciona una manera de incluir los assets de bootstrap en tus páginas añadiendo una única linea a `AppAsset.php` localizado en tu
directorio `@app/assets`:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // esta linea
];
```
Usando bootstrap a través de Yii asset manager permite que minimices los recursos y combinarlos con tus propios recursos
cuando lo necesites.

View File

@ -0,0 +1,28 @@
Html helper
===========
Bootstrap introduce muchas construcciones y esqueletos consistentes de HTML, que permiten crear diferentes efectos visuales.
Unicamente lo más complejo está cubierto por los widgets proporcionados en esta extensión. El resto debería ser
compuesto manualmente usando HTML directamente.
Sin embargo, algunas marcas especiales de Bootstrap son cubiertas por el helper [[\yii\bootstrap5\Html]].
[[\yii\bootstrap5\Html]] es una versión mejorada de la regular [[\yii\helpers\Html]] dedicada a las necesidades de Bootstrap.
Proporciona varios métodos útiles:
- `staticControl()` - permite renderizar formularios "[static controls](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)"
[[\yii\bootstrap5\Html]] hereda todas las funcionalidades disponibles en [[\yii\helpers\Html]] y puede usarse como sustituto,
así que no es necesario incluir ambos dentro de los archivos de tus vistas.
Por ejemplo:
```php
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> Atención: no confundas [[\yii\bootstrap5\Html]] con [[\yii\helpers\Html]], ten cuidado que clases estás usando dentro de tus vistas.

View File

@ -0,0 +1,20 @@
Instalación
===========
## Obteniendo el Paquete de Composer
La mejor manera para instalar esta extensión es a través de [composer](https://getcomposer.org/download/).
Ejecuta
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
o añade
```
"yiisoft/yii2-bootstrap": "~1.0.0"
```
en la sección require de tu fichero `composer.json`.

View File

@ -0,0 +1,17 @@
Usando directamente los ficheros .sass de Bootstrap
===================================================
Si deseas incluir el [css de Bootstrap directamente en tus ficheros sass](https://getbootstrap.com/getting-started/#customizing) puedes necesitar deshabilitar los ficheros css de bootstrap originales para ser cargados.
Puedes hacer esto mediante la configuración de la propiedad css de [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] asignando
un array vacio.
Para esto necesitas configurar el `assetManager` [componente de aplicación](https://github.com/yiisoft/yii2/blob/master/docs/guide-es/structure-application-components.md) como se muestra a continuación:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,66 @@
Yii widgets
===========
La mayoría de los componentes de bootstrap están encapsulados dentro de Yii widgets lo que permite una sintaxis
más robusta y poder integrarse con las características del framework. Todos los widgets pertenecen
al namespace `\yii\bootstrap5`:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## Personalización de las clases css para los widget <span id="customizing-css-classes"></span>
Los widgets permiten una rápida composición del HTML para los componentes de bootstrap que requieren las clases
CSS de bootstrap.
Las clases por defecto para un componente en particular serán añadidas automáticamente por los widgets, y las clases
opcionales que quieres personalizar son frecuentemente soportadas a través de las propiedades de los widgets.
Por ejemplo, puedas usar [[yii\bootstrap5\Button::options]] para personalizar la apariencia de un botón.
La clase 'btn' que se requiere para un botón será añadida automáticamente, por lo que no necesitas preocuparte
por ello.
Todo lo que necesitas es especificar una clase de botón en particular:
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // produce la clase "btn btn-primary"
]);
```
Sin embargo, a veces puede que tengas que remplazar las clases por defecto por las alternativas.
Por ejemplo, el widget [[yii\bootstrap5\ButtonGroup]] utiliza por defecto la clase 'btn-group' para el contenido del div, pero necesitas usar 'btn-group-vertical' en lugar de alinear los botones verticalmente.
El uso directo de la opción 'class' simplemente añade 'btn-group-vertical' a 'btn-group, el cual producirá un resultado incorrecto.
Con el fin de sobrescribir las clases por defecto de un widget, necesitas especificar la opción 'class' como un
array que contiene la definición de la clase personalizada bajo la clave 'widget':
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // remplaza 'btn-group' con 'btn-group-vertical'
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```

View File

@ -0,0 +1,31 @@
Yii 2 Twitter Bootstrap エクステンション
========================================
このエクステンションは、マークアップとコンポーネントのフレームワーク [Bootstrap 5](https://getbootstrap.com/) ("Twitter Bootstrap" としても知られています)
に対するサポートを提供します。
Bootstrap は優れた、レスポンシブなフレームワークであり、クライアント・サイドの開発プロセスを大いにスピードアップすることが出来るものです。
Bootstrap のコアは二つの部分によって表されます。
- CSS の基礎。例えば、グリッド・レイアウト・システム、タイポグラフィ、ヘルパ・クラス、レスポンシブ・ユーティリティなど。
- そのまま使えるコンポーネント。フォーム、メニュー、ページネーション、モーダル・ボックス、タブなど。
始めよう
--------
* [インストール](installation.md)
* [アセットのセットアップ](assets-setup.md)
* [基本的な使用方法](basic-usage.md)
使用方法
--------
* [Yii ウィジェット](usage-widgets.md)
* [Html ヘルパ](helper-html.md)
* [アセット・バンドル](asset-bundles.md)
追加のトピック
--------------
* [Bootstrap の .sass ファイルを直接に使う](topics-sass.md)
* [yii2-bootstrap からの移行](migrating-yii2-bootstrap.md)

View File

@ -0,0 +1,16 @@
アセット・バンドル
==================
Bootstrap は、CSS、JavaScript、フォントなどを含む複雑なフロントエンド・ソリューションです。
Bootstrap コンポーネントに対する最大限の柔軟な制御を可能にするために、このエクステンションは複数のアセット・バンドルを提供しています。
すなわち、
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - メインの CSS ファイルのみを含みます。
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - [[yii\bootstrap5\BootstrapAsset]] に依存し、javascript ファイルを含みます。
個々のアプリケーションは、その要求に応じて、異なるバンドル (またはバンドルの組み合わせ) を必要とするでしょう。
CSS のスタイルだけが必要なのであれば、[[yii\bootstrap5\BootstrapAsset]] だけで十分です。
しかし、Bootstrap の JavaScript を必要とする場合は、[[yii\bootstrap5\BootstrapPluginAsset]]
をも登録しなければなりません。
> Tip: ほとんどのウィジェットは [[yii\bootstrap5\BootstrapPluginAsset]] を自動的に登録します。

View File

@ -0,0 +1,176 @@
アセットのセットアップ
======================
Bootstrap エクステンションは、アセットのインストールについて、[Bower](https://bower.io/) および/または [NPM](https://www.npmjs.org/) のパッケージに依存しています。
Bootstrap パッケージを使う前に、これらのパッケージをあなたのプロジェクトにインストールする方法を決定しなければなりません。
## asset-packagist レポジトリを使う
[asset-packagist.org](https://asset-packagist.org) を Bootstrap アセットのソース・パッケージとしてセットアップすることが出来ます。
あなたのプロジェクトの `composer.json` に下記の行を追加して下さい。
```json
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
```
そして、アプリケーション構成で `@npm``@bower` を設定します。
```php
return [
//...
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
//...
];
```
## composer アセット・プラグインを使う
次のコマンドを使って [composer アセット・プラグイン](https://github.com/francoispluchino/composer-asset-plugin/) をグローバルにインストールします。
```
composer global require "fxp/composer-asset-plugin:^1.4.0"
```
Yii を使ってアセットを発行したい場合は、あなたのプロジェクトの `composer.json` に下記の行を追加して、
インストールされるパッケージが置かれるディレクトリを設定します。
```json
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
```
これで、`composer install/update` コマンドを実行すると、Bootstrap のアセットを取得することが可能になります。
> Note: `fxp/composer-asset-plugin` は asset-packagist に比べると、`composer update`
コマンドを著しく遅くさせます。
## Bower/NPM クライアントを直接に使う
Bower または NPM のクライアントを直接に使って Bootstrap のアセットをインストールすることが出来ます。
あなたのプロジェクトの `package.json` に次の行を追加して下さい。
```json
{
...
"dependencies": {
"bootstrap": "4.2.1",
...
}
...
}
```
あなたのプロジェクトの `package.json` に次の行を追加して、Bootstrap アセットの冗長なインストールを防止します。
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
## CDN を使う
[公式 CDN](https://www.bootstrapcdn.com) から Bootstrap アセットを使うことが出来ます。.
あなたのプロジェクトの `package.json` に次の行を追加して、Bootstrap アセットの冗長なインストールを防止します。
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
'assetManager' アプリケーション・コンポーネントを構成して、Bootstrap アセット・バンドルを CDN のリンクでオーバーライドします。
```php
return [
'components' => [
'assetManager' => [
// CDN を使うようにバンドルをオーバーライド
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'css' => [
'css/bootstrap.min.css'
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'js' => [
'js/bootstrap.bundle.min.js'
],
],
],
],
// ...
],
// ...
];
```
## .sass ファイルからコンパイルする
Bootstrap CSS ソースを直接にカスタマイズしたい場合、ソースの *.sass ファイルから CSS をコンパイルしたいと思うことがあるでしょう。
そのような場合は、Bootstrap アセットを Composer や Bower/NPM からインストールしても意味がありません。
なぜなら、`vendor` ディレクトリ内のファイルは変更できないからです。
Bootstrap アセットを手作業でダウンロードし、プロジェクト・ソース・コード内のどこか、
例えば `assets/source/bootstrap` フォルダに置かなければなりません。
あなたのプロジェクトの `package.json` に次の行を追加して、Bootstrap アセットの冗長なインストールを防止します。
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
'assetManager' アプリケーション・コンポーネントを構成して、Bootstrap アセット・バンドルをオーバーライドします。
```php
return [
'components' => [
'assetManager' => [
// バンドルをオーバーライドし、ローカル・プロジェクト・ファイルを使う
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'css' => [
YII_ENV_DEV ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'js' => [
YII_ENV_DEV ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
]
],
],
],
// ...
],
// ...
];
```
Bootsrap のソース・ファイルを変更した後は、例えば `npm run dist` を使って、必ず[コンパイル](https://getbootstrap.com/docs/5.1/getting-started/contribute/#using-npm-scripts)して下さい。

View File

@ -0,0 +1,17 @@
基本的な使用方法
================
Yii は bootstrap の基礎を PHP コードでラップすることをしていません。なぜなら、この場合の HTML コードがそれ自体として非常にシンプルだからです。
bootstrap の基礎を使用することに関する詳細は、[bootstrap ドキュメント・ウェブ・サイト](https://getbootstrap.com/docs/) で見ることが出来ます。
それでも、Yii はあなたのページに bootstrap のアセットをインクルードするための便利な方法を提供しています。
`@app/assets` ディレクトリに配置されている `AppAsset.php` に一行を加えるだけで大丈夫です。
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // この行です
];
```
Yii のアセットマネージャによって bootstrap を使うと、必要に応じて、bootstrap のリソースを最小化したり、
あなた自身のリソースと結合したりすることが出来ます。

View File

@ -0,0 +1,30 @@
Html ヘルパ
===========
Bootstrap は、一貫性の高い多数の HTML 構文ないしはスケルトンを導入して、さまざまな視覚的効果の生成を可能にしています。
このエクステンションによって提供されるウィジェットがカバーしているのは、その中の最も複雑なものだけです。
残りのものは、直接に HTML 構文を使って、手作業で構築しなければなりません。
ただし、いくつかの特別な Bootstrap マークアップについては、[[\yii\bootstrap5\Html]] によってカバーされています。
[[\yii\bootstrap5\Html]] は通常の [[\yii\helpers\Html]] の拡張版であり、Bootstrap の要求に特化して、
いくつかの便利なメソッドを提供するものです。例えば、
- `staticControl()` - フォームの "[static controls](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)" のレンダリングを可能にする
[[\yii\bootstrap5\Html]] は [[\yii\helpers\Html]] を継承しており、
その代替物として使うことが出来ますので、ビュー・ファイルの中で両方を使う必要はありません。
例えば、
```php
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> 注意: [[\yii\bootstrap5\Html]] と [[\yii\helpers\Html]] を混同してはいけません。
ビューの中でどちらのクラスを使っているのかに注意してください。

View File

@ -0,0 +1,19 @@
インストール
============
## Composer パッケージを取得する
このエクステンションをインストールするのに推奨される方法は [composer](https://getcomposer.org/download/) によるものです。
下記のコマンドを実行してください。
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
または、あなたの `composer.json` ファイルの `require` セクションに、
```
"yiisoft/yii2-bootstrap": "~1.0.0"
```
を追加してください。

View File

@ -0,0 +1,39 @@
yii2-bootstrap4 からの移行
=========================
yii2-bootstrap5 は、Bootstrap 4 から Bootstrap 5 への移行ガイドに従って、yii-bootstrap4 プロジェクト全体を大きく書き換えたものです。
最も注目すべき変更点を要約すると以下の通りです。
## 一般
* 名前空間は `yii\bootstrap4` から `yii\bootstrap5` に変更
## ウィジェット / クラス
### BaseHtml
### ActiveField
### ActiveForm
新しい定数[[yii\bootstrap5\ActiveForm::LAYOUT_FLOATING]]があります。 Bootstrap5で導入された[新しいフォームレイアウト](https://getbootstrap.com/docs/5.1/forms/floating-labels/)です。
### Breadcrumbs
### ButtonDropdown
### ButtonToolbar
### Carousel
### LinkPager
### Modal
### Nav
### NavBar
### Tabs
### ToggleButtonGroup

View File

@ -0,0 +1,17 @@
Bootstrap の .sass ファイルを直接に使う
=======================================
あなたが [Bootstrap CSS をあなたの sass ファイルに直接含める](https://getbootstrap.com/getting-started/#customizing) ことを望む場合は、
オリジナルの CSS ファイルがロードされないように無効化する必要があります。
[[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] の `css` プロパティを空に設定することによって、そうすることが出来ます。
そのためには、`assetManager` [アプリケーション・コンポーネント](https://github.com/yiisoft/yii2/blob/master/docs/guide-ja/structure-application-components.md) を以下のように構成します。
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,95 @@
Yii ウィジェット
================
複雑な bootstrap コンポーネントのほとんどは Yii ウィジェットでラップされて、より堅牢な構文を与えられ、フレームワークの諸機能と統合されています。
全てのウィジェットは `\yii\bootstrap5` 名前空間に属します。
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## ウィジェットの CSS クラスをカスタマイズする <span id="customizing-css-classes"></span>
これらのウィジェットを使うと、bootstrap CSS クラスの使用を要求する bootstrap コンポーネントのための HTML を素速く構成することが出来ます。特定のコンポーネントのデフォルトの CSS クラスはウィジェットによって自動的に追加されます。
そして、あなたがカスタマイズしたいであろうオプションの CSS クラスは、通常は、ウィジェットのプロパティによってサポートされています。
例えば、[[yii\bootstrap5\Button::options]] を使って、ボタンの外見をカスタマイズすることが出来ます。
このとき、ボタンに要求される 'btn' クラスは自動的に追加されますので、あなたが心配をする必要はありません。
特定のボタン・クラスを指定するだけで十分です。
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // "btn btn-primary" というクラスを生成
]);
```
しかしながら、時として、デフォルトのクラスを別のクラスで置き換える必要がある場合があります。
例えば、[[yii\bootstrap5\ButtonGroup]] は、コンテナの div に 'btn-group' をデフォルトで使用しますが、
ボタンを垂直に並べるために 'btn-group-vertical' を代りに使いたいことがあるでしょう。
単純に 'class' オプションを使うと、'btn-group-vertical' が 'btn-group' に追加されるだけで、正しくない結果が生成されることになります。
ウィジェットのデフォルトのクラスをオーバーライドするためには、'class' オプションに配列形式を使用して、'widget' キーの下にカスタマイズしたクラスの定義を指定しなければなりません。
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // 'btn-group' を 'btn-group-vertical' で置き換え
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```
## Navbar ウィジェット <span id="navbar-widget"></span>
Navbar ウィジェットには独特の癖があります。あなたは Navbar が折り畳まれるブレークポイントと
Navbar の全体的なスタイル (カラー・スキーム) を指定しなければなりません。
カラー・スキームと折り畳みのブレークポイントは CSS のクラスで変更することが出来ます。指定されない場合は、カラー・スキームは `navbar-light bg-light`
ブレークポイントは`navbar-expand-lg` がデフォルトとして採用されます。詳細な情報は、[Bootstrap documentation](https://getbootstrap.com/docs/5.1/components/navbar/) を参照して下さい。
```php
Navbar::begin([
'options' => [
'class' => ['navbar-dark', 'bg-dark', 'navbar-expand-md']
]
]);
[...]
Navbar::end();
```
モバイル向けナビゲーションでブランド (アイコン) とトグル・ボタンの位置を入れ替えたい場合は、次のようにすることが出来ます。
```php
Navbar::begin([
'brandOptions' => [
'class' => ['order-1']
],
'togglerOptions' => [
'class' => ['order-0']
]
]);
[...]
Navbar::end();
```

View File

@ -0,0 +1,29 @@
Extenção Twitter Bootstrap para Yii 2
=====================================
A extensão inclui suporte para marcação e componentes ao framework [Bootstrap 5](https://getbootstrap.com/)
(também conhecido como "Bootstrap Twitter"). Bootstrap é um excelente framework ágil, que pode acelerar bastante o
do lado do cliente do seu processo de desenvolvimento.
O núcleo do bootstrap é representado por duas partes:
- Noções básicas de estilo CSS, tais como um sistema de rede layout, tipografia, classes auxiliares, e os utilitários de resposta.
- Componentes prontos para usar, tais como formulários, menus, paginação, caixas de modais, guias, etc.
Iniciando
---------------
* [Instalação](installation.md)
* [uso Básico](basic-usage.md)
Uso
-----
* [Yii widgets](usage-widgets.md)
* [Html helper](helper-html.md)
* [Asset Bundles](asset-bundles.md)
Tópicos Adicionais
-----------------
* [Usando arquivos .sass do Bootstrap diretamente](topics-sass.md)

View File

@ -0,0 +1,14 @@
Asset Bundles
=============
Bootstrap é uma solução complexa para front-end, o qual inclue CSS, JavaScript, fontes e assim por diante.
A fim de permitir que você tenha controle mais flexível sobre componentes Bootstrap , esta extensão fornece vários asset bundles. Eles são:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - Contém apenas arquivos CSS.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - Depende de [[yii\bootstrap5\BootstrapAsset]], contem os arquivos JavaScript.
Necessidades de aplicações específicas podem exigir utilização de pacotes diferentes ( ou a combinação bundle).
Se você precisa apenas de estilos CSS, [[yii\bootstrap5\BootstrapAsset]] será o suficiente para você. No entanto , se
você quiser usar Bootstrap JavaScript, você precisa se registrar [[yii\bootstrap5\BootstrapPluginAsset]].
> Tip: a maioria dos widgets [[yii\bootstrap5\BootstrapPluginAsset]] registram automaticamente.

View File

@ -0,0 +1,17 @@
Uso Básico
===========
O Yii Não registra os componentes básicos do bootstrap em código PHP visto que esse HTML é muito simples, por si só.
Você pode encontrar detalhes sobre como usar o básico no [site documentação do Bootstrap] (https://getbootstrap.com/docs/). O Yii ainda fornece uma
forma conveniente para incluir assets de bootstrap em suas páginas com uma única linha adicionado ao arquivo `AppAsset.php` localizado no seu
diretório `@app/assets`:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // this line
];
```
Usando bootstrap através Yii assets lhe permite minimizar os seus recursos/fontes e combinar com seus próprios recursos/fontes quando
necessário.

View File

@ -0,0 +1,17 @@
Bootstrap introduz construções HTML mais consistentes e esqueletos, que permitem a criação de diferentes efeitos visuais. Apenas o mais complexos deles são cobertos por os widgets fornecidos com esta extensão . O restante deverá ser escrito manualmente usando escrita HTML direta. No entanto, vários casos especiais de marcação Bootstrap são cobertos pelo helper [[\yii\bootstrap5\Html]]. [[\yii\bootstrap5\Html]] é uma versão melhorada de [[\yii\helpers\Html]] dedicada à quem precisa do Bootstrap. Ele fornece vários métodos úteis :
- staticControl() - allows rendering of form "[static controls](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)"
[[\yii\bootstrap5\Html]] herda toda funcionalidade disponível em [[\yii\helpers\Html]] e pode ser usado como um substituto , para que você não precisa de ambos dentro de seus arquivos de views . Por exemplo:
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
Atenção: Não confunda [[\yii\bootstrap5\Html]] e [[\yii\helpers\Html]], tenha o cuidado de que classe você está usando dentro de seus arquivos de views.

View File

@ -0,0 +1,20 @@
Instalação
============
## Instalando através do composer
A maneira recomendada para instalar esta extensão é através do [composer](https://getcomposer.org/download/).
Então rode
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
Ou Adicione
```
"yiisoft/yii2-bootstrap": "~1.0.0"
```
na sessão de requirimentos do seu arquivo `composer.json`.

View File

@ -0,0 +1,18 @@
Usando arquivos .sass diretamente do Bootstrap
===========================================
Se você quiser incluir o [css do Bootstrap diretamente em seus arquivos sass] (https://getbootstrap.com/getting-started/#customizing)
talvez você precise desativar os arquivos css do Bootstrap originais que são carregados.
Você pode fazer isso definindo a propriedade css do [[yii \ inicialização \ BootstrapAsset | BootstrapAsset]] e deixe estar vazio.
Para isso, você precisa configurar o `assetManager` [application component](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md)
do seguinte modo:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,27 @@
Yii widgets
===========
A maioria dos componentes complexos do bootstrap são envolvidos em widgets Yii para permitir uma sintaxe mais robusta e integrar-se com
características estruturais do framework. Todos widgets pertencem ao namespace `\yii\bootstrap5`:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]

View File

@ -0,0 +1,28 @@
Расширение Twitter Bootstrap для Yii 2
======================================
Расширение включает поддержку разметки и компонентов фреймворка [Bootstrap 5](https://getbootstrap.com/) (также известного как "Twitter Bootstrap"). Bootstrap является прекрасным, отзывчивым фреймворком, который может значительно ускорить процесс разработки на стороне клиента.
Ядро Bootstrap представлено двумя частями:
- CSS основа, такая как система разметки, типографика, вспомогательные классы, и утилиты адаптивности.
- Готовые к использованию компоненты, такие как формы, меню, нумерация страниц, модальные окна, вкладки и т.д.
Как начать
----------
* [Установка](installation.md)
* [Основы использования](basic-usage.md)
Использование
------------
* [Виджеты Yii](usage-widgets.md)
* [Класс-помощник Html](helper-html.md)
* [Asset Bundles](asset-bundles.md)
Дополнительно
-------------
* [Использование .sass файлов Bootstrap напрямую](topics-sass.md)
* [Миграция с yii2-bootstrap4](migrating-yii2-bootstrap.md)

View File

@ -0,0 +1,12 @@
Asset Bundles
=============
Bootstrap - это комплексное front-end решение, включающее CSS, JavaScript, шрифты и т.д. Для того чтобы обеспечить гибкий контроль над компонентами Bootstrap, расширение предоставляет несколько Asset Bundles. Вот они:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - содержит CSS файлы.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - зависит от [[yii\bootstrap5\BootstrapAsset]], содержащий javascript файлы.
- [[yii\bootstrap5\BootstrapIconAsset|BootstrapIconAsset]] - содержит иконки.
Конкретные приложения могут потребовать различного использования. Если вам нужны только CSS-стили, то пакета [[yii\bootstrap5\BootstrapAsset]] будет достаточно. Тем не менее, если вы хотите использовать Bootstrap JavaScript, вам необходимо зарегистрировать [[yii\bootstrap5\BootstrapPluginAsset]], если вы хотите использовать Bootstrap Icons, вам необходимо зарегистрировать [[yii\bootstrap5\BootstrapIconAsset|BootstrapIconAsset]].
> Tip: большинство виджетов регистрируются с помощью [[yii\bootstrap5\BootstrapPluginAsset]] автоматически.

View File

@ -0,0 +1,13 @@
Базовое использование
===========
Yii не оборачивает базовый Bootstrap в PHP код, поскольку HTML, в этом случае, прост сам по себе. Вы можете найти подробную информацию о возможностях Bootstrap в [официальной документации](https://getbootstrap.com/docs/). Тем не менее, Yii обеспечивает удобный способ включения Bootstrap assets на страницах вашего приложения добавлением одной строки в файл `AppAsset.php`, расположенный в директории `@app/assets`:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // подключение Bootstrap
];
```
Использование загрузки Bootstrap через Yii Asset Manager позволяет минимизировать ресурсы и объединить с вашими собственными ресурсами, когда это будет необходимо.

View File

@ -0,0 +1,21 @@
Класс-помощник Html
===================
Bootstrap предоставляет множество последовательных HTML конструкции и каркасов, которые позволяют создавать различные визуальные эффекты. Только самые сложные из них передставлены виджетами, поставляемые с данным расширением. Остальные должны быть собраны вручную, используя HTML напрямую. Тем не менее, несколько специальных Bootstrap разметок предоставляются в помощнике [[\yii\bootstrap5\Html]]. [[\yii\bootstrap5\Html]] является расширенной версией [[\yii\helpers\Html]], удовлетворяющей потребности Bootstrap. Он предоставляет несколько полезных методов:
- `staticControl()` - позволяет отображать "[статические элементы управления](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)" формы
[[\yii\bootstrap5\Html]] наследует все функциональные возможности, доступные в [[\yii\helpers\Html]], и может быть использован в качестве замены в ваших представлениях. Например:
```php
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> Attention: не путайте [[\yii\bootstrap5\Html]] и [[\yii\helpers\Html]]! Следите за тем какой класс вы используете в своих представлениях.

View File

@ -0,0 +1,20 @@
Установка
=========
## Получение расширения через Composer
Предпочтительный способ установки расширения - через [Composer](https://getcomposer.org/download/).
Для этого запустите команду
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
или добавьте
```
"yiisoft/yii2-bootstrap5": "~2.0.0"
```
в секцию **require** вашего `composer.json`.

View File

@ -0,0 +1,50 @@
Миграция с yii2-bootstrap4
==============================
yii2-bootstrap5 является серьезной переработкой всего проекта (в соответствии с руководством по миграции с Bootstrap4 на Bootstrap5).
Наиболее заметные изменения кратко изложены ниже:
## General
* Изменение namespace с `yii\bootstrap4` на `yii\bootstrap5`
* Минимальная совместимая версия php **ограничена** `>=7.0`
* Кнопки закрытия виджетов, таких как [[yii\bootstrap5\Alert|Alert]] или [[yii\bootstrap5\Modal|Modal]], теперь отображаются
с помощью CSS и больше не содержат содержимого. Поэтому обязательно удалите класс "btn-close" и самостоятельно установите соответствующие стили, если вы его переопределяли.
## Widgets / Classes
### BaseHtml
### ActiveField
### ActiveForm
Новая константа [[yii\bootstrap5\ActiveForm::LAYOUT_FLOATING]]. Это
[new form layout](https://getbootstrap.com/docs/5.1/forms/floating-labels/) введен в Bootstrap 5.
### Breadcrumbs
### ButtonDropdown
### ButtonToolbar
### Carousel
### LinkPager
### Modal
Заменить `data-target` и `data-toggle` на `data-bs-target` и `data-bs-toggle`
### Nav
### NavBar
Теперь есть возможность создать [offcanvas navbar](https://getbootstrap.com/docs/5.1/components/navbar/#offcanvas).
Вы можете добиться этого, установив для параметра `$collapseOptions` значение `false` в виджете [[yii\bootstrap5\NavBar|Navbar]] и
`$offcanvasOptions`, значение пустого массива.
### Tabs
### ToggleButtonGroup

View File

@ -0,0 +1,14 @@
Использование .sass файлов Bootstrap напрямую
=============================================
Если вы хотите включить [Bootstrap CSS непосредственно в ваши sass-файлы](https://getbootstrap.com/getting-started/#customizing), вам может понадобиться исключить исходные css-файлы Bootstrap из загрузки. Вы можете сделать это, установив пустым свойство `css` пакета [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]]. Для этого вам необходимо настроить [компонент приложения](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md) `assetManager` следующим образом:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [], // исключение исходных css-файлов из загрузки
]
]
]
```

View File

@ -0,0 +1,92 @@
Виджеты Yii
===========
Большинство сложных Bootstrap компонентов обернуты в виджеты Yii, чтобы обеспечить более надежный синтаксис и интеграцию с особенностями фреймворка. Все виджеты относятся к пространству имен `\yii\bootstrap5`:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## ActiveField: дополнительные поля <span id="additional-fields"></span>
- [Диапазон](https://getbootstrap.com/docs/5.1/forms/range/): `$form->rangeInput(['min' => 0, 'max' => 100, 'step' => 1])`
- [Выбор цвета](https://getbootstrap.com/docs/5.1/forms/form-control/#color): `$form->colorInput()`
- [Переключатель](https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches): `$form->checkbox(['switch' => true])`
## Настройка CSS классов виджетов <span id="customizing-css-classes"></span>
Виджеты позволяют быстро создавать HTML Bootstrap компоненты, которые требуют CSS классы Bootstrap. Классы по умолчанию, для конкретного компонента, будут добавлены автоматически виджетом, и необязательные классы, которые вы можете настроить, как правило, поддерживаются через свойства виджета.
Например, вы можете использовать [[yii\bootstrap5\Button::options]] чтобы настроить внешний вид кнопки. Класс `btn`, который требуется для кнопки, будет добавлен автоматически. Все, что вам нужно, это указать конкретный класс кнопки:
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // устанавливает класс "btn btn-primary"
]);
```
Тем не менее, иногда вам может понадобиться заменить классы по умолчанию альтернативными. Например, виджет [[yii\bootstrap5\ButtonGroup]] использует класс `btn-group` для контейнера `div` по умолчанию, но вам, возможно, придётся использовать `btn-group-vertical` чтобы выровнять кнопки по вертикали. Добавление `btn-group-vertical` в параметр `class` приведет к неправильному результату. Для того, чтобы переопределить классы виджета по умолчанию, необходимо указать параметр `class` как массив, содержащий определение класса, настроенное в ключе `widget`:
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // заменяет класс 'btn-group' на 'btn-group-vertical'
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```
## Виджет навигационной панели <span id="navbar-widget"></span>
Виджет навигационной панели имеет свои особенности. Вы должны задать точку останова (разрешение при котором панель отображается в свернутом виде)
и основной стиль отображения (цветовая схема) для панели.
Вы можете изменить цветовую схему и точку останова с помощью CSS классов. По умолчанию, используется цветовая схема
`navbar-light bg-light` и точка останова `navbar-expand-lg`. Для получения доп. информации, смотрите [документацию Bootstrap](https://getbootstrap.com/docs/5.1/components/navbar/):
```php
Navbar::begin([
'options' => [
'class' => ['navbar-dark', 'bg-dark', 'navbar-expand-md']
]
]);
[...]
Navbar::end();
```
Если Вы хотите повернуть бренд (значок) и переключить положение кнопок в мобильной навигации, то можете сделать это следующим образом:
```php
Navbar::begin([
'brandOptions' => [
'class' => ['order-1']
],
'togglerOptions' => [
'class' => ['order-0']
]
]);
[...]
Navbar::end();
```

View File

@ -0,0 +1,27 @@
Розширення Twitter Bootstrap для Yii 2
======================================
З коробки Yii включає підтримку розмітки [Bootstrap 5](https://getbootstrap.com/) та компонентів фреймворку
(також відомий як "Twitter Bootstrap"). Bootstrap є чудовим, адаптивним фреймворком, який може значно прискорити
процес розробки клієнтської частини сайту.
Ядро Bootstrap представлене двома частинами:
- Основи CSS, такі як система макету сітки, типографія, допоміжні класи і адаптивні утиліти.
- Готові до використання компоненти, такі як форми, меню, нумерація сторінок (pagination), модальні вікна, вкладки (tabs) і т.д.
Початок роботи
--------------
* [Встановлення](installation.md)
* [Основи використання](basic-usage.md)
Використання
------------
* [Віджети Yii](usage-widgets.md)
Додаткові теми
--------------
* [Використання .sass файлів в Bootstrap](topics-sass.md)

View File

@ -0,0 +1,16 @@
Основи використання
===================
Yii не загортає основи bootstrap в код PHP, оскільки в цьому випадку, сам по собі HTML є дуже простим.
Ви можете знайти детальну інформацію щодо використання основ на [сайті документації bootstrap](https://getbootstrap.com/docs/).
Проте Yii забезпечує зручний спосіб підключення ресурсів bootstrap до ваших сторінок за допомогою додання всього одного рядка до файлу
`AppAsset.php`, розташованого в каталозі `@app/assets`:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // цей рядок
];
```
Використання bootstrap через менеджер ресурсів Yii дозволяє мінімізувати свої ресурси і обʼєднати із вашими власними ресурсами коли це необхідно.

View File

@ -0,0 +1,20 @@
Встановлення
============
## Отримання пакету Composer
Кращим способом для встановлення даного розширення є встановлення через [composer](https://getcomposer.org/download/).
Запустіть
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
або додайте
```
"yiisoft/yii2-bootstrap": "~1.0.0"
```
до потрібного розділу вашого файлу `composer.json`.

View File

@ -0,0 +1,18 @@
Використання .sass файлів в Bootstrap
=====================================
Якщо ви хочете включити [CSS Bootstrap напряму до ваших sass файлів](https://getbootstrap.com/getting-started/#customizing)
вам необхідно відключити завантаження оригінальних css файлів bootstrap.
Ви можете зробити це, встановивши CSS властивість [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] порожньою.
Для цього вам необхідно налаштувати [компонент додатка](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md)
`assetManager` наступним чином:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,27 @@
Віджети Yii
===========
Найбільш складні компоненти bootstrap загорнуті в віджети Yii, щоб забезпечити більш надійний синтаксис
та інтегрувати його з можливостями фреймворку. Всі віджети належать до простору імен `\yii\bootstrap5`:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]

View File

@ -0,0 +1,29 @@
基于Yii 2 的 Twitter Bootstrap 扩展
=====================================
扩展包括对 [Bootstrap 5](https://getbootstrap.com/) 标记和组件框架的支持
也称为“Twitter Bootstrap”。 Bootstrap是一个优秀的响应式框架可以大大加快
客户端的开发过程。
Bootstrap的核心由两部分组成
- 基础CSS样式如栅格化布局排版帮助类和响应式工具。
- 开箱即用的组件,如表单,菜单,分页,模态框,标签等。
起步
---------------
* [安装](installation.md)
* [基本用法](basic-usage.md)
使用
-----
* [Yii 小部件](usage-widgets.md)
* [Html 助手](helper-html.md)
* [Asset Bundles资源包](asset-bundles.md)
其他
-----------------
* [直接使用Bootstrap的.sass文件](topics-sass.md)

View File

@ -0,0 +1,14 @@
资源包
=============
Bootstrap是一个复杂的前端解决方案其中包括 CSS JavaScript ,字体等。
为了灵活的控制 Bootstrap 组件,此扩展提供了多个资源包。
如下:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - 只包含主要的 CSS 文件.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - 包含 javascript 文件, 依赖于 [[yii\bootstrap5\BootstrapAsset]] .
特定的应用可能需要加载不同的资源包,(或者资源包组合).
如果只需要 CSS 文件, 引入 [[yii\bootstrap5\BootstrapAsset]] 即可. 但是, 如果需要使用 Bootstrap 的 JavaScript, 则需要引入 [[yii\bootstrap5\BootstrapPluginAsset]].
> 提示:大多数小部件会自动注册到 [[yii\bootstrap5\BootstrapPluginAsset]] 。

View File

@ -0,0 +1,13 @@
使用
===========
Yii不会将 bootstrap 合并到PHP代码中因为HTML本身是非常简单的。猛击 [bootstrap 文档页](https://getbootstrap.com/docs/) 查看如何使用 bootstrap. 但是 Yii 还是提供了在框架中更为方便的管理和使用 bootstrap的方式`@app/assets` 路径下的 `AppAsset.php` 文件中,添加如下代码即可:
```php
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap5\BootstrapAsset', // this line
];
```
通过 Yii 的资源管理器asset manager引入 bootstrap ,可最小化的引入 bootstrap 并在需要时合并自定义资源文件一起使用。

View File

@ -0,0 +1,26 @@
Html 助手
===========
Bootstrap 引入了许多一致的 HTML 结构和骨架,允许创建不同的视觉效果。
只有最复杂的部分由此扩展提供的小部件覆盖。 其余应使用直接 HTML 手动组合。
但是, 有些特殊的 Bootstrap 标签被 [[\yii\bootstrap5\Html]] 重载.
[[\yii\bootstrap5\Html]] 是基于 Bootstrap 的 [[\yii\helpers\Html]] 增强版.
它提供了很多实用的方法,例如:
- `staticControl()` - 生成表单静态组件 "[static controls](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)"
[[\yii\bootstrap5\Html]] 继承了 [[\yii\helpers\Html]] 的所有功能,所以不需要在视图文件中同时引入这两个文件,如果需要,仅使用 [[\yii\bootstrap5\Html]] 即可.
例如:
```php
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> 注意: 不要混淆 [[\yii\bootstrap5\Html]] 和 [[\yii\helpers\Html]], 一定注意你在视图中引入和使用的类.

View File

@ -0,0 +1,18 @@
安装
============
## 获取 Composer 包
安装此扩展的首选方式是通过 [composer](https://getcomposer.org/download/).
直接运行
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
或者在项目目录的 `composer.json` 文件中添加如下代码
```
"yiisoft/yii2-bootstrap": "~1.0.0"
```

View File

@ -0,0 +1,17 @@
直接使用Bootstrap的.sass文件
=======================================
如果引入 [直接使用Bootstrap的.sass文件](https://getbootstrap.com/getting-started/#customizing)
则需要禁用原始加载的 css 文件.
通过设置 [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] 的 css 属性为空即可.
为此,需要配置 `assetManager` [应用组件](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md) 为如下:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,58 @@
Yii 小部件
===========
大多数复杂的 bootstrap 组件被包装到 Yii 小部件中,以允许更强大的语法并与框架特性集成。 所有小部件都在命名空间 `\yii\bootstrap5` 下:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## 自定义小部件CSS类 <span id="customizing-css-classes"></span>
这些小部件可以快速构建基于 bootstrap CSS 样式的 bootstrap 组件,并直接生成 HTML 代码。
特定组件的默认样式是自动添加的,也可以通过修改部件属性添加自定义样式类。
例如, 使用 [[yii\bootstrap5\Button::options]] 创建按钮。
按钮中的 `btn` 样式将会被自动添加。只要再添加自己所需的按钮样式即可:
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // produces class "btn btn-primary"
]);
```
但是,有的时候需要将默认样式替换为自定义样式。
例如, 小部件 [[yii\bootstrap5\ButtonGroup]] 默认使用 'btn-group' 类作为 div 容器的默认样式,但是我们希望使用 'btn-group-vertical' 作为默认样式以实现按钮组的垂直居中。
直接在 'class' 选项中添加 'btn-group-vertical' 是替换不了 'btn-group' 的。
为了重载组件的默认样式,需要在 'class' 选项中的 'widget' 选项中定义即可:
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // replaces 'btn-group' with 'btn-group-vertical'
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```

View File

@ -0,0 +1,31 @@
Twitter Bootstrap Extension for Yii 2
=====================================
The extension includes support for the [Bootstrap 5](https://getbootstrap.com/) markup and components framework
(also known as "Twitter Bootstrap"). Bootstrap is an excellent, responsive framework that can greatly speed up the
client-side of your development process.
The core of Bootstrap is represented by two parts:
- CSS basics, such as a grid layout system, typography, helper classes, and responsive utilities.
- Ready to use components, such as forms, menus, pagination, modal boxes, tabs etc.
Getting Started
---------------
* [Installation](installation.md)
* [Assets Setup](assets-setup.md)
* [Basic Usage](basic-usage.md)
Usage
-----
* [Yii widgets](usage-widgets.md)
* [Html helper](helper-html.md)
* [Asset Bundles](asset-bundles.md)
Additional topics
-----------------
* [Using the .sass files of Bootstrap directly](topics-sass.md)
* [Migrating from yii2-bootstrap](migrating-yii2-bootstrap.md)

View File

@ -0,0 +1,18 @@
Asset Bundles
=============
Bootstrap is a complex front-end solution, which includes CSS, JavaScript, fonts and so on.
In order to allow you the most flexible control over Bootstrap components, this extension provides several asset bundles.
They are:
- [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] - contains only the main CSS files.
- [[yii\bootstrap5\BootstrapPluginAsset|BootstrapPluginAsset]] - depends on [[yii\bootstrap5\BootstrapAsset]], contains the javascript files.
- [[yii\bootstrap5\BootstrapIconAsset|BootstrapIconAsset]] - contains Bootstrap icons.
Particular application needs may require different bundle (or bundle combination) usage.
If you only need CSS styles, [[yii\bootstrap5\BootstrapAsset]] will be enough for you. However, if
you intend to use Bootstrap JavaScript, you will need to register [[yii\bootstrap5\BootstrapPluginAsset]]
as well. If you'd like to use the Bootstrap icons, you'll need to add `twbs/bootstrap-icons` package to your
`composer.json` and register [[yii\bootstrap5\BootstrapIconAsset]] in your application.
> Tip: most of the widgets register [[yii\bootstrap5\BootstrapPluginAsset]] automatically.

View File

@ -0,0 +1,176 @@
Assets Setup
============
This extensions relies on [Bower](https://bower.io/) and/or [NPM](https://www.npmjs.org/) packages for the asset installation.
Before using this package you should decide in which way you will install those packages in your project.
## Using asset-packagist repository
You can setup [asset-packagist.org](https://asset-packagist.org) as package source for the Bootstrap assets.
In the `composer.json` of your project, add the following lines:
```json
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
```
Adjust `@npm` and `@bower` in you application configuration:
```php
return [
//...
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
//...
];
```
## Using composer asset plugin
Install [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) globally, using following command:
```
composer global require "fxp/composer-asset-plugin:^1.4.0"
```
Add the following lines to `composer.json` of your project to adjust directories where the installed packages
will be placed, if you want to publish them using Yii:
```json
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
```
Then you can run composer install/update command to pick up Bootstrap assets.
> Note: `fxp/composer-asset-plugin` significantly slows down the `composer update` command in comparison
to asset-packagist.
## Using Bower/NPM client directly
You can install Bootstrap assets directly via Bower or NPM client.
In the `package.json` of your project, add the following lines:
```json
{
...
"dependencies": {
"bootstrap": "5.1",
...
}
...
}
```
In the `composer.json` of your project, add the following lines in order to prevent redundant Bootstrap asset installation:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
## Using CDN
You may use Bootstrap assets from [official CDN](https://www.bootstrapcdn.com).
In the `composer.json` of your project, add the following lines in order to prevent redundant Bootstrap asset installation:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
Configure 'assetManager' application component, overriding Bootstrap asset bundles with CDN links:
```php
return [
'components' => [
'assetManager' => [
// override bundles to use CDN :
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'css' => [
'css/bootstrap.min.css'
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => null,
'baseUrl' => 'https://cdn.jsdelivr.net/npm/bootstrap@5.1/dist/',
'js' => [
'js/bootstrap.bundle.min.js'
],
],
],
],
// ...
],
// ...
];
```
## Compiling from the .sass files
If you want to customize the Bootstrap CSS source directly, you may want to compile it from source *.sass files.
In such case installing Bootstrap assets from Composer or Bower/NPM makes no sense, since you can not modify files
inside 'vendor' directory.
You'll have to download Bootstrap assets manually and place them somewhere inside your project source code,
for example in the 'assets/source/bootstrap' folder.
In the `composer.json` of your project, add the following lines in order to prevent redundant Bootstrap asset installation:
```json
"replace": {
"npm-asset/bootstrap": ">=5.1"
},
```
Configure 'assetManager' application component, overriding Bootstrap asset bundles:
```php
return [
'components' => [
'assetManager' => [
// override bundles to use local project files :
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'css' => [
YII_ENV_DEV ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
],
],
'yii\bootstrap5\BootstrapPluginAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'js' => [
YII_ENV_DEV ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
]
],
],
],
// ...
],
// ...
];
```
After you make changes to Bootstrap's source files, make sure to [compile them](https://getbootstrap.com/docs/5.1/getting-started/contribute/#using-npm-scripts), eg. using `npm run dist`.

View File

@ -0,0 +1,18 @@
Basic Usage
===========
Yii doesn't wrap the Bootstrap basics into PHP code since HTML is very simple by itself in this case. You can find details
about using the basics at [Bootstrap documentation](https://getbootstrap.com/docs/). Still Yii provides a convenient
way to include Bootstrap assets in your pages with a line(s) added to `@app/assets/AppAsset.php`(basic application):
```php
public $depends = [
<...>
yii\bootstrap5\BootstrapAsset::class,
// optional, Bootstrap icons
// yii\bootstrap5\BootstrapIconAsset::class
];
```
Using Bootstrap through Yii asset manager allows you to minimize its resources and combine with your own resources when
needed.

View File

@ -0,0 +1,30 @@
Html helper
===========
Bootstrap introduces many consistent HTML constructions and skeletons, which allow creating different visual effects.
Only the most complex of them are covered by the widgets provided with this extension. The rest should be composed manually
using direct HTML composition.
However, several special Bootstrap markup cases are covered by the [[\yii\bootstrap5\Html]] helper.
[[\yii\bootstrap5\Html]] is an enhanced version of the regular [[\yii\helpers\Html]] dedicated to the Bootstrap needs.
It provides some useful methods like:
- `staticControl()` - allows rendering of form "[static controls](https://getbootstrap.com/docs/5.1/forms/form-control/#readonly-plain-text)"
As [[\yii\bootstrap5\Html]] extends [[\yii\helpers\Html]], it can be used as a substitute, so you don't need them both
inside your view files.
For example:
```php
<?php
use yii\bootstrap5\Html;
?>
<?= Button::widget([
'label' => Html::encode('Save & apply'),
'encodeLabel' => false,
'options' => ['class' => 'btn-primary'],
]); ?>
```
> Attention: do not confuse [[\yii\bootstrap5\Html]] and [[\yii\helpers\Html]], be careful of which class
you are using inside your views.

View File

@ -0,0 +1,20 @@
Installation
============
## Getting Composer package
The preferred way to install this extension is through [composer](https://getcomposer.org/download/).
Either run
```
php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5
```
or add
```
"yiisoft/yii2-bootstrap5": "~1.0.0"
```
to the require section of your `composer.json` file.

View File

@ -0,0 +1,50 @@
Migrating from yii2-bootstrap4
==============================
yii2-bootstrap5 is a major rewrite of the entire project (according Bootstrap 5 to Bootstrap 4 migration guide).
The most notable changes are summarized below:
## General
* The namespace is `yii\bootstrap5` instead of `yii\bootstrap4`
* The php compatibility **is limited to** `>=7.0`
* The close buttons of widgets like [[yii\bootstrap5\Alert|Alert]] or [[yii\bootstrap5|Modal|Modal]] now gets rendered
via CSS and does not have any content anymore. So be sure to remove `btn-close` class and set appropriate styles yourself
if you override it.
## Widgets / Classes
### BaseHtml
### ActiveField
### ActiveForm
There is a new constant [[yii\bootstrap5\ActiveForm::LAYOUT_FLOATING]]. It's a
[new form layout](https://getbootstrap.com/docs/5.1/forms/floating-labels/) introduced in Bootstrap 5.
### Breadcrumbs
### ButtonDropdown
### ButtonToolbar
### Carousel
### LinkPager
### Modal
Change `data-target` and `data-toggle` to `data-bs-target` and `data-bs-toggle`
### Nav
### NavBar
There is now the possibility to create an [offcanvas navbar](https://getbootstrap.com/docs/5.1/components/navbar/#offcanvas).
You can achieve this by setting the `$collapseOptions` to `false` in [[yii\bootstrap5\NavBar|Navbar]] widget and the
`$offcanvasOptions` to at least an empty array.
### Tabs
### ToggleButtonGroup

View File

@ -0,0 +1,17 @@
Using the .sass files of Bootstrap directly
===========================================
If you want to include the [Bootstrap css directly in your sass files](https://getbootstrap.com/getting-started/#customizing)
you may need to disable the bootstrap css files loaded by this extension.
You can do this by setting the css property of [[yii\bootstrap5\BootstrapAsset|BootstrapAsset]] to be empty.
For this, you need to configure the `assetManager` [application component](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md) as follows:
```php
'assetManager' => [
'bundles' => [
'yii\bootstrap5\BootstrapAsset' => [
'css' => [],
]
]
]
```

View File

@ -0,0 +1,100 @@
Yii widgets
===========
Most complex bootstrap components are wrapped into Yii widgets to allow more robust syntax and integrate with
framework features. All widgets belong to `\yii\bootstrap5` namespace:
- [[yii\bootstrap5\Accordion|Accordion]]
- [[yii\bootstrap5\ActiveField|ActiveField]]
- [[yii\bootstrap5\ActiveForm|ActiveForm]]
- [[yii\bootstrap5\Alert|Alert]]
- [[yii\bootstrap5\Breadcrumbs|Breadcrumbs]]
- [[yii\bootstrap5\Button|Button]]
- [[yii\bootstrap5\ButtonDropdown|ButtonDropdown]]
- [[yii\bootstrap5\ButtonGroup|ButtonGroup]]
- [[yii\bootstrap5\ButtonToolbar|ButtonToolbar]]
- [[yii\bootstrap5\Carousel|Carousel]]
- [[yii\bootstrap5\Dropdown|Dropdown]]
- [[yii\bootstrap5\LinkPager|LinkPager]]
- [[yii\bootstrap5\Modal|Modal]]
- [[yii\bootstrap5\Nav|Nav]]
- [[yii\bootstrap5\NavBar|NavBar]]
- [[yii\bootstrap5\Offcanvas|Offcanvas]]
- [[yii\bootstrap5\Popover|Popover]]
- [[yii\bootstrap5\Progress|Progress]]
- [[yii\bootstrap5\Tabs|Tabs]]
- [[yii\bootstrap5\Toast|Toast]]
- [[yii\bootstrap5\ToggleButtonGroup|ToggleButtonGroup]]
## ActiveField: additional fields <span id="additional-fields"></span>
- [Range](https://getbootstrap.com/docs/5.1/forms/range/): `$form->rangeInput(['min' => 0, 'max' => 100, 'step' => 1])`
- [Color picker](https://getbootstrap.com/docs/5.1/forms/form-control/#color): `$form->colorInput()`
- [Switch](https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches): `$form->checkbox(['switch' => true])`
## Customizing widget CSS classes <span id="customizing-css-classes"></span>
The widgets allow quick composition of the HTML for the bootstrap components that require the bootstrap CSS classes.
The default classes for a particular component will be added automatically by the widget, and the optional classes that you may want to customize are usually supported through the properties of the widget.
For example, you may use [[yii\bootstrap5\Button::options]] to customize the appearance of a button.
The class 'btn' which is required for a button will be added automatically, so you don't need to worry about it.
All you need is specify a particular button class:
```php
echo Button::widget([
'label' => 'Action',
'options' => ['class' => 'btn-primary'], // produces class "btn btn-primary"
]);
```
However, sometimes you may need to replace the default classes with the alternative ones.
For example, the widget [[yii\bootstrap5\ButtonGroup]] uses 'btn-group' class for the container div by default,
but you may need to use 'btn-group-vertical' instead to align the buttons vertically.
Using a plain 'class' option simply adds 'btn-group-vertical' to 'btn-group', which will produce an incorrect result.
In order to override the default classes of a widget, you need to specify the 'class' option as an array that contains the customized class definition under the 'widget' key:
```php
echo ButtonGroup::widget([
'options' => [
'class' => ['widget' => 'btn-group-vertical'] // replaces 'btn-group' with 'btn-group-vertical'
],
'buttons' => [
['label' => 'A'],
['label' => 'B'],
]
]);
```
## Navbar widget <span id="navbar-widget"></span>
The navbar widget has its peculiarities. You should define at which breakpoint the navbar collapses and the generic
style of navbar (color scheme).
You can change the color scheme and the collapse breakpoint with css classes. If not defined, the scheme defaults to
`navbar-light bg-light` and the breakpoint to `navbar-expand-lg`. For more information, see [Bootstrap documentation](https://getbootstrap.com/docs/5.1/components/navbar/):
```php
Navbar::begin([
'options' => [
'class' => ['navbar-dark', 'bg-dark', 'navbar-expand-md']
]
]);
[...]
Navbar::end();
```
If you'd like to flip the brand (icon) and toggle button positions in mobile navigation, you can do this like this:
```php
Navbar::begin([
'brandOptions' => [
'class' => ['order-1']
],
'togglerOptions' => [
'class' => ['order-0']
]
]);
[...]
Navbar::end();
```