2011-09-07 65 views
0

这是帖子/ index.php文件=>CakePHP问题:如何从另一个控制器调用一个控制器的视图?

<?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>'; 
} 
?> 

我想打电话从产品/ index.ctp =>这个帖子/ index.ctp这将是所有控制器的通用/通用index.ctp。我怎样才能做到这一点 ?

在posts/index.ctp中使用$ allposts。它在帖子/索引操作中设置。但是当我从产品/索引行动中调用posts/index.ctp时,不同的变量就设置在那里。假设$ this-> set('allproducts',$ allproducts);在产品/索引行动中设置。现在我怎么能使用posts/index.ctp中的所有产品变量?

回答

1

由于@Vins说,你可以在你的控制器动作结束使用$this->render('view_name');来呈现不同的视图(在你的情况应该是$this->render('/posts/index');

在使用你想要的变量而言,有夫妇可以做的事情。一种方法是将每个控制器中的set函数更改为使用通用名称。例如,帖子控制器可能有$this->set('results',$allposts);,而产品控制器可能有$this->set('results',$allproducts);这样做,您始终可以在您的视图文件中引用$results。您可能还想设置另一个变量,$pageModel。例如,在您的产品控制器中使用$this->set('pageModel','Product');。那么你的职位/ index.php文件可以做这样的事情:我代替'controller' => 'posts''controller' => $this->controller这将使您的视图动态的,所以该链接将始终指向正确的控制器的视图操作

<?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>'; 
} 
?> 

通知。

我希望这有助于!

1

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

+0

+1它为我工作,谢谢。 – Chinmay235

0

,如果你想渲染帖子/ index.ctp,而不是产品/ index.ctp,使用$this->render('/posts/index');

或者你可能想把他们中的元素(这是通用/通用index.ctp同样的想法)。

相关问题