扩展Dcat admin Table工具支持自定义列宽度、自定义列名
作者: 分类: 技术分享 发布于: 2023-04-14 17:57:57 浏览:1,273 评论(0)
Dcat admin自带的table 工具只能传二维数组,不能够自定义列的宽度,渲染出来的表格不是很好看,所以根据源码,简单改了一下,直接上代码:
自定义table工具类继承 Dcat\Admin\Widgets\Table
:
namespace App\Widgets;
use Dcat\Admin\Widgets\Table as BaseTable;
class Table extends BaseTable
{
protected $view = 'widgets.table';
}
就是这么简单,只是重新声明一下模板地址
创建模板
// resources/views/widgets/table.blade.php
<table>
<thead>
<tr>
@foreach($headers as $header)
<th>{{ $header }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach($rows as $row)
<tr>
@foreach($row as $item)
@if(is_string($item))
<td>{!! $item !!}</td>
@else
<td>attributes() !!}>{!! $item->content() !!}</td>
@endif
@endforeach
</tr>
@endforeach
</tbody>
</table>
创建Column模型
<?php namespace App\Layouts;
class Column
{
protected $content = '';
protected $class = [];
protected $width = 0;
/**
* Column constructor.
* @param string $content
*/
public function __construct(string $content = '')
{
$this->content = $content;
}
/**
* @param mixed ...$params
*
* @return static
*/
public static function make(...$params)
{
return new static(...$params);
}
/**
* 设置宽度
*
* @param int $width
* @return $this
*/
public function width($width = 0)
{
$this->width = $width;
return $this;
}
/**
* 设置类名
*
* @param string|array $class
* @return $this
*/
public function class($class = [])
{
if (is_array($class)) {
$this->class = array_merge($class, $this->class);
} else {
$this->class[] = $class;
}
return $this;
}
/**
* 添加label标签
*
* @param $content
* @param string $class
* @return $this
*/
public function label($content, $class = 'default')
{
$this->content .= sprintf(' <span class="label bg-%s">%s</span>', $class, $content);
return $this;
}
/**
* 获取内容
*
* @return string
*/
public function content()
{
return $this->content;
}
/**
* 获取列属性
*
* @return string
*/
public function attributes()
{
$attributes = '';
if (empty($this->class)) {
$attributes .= sprintf('class="%s" ', implode(' ', $this->class));
}
if ($this->width) {
$attributes .= sprintf('width="%s" ', $this->width);
}
return $attributes;
}
}
控制器中使用
use App\Layouts\Column as TableColumn;
use App\Widgets\Table;
.
.
.
return Card::make('系统信息', function () {
return new Table([
[TableColumn::make('运行环境')->width(120), request()->server('SERVER_SOFTWARE')],
['是否可读',TableColumn::make()->label('可读', 'primary')->label('不可写', 'danger')],
]);
});
渲染效果
转载时请注明出处及相应链接。
本文永久链接: https://blog.baigei.com/articles/dcat-table-column