2012-01-17 114 views
2

我正在尋找一種乾淨的方式將變量傳遞給局部視圖。請看下面的例子代碼:將變量傳遞給局部視圖的簡潔方法

在我控制我做的:

$this->view->articles = $arrayWithArticles; 
$this->render('articles.phtml'); 

在我articles.phtml觀點我做的:

foreach($this->articles as $article) { 
    // show article 

    $this->render('comments.phtml'); 
} 

在另一個控制器我做的:

$this->view->products = $arrayWithProducts; 
$this->render('products.phtml'); 

在我的products.phtml觀點我做的:

foreach($this->products as $product) { 
    // show product 

    $this->render('comments.phtml'); 
} 

正如你可以看到我使用相同的(部分)視圖comments.phtml顯示約寫的文章,以及產品的意見。我想要顯示的'評論'在$article->comments$product->reviews。部分視圖將需要這些來顯示它們。

什麼是將它們傳遞給局部視圖的乾淨方式。我真的不想做的事:

$this->comments = $article->comments; 
$this->render('comments.phtml'); 

,因爲這將有可能成爲一個痛苦的跟蹤關(即設置了同樣的觀點變量在兩個控制器作爲視圖)。

是否有一個乾淨的解決方案將變量傳遞給部分視圖?

回答

1

嗯,我認爲給render()方法添加一個參數就足夠了。也許像...

$this->renderSubView($fileName, $data); 

然後在renderSubView()你可以做什麼,那就是你需要做的陣列,並返回渲染的局部視圖。這樣你就不需要在視圖中重新聲明變量,只需在渲染時傳遞適合該特定部分的數據即可。