【问题标题】:Merge view templates in cakephp在 cakephp 中合并视图模板
【发布时间】:2013-08-04 15:10:12
【问题描述】:

我有 2 个模板, - /view/opinions/add.ctp - 添加表格 - /view/opinions/list.ctp - 显示意见

我希望它们显示在 /views/opinions/index.ctp 中是否可能?

是 $this -> element() 的唯一方法吗?如果是这样,我可以包含来自 /view/opinions 而不是 /view/elements 的模板吗?

@编辑

OpinionsController.php

class OpinionsController extends AppController { 
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');

    var $name = 'Opinions'; 

    function index() { 
        $opinions = $this->Opinion->find('all'); 
        if(isset($this->params['requested'])) { 
             return $opinions; 
        } 
        $this->set('opinions', $opinions);       
    } 



    public function add() {
        if ($this->request->is('post')) {
            $this->Opinion->create();
            if ($this->Opinion->save($this->request->data)) {
                $this->Session->setFlash(__('saved.'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Unable to add.'));
            }
        }
    }
} 

index.ctp

$this->extend('/Opinions/view');
$this->extend('/Opinions/add');

添加.ctp

echo $this->Form->create('Opinion', array('type' => 'file'));
echo $this->Form->input('author_name', array('label' => 'Imię'));
echo $this->Form->input('author_signature', array('label' => 'Podpis'));
echo $this->Form->input('text', array('rows' => '5', 'cols' => '30', 'label' => 'Opinia'));
echo $this->Form->input('author_pic', array('type' => 'file', 'label' => 'Zdjęcie')); 
echo $this->Form->input('author_pic_dir', array('type' => 'hidden')); 
echo $this->Form->end('Dodaj opinię');

view.ctp `

<?php foreach ($opinions as $opinion): ?>

    <div class="opinion">
        <div class="author">
            <div class="pic"><?php echo $this->Html->image("defaultAvatar.jpg", array('alt' => $opinion['Opinion']['author_name'])); ?></div>
            <div class="signature"><b><?= $opinion['Opinion']['author_name']?></b><br><i><?= $opinion['Opinion']['author_signature']?></i></div>
        </div>
        <div class="text">
            <blockquote><p><?= $opinion['Opinion']['text']?></p></blockquote>       
        </div>
        <div class="clear"><!-- . --></div>
    </div>

    <div class="clear"><!-- . --></div>

<?php endforeach; ?>
<?php unset($post); ?>

`

【问题讨论】:

  • 我们可以做到,只需在 index.ctp 文件中添加您的视图代码......以及您的控制器的索引操作。添加您的添加逻辑并列出值..!!

标签: php templates cakephp view


【解决方案1】:

在像 CakePHP 这样的 web 框架中,我们希望保持我们的代码 DRY。为了做你想做的事,我认为更好的方法是创建元素来列出你的意见,并创建另一个元素来添加新的表单。

然后在index.ctp 中放置这两个元素。在add.ctp 中只放置带有表单的元素,在view.ctp 中应该放置列出意见的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2012-10-06
    • 2012-04-29
    • 2017-04-27
    • 2012-09-23
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多