【问题标题】:CakePHP question: How can i call a view of one controller from another controller?CakePHP 问题:如何从另一个控制器调用一个控制器的视图?
【发布时间】:2011-09-07 15:05:41
【问题描述】:

这是帖子/index.php =>

<?php foreach ($allposts as $post) {
            echo '<tr class="class_row">';
            echo '<td>';

            echo $this->Html->link($post['Post']['title'],
                                array('controller'=>'posts','action'=>'view',$post['Post']['id']),
                                array('id'=>'id_anchor_title','class'=>'class_anchor_title') );
            echo '<tr>';
            echo '<td>';
}
?>

我想从 products/index.ctp 中调用这个 posts/index.ctp => 这将是所有控制器的通用/通用 index.ctp。我该怎么做?

在posts/index.ctp 中使用了$allposts。它在帖子/索引操作中设置。但是当我从 products/index 操作中调用 posts/index.ctp 时,会在那里设置不同的变量。假设 $this->set('allproducts',$allproducts);在产品/索引操作中设置。现在我如何在 posts/index.ctp 中使用 allproducts 变量?

【问题讨论】:

    标签: cakephp cakephp-1.3


    【解决方案1】:

    正如@Vins 所说,您可以在控制器操作结束时使用$this-&gt;render('view_name'); 来呈现不同的视图(在您的情况下应该是$this-&gt;render('/posts/index');

    在使用您想要的变量方面,您可以做几件事。一种方法是将每个控制器中的 set 函数更改为使用通用名称。例如,posts 控制器可能有$this-&gt;set('results',$allposts);,products 控制器可能有$this-&gt;set('results',$allproducts);。这样做,您可以随时在视图文件中引用$results。您可能还想设置另一个变量$pageModel$this-&gt;set('pageModel','Product'); 例如在您的产品控制器中。然后你的 posts/index.php 文件可以做这样的事情:

    <?php foreach ($results as $result) {
                echo '<tr class="class_row">';
                echo '<td>';
    
                echo $this->Html->link($result[$pageModel]['title'],
                                    array('controller'=>$this->controller,'action'=>'view',$result[$pageModel]['id']),
                                    array('id'=>'id_anchor_title','class'=>'class_anchor_title') );
                echo '<tr>';
                echo '<td>';
    }
    ?>
    

    请注意,我将 'controller' =&gt; 'posts' 替换为 'controller' =&gt; $this-&gt;controller 这将使您的视图动态化,因此链接将始终指向正确控制器的视图操作。

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      我们可以使用$this-&gt;render('view_name'); 将另一个视图用于其他操作。我不确定您将如何实现您的目标。

      【讨论】:

        【解决方案3】:

        如果你想渲染posts/index.ctp而不是products/index.ctp,使用$this-&gt;render('/posts/index');

        或者你可能想把它放在一个元素中(这与 generic/common index.ctp 的想法相同)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-07
          • 1970-01-01
          • 2013-07-25
          相关资源
          最近更新 更多