cakephp 3.x 创建自定义小部件
cakephp 3.x create custom widget
我想为 Cakephp formHelper 创建小部件。
我在 View/Widget 目录中创建了一个名为 ImageWidget.php 的小部件文件(我不知道这是否是正确的目录,但 phpstorm 加载它所以看起来不错)
<?php
namespace App\View\Widget;
use Cake\View\Form\ContextInterface;
use Cake\View\Widget\WidgetInterface;
class ImageWidget implements WidgetInterface
{
protected $_templates;
public function __construct($templates)
{
$this->_templates = $templates;
}
public function render(array $data, ContextInterface $context)
{
$data += [
'name' => '',
];
return $this->_templates->format('myTestTemp', [
'name' => $data['name'],
'attrs' => $this->_templates->formatAttributes($data, ['name'])
]);
}
public function secureFields(array $data)
{
return [$data['name']];
}
}
?>
但是我得到了这个错误:
Cannot find template named 'myTestTemp'.
我不知道我的模板应该放在哪里,也不知道这个模板是什么
(像cakephp普通模板吗?)
我的模板文件是这样的:
//in myTestTemp.ctp file
<p>some html for test</p>
我试图将文件放在这些目录中,但它不起作用
- src/Template
- src/View
- src/View/Widget
谢谢
与任何其他小部件一样,您的小部件使用字符串模板,它依赖于在表单助手中设置的模板(分别在传递给小部件构造函数的 \Cake\View\StringTemplate
对象上设置),例如:
$this->Form->setTemplates([
'myTestTemp' => '<p {{attrs}}>some html for test</p>'
]);
另见
我想为 Cakephp formHelper 创建小部件。
我在 View/Widget 目录中创建了一个名为 ImageWidget.php 的小部件文件(我不知道这是否是正确的目录,但 phpstorm 加载它所以看起来不错)
<?php
namespace App\View\Widget;
use Cake\View\Form\ContextInterface;
use Cake\View\Widget\WidgetInterface;
class ImageWidget implements WidgetInterface
{
protected $_templates;
public function __construct($templates)
{
$this->_templates = $templates;
}
public function render(array $data, ContextInterface $context)
{
$data += [
'name' => '',
];
return $this->_templates->format('myTestTemp', [
'name' => $data['name'],
'attrs' => $this->_templates->formatAttributes($data, ['name'])
]);
}
public function secureFields(array $data)
{
return [$data['name']];
}
}
?>
但是我得到了这个错误:
Cannot find template named 'myTestTemp'.
我不知道我的模板应该放在哪里,也不知道这个模板是什么 (像cakephp普通模板吗?)
我的模板文件是这样的:
//in myTestTemp.ctp file
<p>some html for test</p>
我试图将文件放在这些目录中,但它不起作用
- src/Template
- src/View
- src/View/Widget
谢谢
与任何其他小部件一样,您的小部件使用字符串模板,它依赖于在表单助手中设置的模板(分别在传递给小部件构造函数的 \Cake\View\StringTemplate
对象上设置),例如:
$this->Form->setTemplates([
'myTestTemp' => '<p {{attrs}}>some html for test</p>'
]);
另见