Bootstrap4 ใน Yii Framework 2 นั้นจะมาใน Yii version 2.1 ซึ่งก็คงต้องรออีกสักระยะ และประกอบกับ Bootstrap4 เอง ณ ตอนนี้ก็ยังเป็น version beta อยู่ แต่ถ้าหากว่าเราต้องการใช้งาน Bootstrap4 ใน Yii 2.0.xx แล้วล่ะก็ยังสามารถใช้งานได้เช่นกัน
ในบทเรียนรู้นี้เรามาสร้าง layout ที่ใช้งาน Bootstrap4 beta กันนะครับ โดยเริ่มจากแก้ไขไฟล์ composer.json ส่วนของ require ดังนี้
"bower-asset/bootstrap": "~4.0.0@beta",
"yiisoft/yii2-bootstrap": "2.1.x-dev",
ปรับแต่งไฟล์ frontend/views/layouts/main.php
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'eOffice',
'renderInnerContainer' => false,
'options' => [
'class' => 'navbar navbar-dark bg-primary navbar-expand-md'
]
]);
$menuItems = [
['label' => 'หน้าหลัก', 'url' => ['/site/index']],
['label' => 'เกี่ยวกับ', 'url' => ['/site/about']],
['label' => 'ติดต่อ', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'สมัครสมาชิก', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'เข้าสู่ระบบ', 'url' => ['/site/login']];
} else {
$menuItems[] = '<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
'ออกจากระบบ (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']
)
. Html::endForm()
. '</li>';
}
echo Nav::widget([
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container-fluid">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
'tag' => 'ol',
'itemTemplate' => "<li class=\"breadcrumb-item\">{link}</li>\n",
'activeItemTemplate' => "<li class=\"breadcrumb-item active\">{link}</li>\n"
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container-fluid">
<div class="row">
<div class="col-6">
© หน่วยงานของฉัน <?= date('Y') ?>
</div>
<div class="col-6 text-right">
<?=Html::a('HanumanIT Co., Ltd.', 'https://hanumanit.co.th', ['target' => '_blank', 'title' => 'พัฒนาโดย บริษัท หนุมานไอที จำกัด'])?>
</div>
</div>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
ปรับแต่ง frontend/web/css/site.css
html,
body {
height: 100%;
}
.wrap {
min-height: 100%;
height: auto;
margin: 0 auto -60px;
padding: 0 0 60px;
}
.wrap > .container-fluid {
padding: 20px 15px 20px;
}
.footer {
height: 60px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
padding-top: 20px;
}
.jumbotron {
text-align: center;
background-color: transparent;
}
.jumbotron .btn {
font-size: 21px;
padding: 14px 24px;
}
.not-set {
color: #c55;
font-style: italic;
}
/* add sorting icons to gridview sort links */
a.asc:after, a.desc:after {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
padding-left: 5px;
}
a.asc:after {
content: "\e151";
}
a.desc:after {
content: "\e152";
}
.sort-numerical a.asc:after {
content: "\e153";
}
.sort-numerical a.desc:after {
content: "\e154";
}
.sort-ordinal a.asc:after {
content: "\e155";
}
.sort-ordinal a.desc:after {
content: "\e156";
}
.grid-view td {
white-space: nowrap;
}
.grid-view .filters input,
.grid-view .filters select {
min-width: 50px;
}
.hint-block {
display: block;
margin-top: 5px;
color: #999;
}
.error-summary {
color: #a94442;
background: #fdf7f7;
border-left: 3px solid #eed3d7;
padding: 10px 20px;
margin: 0 0 15px 0;
}
/* align the logout "link" (button in form) of the navbar */
.nav li > form > button.logout {
padding: 15px;
border: none;
}
@media(max-width:767px) {
.nav li > form > button.logout {
display:block;
text-align: left;
width: 100%;
padding: 10px 15px;
}
}
.nav > li > form > button.logout:focus,
.nav > li > form > button.logout:hover {
text-decoration: none;
}
.nav > li > form > button.logout:focus {
outline: none;
}
ปรับแต่ง vendor/yiisoft/yii2-bootstrap/NavBar.php
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\bootstrap;
use Yii;
use yii\helpers\ArrayHelper;
/**
* NavBar renders a navbar HTML component.
*
* Any content enclosed between the [[begin()]] and [[end()]] calls of NavBar
* is treated as the content of the navbar. You may use widgets such as [[Nav]]
* or [[\yii\widgets\Menu]] to build up such content. For example,
*
* ```php
* use yii\bootstrap\NavBar;
* use yii\bootstrap\Nav;
*
* NavBar::begin(['brandLabel' => 'NavBar Test']);
* echo Nav::widget([
* 'items' => [
* ['label' => 'Home', 'url' => ['/site/index']],
* ['label' => 'About', 'url' => ['/site/about']],
* ],
* 'options' => ['class' => 'navbar-nav'],
* ]);
* NavBar::end();
* ```
*
* @see http://getbootstrap.com/components/#navbar
* @author Antonio Ramirez <amigo.cobos@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class NavBar extends Widget
{
/**
* @var array the HTML attributes for the widget container tag. The following special options are recognized:
*
* - tag: string, defaults to "nav", the name of the container tag.
*
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = [];
/**
* @var array the HTML attributes for the container tag. The following special options are recognized:
*
* - tag: string, defaults to "div", the name of the container tag.
*
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $containerOptions = [];
/**
* @var string|boolean the text of the brand or false if it's not used. Note that this is not HTML-encoded.
* @see http://getbootstrap.com/components/#navbar
*/
public $brandLabel = false;
/**
* @var array|string|boolean $url the URL for the brand's hyperlink tag. This parameter will be processed by [[\yii\helpers\Url::to()]]
* and will be used for the "href" attribute of the brand link. Default value is false that means
* [[\yii\web\Application::homeUrl]] will be used.
* You may set it to `null` if you want to have no link at all.
*/
public $brandUrl = false;
/**
* @var array the HTML attributes of the brand link.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $brandOptions = [];
/**
* @var string text to show for screen readers for the button to toggle the navbar.
*/
public $screenReaderToggleText = 'Toggle navigation';
/**
* @var boolean whether the navbar content should be included in an inner div container which by default
* adds left and right padding. Set this to false for a 100% width navbar.
*/
public $renderInnerContainer = true;
/**
* @var array the HTML attributes of the inner container.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $innerContainerOptions = [];
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
$this->clientOptions = false;
if (empty($this->options['class'])) {
Html::addCssClass($this->options, ['navbar', 'navbar-expand-md', 'navbar-light', 'bg-light']);
} else {
Html::addCssClass($this->options, ['widget' => 'navbar']);
}
/*if (empty($this->options['role'])) {
$this->options['role'] = 'navigation';
}*/
$options = $this->options;
$tag = ArrayHelper::remove($options, 'tag', 'nav');
echo Html::beginTag($tag, $options);
if ($this->renderInnerContainer) {
if (!isset($this->innerContainerOptions['class'])) {
Html::addCssClass($this->innerContainerOptions, 'container');
}
echo Html::beginTag('div', $this->innerContainerOptions);
}
//echo Html::beginTag('div', ['class' => 'navbar-header']);
if (!isset($this->containerOptions['id'])) {
$this->containerOptions['id'] = "{$this->options['id']}-collapse";
}
if ($this->brandLabel !== false) {
Html::addCssClass($this->brandOptions, ['widget' => 'navbar-brand']);
echo Html::a($this->brandLabel, $this->brandUrl === false ? Yii::$app->homeUrl : $this->brandUrl, $this->brandOptions);
}
echo $this->renderToggleButton();
//echo Html::endTag('div');
Html::addCssClass($this->containerOptions, ['collapse' => 'collapse', 'widget' => 'navbar-collapse']);
$options = $this->containerOptions;
$tag = ArrayHelper::remove($options, 'tag', 'div');
echo Html::beginTag($tag, $options);
}
/**
* Renders the widget.
*/
public function run()
{
$tag = ArrayHelper::remove($this->containerOptions, 'tag', 'div');
echo Html::endTag($tag);
if ($this->renderInnerContainer) {
echo Html::endTag('div');
}
$tag = ArrayHelper::remove($this->options, 'tag', 'nav');
echo Html::endTag($tag);
BootstrapPluginAsset::register($this->getView());
}
/**
* Renders collapsible toggle button.
* @return string the rendering toggle button.
*/
protected function renderToggleButton()
{
$screenReader = "<span class=\"navbar-toggler-icon\"></span>";
return Html::button("{$screenReader}\n", [
'class' => 'navbar-toggler',
'data-toggle' => 'collapse',
'data-target' => "#{$this->containerOptions['id']}",
'aria-controls' =>"{$this->containerOptions['id']}",
'aria-expanded' => 'false',
'aria-label' => "{$this->screenReaderToggleText}"
]);
}
}
ปรับแต่ง vendor/yiisoft/yii2-bootstrap/Nav.php
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\bootstrap;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
/**
* Nav renders a nav HTML component.
*
* For example:
*
* ```php
* echo Nav::widget([
* 'items' => [
* [
* 'label' => 'Home',
* 'url' => ['site/index'],
* 'linkOptions' => [...],
* ],
* [
* 'label' => 'Dropdown',
* 'items' => [
* ['label' => 'Level 1 - Dropdown A', 'url' => '#'],
* '<div class="dropdown-divider"></div>',
* '<div class="dropdown-header">Dropdown Header</div>',
* ['label' => 'Level 1 - Dropdown B', 'url' => '#'],
* ],
* ],
* [
* 'label' => 'Login',
* 'url' => ['site/login'],
* 'visible' => Yii::$app->user->isGuest
* ],
* ],
* 'options' => ['class' =>'nav-pills'], // set this to nav-tab to get tab-styled navigation
* ]);
* ```
*
* Note: Multilevel dropdowns beyond Level 1 are not supported in Bootstrap 3.
*
* @see http://getbootstrap.com/components/#dropdowns
* @see http://getbootstrap.com/components/#nav
*
* @author Antonio Ramirez <amigo.cobos@gmail.com>
* @since 2.0
*/
class Nav extends Widget
{
/**
* @var array list of items in the nav widget. Each array element represents a single
* menu item which can be either a string or an array with the following structure:
*
* - label: string, required, the nav item label.
* - url: optional, the item's URL. Defaults to "#".
* - visible: boolean, optional, whether this menu item is visible. Defaults to true.
* - linkOptions: array, optional, the HTML attributes of the item's link.
* - options: array, optional, the HTML attributes of the item container (LI).
* - active: boolean, optional, whether the item should be on active state or not.
* - dropDownOptions: array, optional, the HTML options that will passed to the [[Dropdown]] widget.
* - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
* or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
* - encode: boolean, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for only this item.
*
* If a menu item is a string, it will be rendered directly without HTML encoding.
*/
public $items = [];
/**
* @var boolean whether the nav items labels should be HTML-encoded.
*/
public $encodeLabels = true;
/**
* @var boolean whether to automatically activate items according to whether their route setting
* matches the currently requested route.
* @see isItemActive
*/
public $activateItems = true;
/**
* @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
*/
public $activateParents = false;
/**
* @var string the route used to determine if a menu item is active or not.
* If not set, it will use the route of the current request.
* @see params
* @see isItemActive
*/
public $route;
/**
* @var array the parameters used to determine if a menu item is active or not.
* If not set, it will use `$_GET`.
* @see route
* @see isItemActive
*/
public $params;
/**
* @var string this property allows you to customize the HTML which is used to generate the drop down caret symbol,
* which is displayed next to the button text to indicate the drop down functionality.
* Defaults to `null` which means `<span class="caret"></span>` will be used. To disable the caret, set this property to be an empty string.
*/
public $dropDownCaret;
/**
* @var string name of a class to use for rendering dropdowns withing this widget. Defaults to [[Dropdown]].
* @since 2.0.7
*/
public $dropdownClass = 'yii\bootstrap\Dropdown';
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
if ($this->route === null && Yii::$app->controller !== null) {
$this->route = Yii::$app->controller->getRoute();
}
if ($this->params === null) {
$this->params = Yii::$app->request->getQueryParams();
}
if ($this->dropDownCaret === null) {
$this->dropDownCaret = '<span class="caret"></span>';
}
Html::addCssClass($this->options, ['widget' => 'navbar-nav']);
}
/**
* Renders the widget.
*/
public function run()
{
BootstrapAsset::register($this->getView());
return $this->renderItems();
}
/**
* Renders widget items.
*/
public function renderItems()
{
$items = [];
foreach ($this->items as $i => $item) {
if (isset($item['visible']) && !$item['visible']) {
continue;
}
$items[] = $this->renderItem($item);
}
return Html::tag('ul', implode("\n", $items), $this->options);
}
/**
* Renders a widget's item.
* @param string|array $item the item to render.
* @return string the rendering result.
* @throws InvalidConfigException
*/
public function renderItem($item)
{
if (is_string($item)) {
return $item;
}
if (!isset($item['label'])) {
throw new InvalidConfigException("The 'label' option is required.");
}
$encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
$label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
$options = ArrayHelper::getValue($item, 'options', []);
$items = ArrayHelper::getValue($item, 'items');
$url = ArrayHelper::getValue($item, 'url', '#');
$linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);
if (isset($item['active'])) {
$active = ArrayHelper::remove($item, 'active', false);
} else {
$active = $this->isItemActive($item);
}
if (empty($items)) {
$items = '';
} else {
$linkOptions['data-toggle'] = 'dropdown';
Html::addCssClass($options, ['widget' => 'dropdown']);
Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
if (is_array($items)) {
$items = $this->isChildActive($items, $active);
$items = $this->renderDropdown($items, $item);
}
}
Html::addCssClass($options, 'nav-item');
Html::addCssClass($linkOptions, 'nav-link');
if ($this->activateItems && $active) {
Html::addCssClass($linkOptions, 'active');
}
return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
}
/**
* Renders the given items as a dropdown.
* This method is called to create sub-menus.
* @param array $items the given items. Please refer to [[Dropdown::items]] for the array structure.
* @param array $parentItem the parent item information. Please refer to [[items]] for the structure of this array.
* @return string the rendering result.
* @since 2.0.1
*/
protected function renderDropdown($items, $parentItem)
{
/** @var Widget $dropdownClass */
$dropdownClass = $this->dropdownClass;
return $dropdownClass::widget([
'options' => ArrayHelper::getValue($parentItem, 'dropDownOptions', []),
'items' => $items,
'encodeLabels' => $this->encodeLabels,
'clientOptions' => false,
'view' => $this->getView(),
]);
}
/**
* Check to see if a child item is active optionally activating the parent.
* @param array $items @see items
* @param boolean $active should the parent be active too
* @return array @see items
*/
protected function isChildActive($items, &$active)
{
foreach ($items as $i => $child) {
if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
Html::addCssClass($items[$i]['options'], 'active');
if ($this->activateParents) {
$active = true;
}
}
}
return $items;
}
/**
* Checks whether a menu item is active.
* This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
* When the `url` option of a menu item is specified in terms of an array, its first element is treated
* as the route for the item and the rest of the elements are the associated parameters.
* Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
* be considered active.
* @param array $item the menu item to be checked
* @return boolean whether the menu item is active
*/
protected function isItemActive($item)
{
if (!$this->activateItems) {
return false;
}
if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
$route = $item['url'][0];
if ($route[0] !== '/' && Yii::$app->controller) {
$route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
}
if (ltrim($route, '/') !== $this->route) {
return false;
}
unset($item['url']['#']);
if (count($item['url']) > 1) {
$params = $item['url'];
unset($params[0]);
foreach ($params as $name => $value) {
if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
return false;
}
}
}
return true;
}
return false;
}
}
ความคิดเห็น