2012-01-26 50 views
0

我在我的網站上使用CakePHP,我需要解析一個變量並將其寫入佈局。該變量在MySQL中,表「articles」,列「author」。變量佈局

如果在一篇文章中我寫它顯示作者, ,但如果我寫在views/layout/default.thtml它不會顯示任何東西。

有沒有簡單的方法來做到這一點?

+0

你在哪裏放置變量?你能否用你的佈局內容更新你的問題('default.ctp')。任何相關的控制器代碼都可以派上用場。 – mensch

回答

1

您是否在右側控制器功能中獲取了此變量?也許你需要將它插入到一個beforeRender函數中(http://planetcakephp.org/aggregator/items/1398-utilizing-the-appcontrollerbeforerender-to-assign-cakephps-controller-attribut)

0

一個選項可以做到這一點是通過使用CakePHP的requestAction並將其放置在可以標記爲默認佈局的元素中。基本上你會做類似以下的事情

//Create a function in your articles controller as such 
function authorName($articleId = NULL){  
    //Return Author if an ID is passed 
    if(!empty($articleId)){ 
     $this->Article->recursive = -1; 
     $article = $this->Article->findById($articleID); 

     $return $article['Article']['author']; 
    } 

} 

// Then create an element author_name.ctp and place it in views/elements 
// that requests the AuthorID form the above function 
<div> 
<?php 
    $author = $this->requestAction(
     array(
      'controller' => 'articles', 
      'action' => 'authorName' 
     ), 
     array(
      'pass' => $article_id 
     ) 
    ); 
    echo $author; 
?> 
</div> 

// Then in you default layout or anywhere else 
// you can include the element as such 
// You have to figure out a way to get the $id. If you can place a screenshot 
// Or some code of you default layout area where you need this, we can help you further 
<?php echo $this->element('author_name', array('article_id' => $id)); ?>