另一个不需要重写模板的选项是创建一个Cell
使用类的自定义CellView
类。然后,视图类将单元格内容包装在一个布局中,该布局可以显示块,就像您通常在 Cake 视图/布局模板中所期望的那样。
<?php
declare(strict_types=1);
namespace App\View;
use Cake\View\Cell as BaseCell;
use Cake\View\View;
class Cell extends BaseCell
{
/**
* @inheritDoc
*/
public function createView(?string $viewClass = null): View
{
// use custom CellView to for Cells
return parent::createView(CellView::class);
}
}
然后是 CellView:
<?php
declare(strict_types=1);
namespace App\View;
class CellView extends AppView
{
/**
* @inheritDoc
*/
public function render(?string $template = null, $layout = null): string
{
$cellContents = parent::render($template, $layout);
// wrap cell contents in "cell" layout
return $this->renderLayout($cellContents, 'cell');
}
}
现在所有单元格都使用了一个布局,剩下的就是创建一个单元格专用的基本布局:
/templates/layout/cell.php (CakePHP 3: /src/Template/Layout/cell.ctp )
<?php
/**
* @var CellView $this
*/
use App\View\CellView;
echo $this->fetch('styles');
echo $this->fetch('content');
echo $this->fetch('scripts');
在这个初步工作之后,所有App\View\Cell
的 s 都将使用“单元格”布局。我发现从长远来看,如果您使用不同的块或postLink
带有块的 s,这会更直观。
注意:此处的代码适用于 CakePHP 4,但您需要做的就是使其与 CakePHP 3 兼容,只需匹配方法签名即可