我正在使用CakePHP 2.4.我有一个博客,我可以添加和编辑帖子.当我实现我的时候edit.ctp,我认识到,我在视图中有相同的代码add.ctp:
<?php
echo $this->Form->create();
echo $this->Form->input('headline');
echo $this->Form->input('text', array('type' => 'textarea');
echo $this->Form->end('Save');
?>
Run Code Online (Sandbox Code Playgroud)
(简化代码)
关于CakePHP的推荐,我想保持我的代码DRY.仅在一次定义表单并在两个视图中使用它的最佳方法是什么?
使用表单代码在文件夹Element中创建一个视图
// app/View/Elements/postForm.ctp
<?php
echo $this->Form->create();
echo $this->Form->input('headline');
echo $this->Form->input('text', array('type' => 'textarea');
echo $this->Form->end('Save');
?>
Run Code Online (Sandbox Code Playgroud)
然后将其包含在您想要的视图中
echo $this->element('postForm');
Run Code Online (Sandbox Code Playgroud)