CakePHP 3 -如何在视图单元格中设置CSS / Script块

jbose2ul  于 2022-11-11  发布在  PHP
关注(0)|答案(2)|浏览(100)

我使用的是CakePHP 3.9
我正在尝试在视图单元格中设置css / script依赖项块。
我希望它能在我的布局的头部中被获取,但是它不起作用。如果我想让它起作用,我必须在调用单元格之前/之后在视图中设置css依赖关系。
有没有办法在视图单元格中设置css依赖关系?
我的看法:

<?= $this->cell('Post::post_input'); ?>
....

我的检视储存格:

<?php echo $this->Html->css(['element/post-input'], ['block' => true]);  ?>
<div class="post-input">...</div>

我的布局:

<html>
<head>
...
    <?php
    echo $this->fetch('css');
    echo $this->fetch('script');
    ?>
...
</head>
<body>
    <?php echo $this->fetch('content'); ?>
</body>
</html>
wvyml7n5

wvyml7n51#

它不起作用,因为单元是一个使用单独视图示例的封闭环境,因此在其模板中定义的所有块都将驻留在其内部视图中。
从文档中:
单元格模板有一个独立的作用域,该作用域与用于呈现当前控制器操作或其他单元格的模板和布局的视图示例不共享同一个视图示例。因此,它们不知道在操作的模板/布局中进行的任何帮助器调用或块设置,反之亦然。

Cookbook〉Views〉View Cell〉实现单元格

如果您不想在每次使用单元格时手动添加CSS块,那么我建议您构建一个自定义帮助器,它可以生成(甚至直接回显)单元格并添加块,大致如下:

<?php
// in src/View/Helper/PostHelper.php

namespace App\View\Helper;

use Cake\View\Helper;

/**
 * @property \Cake\View\Helper\HtmlHelper $Html
 */
class PostHelper extends Helper
{
    protected $helpers = [
        'Html'
    ];

    protected $wasPostInputCssAdded = false;

    public function postInput()
    {
        if (!$this->wasPostInputCssAdded) {
            $this->wasPostInputCssAdded = true;

            $this->Html->css(['element/post-input'], ['block' => true]);
        }

        return $this->_View->cell('Post::post_input');
    }
}

下面的代码将添加块并回显单元格:

<?= $this->Post->postInput() ?>

另请参阅Cookbook〉视图〉帮助程序〉创建帮助程序

lnlaulya

lnlaulya2#

另一个不需要重写模板的方法是创建一个使用CellView类的自定义Cell类,然后视图类将单元格内容 Package 在一个布局中,该布局可以显示块,就像你在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');
    }
}

既然所有单元格都使用一个布局,剩下的就是创建一个单元格专用的基本布局:

/模板/布局/单元格.php(CakePHP 3:/源代码/模板/布局/单元格.ctp

<?php
/**
 * @var CellView $this
 */

use App\View\CellView;

echo $this->fetch('styles');
echo $this->fetch('content');
echo $this->fetch('scripts');

在这个初始工作之后,所有的App\View\Cell都将使用“cell”布局。我发现如果你使用不同的块或带块的postLink,从长远来看,这会更直观。

  • 注意:这里的代码是针对CakePHP 4的,但要使其与CakePHP 3兼容,您需要做的就是匹配方法签名 *

相关问题