我在我的网站上使用CakePHP,我需要解析一个变量并将其写入布局。该变量在MySQL中,表“articles”,列“author”。变量布局
如果在一篇文章中我写它显示作者, ,但如果我写在views/layout/default.thtml它不会显示任何东西。
有没有简单的方法来做到这一点?
我在我的网站上使用CakePHP,我需要解析一个变量并将其写入布局。该变量在MySQL中,表“articles”,列“author”。变量布局
如果在一篇文章中我写它显示作者, ,但如果我写在views/layout/default.thtml它不会显示任何东西。
有没有简单的方法来做到这一点?
您是否在右侧控制器功能中获取了此变量?也许你需要将它插入到一个beforeRender函数中(http://planetcakephp.org/aggregator/items/1398-utilizing-the-appcontrollerbeforerender-to-assign-cakephps-controller-attribut)
一个选项可以做到这一点是通过使用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)); ?>
你在哪里放置变量?你能否用你的布局内容更新你的问题('default.ctp')。任何相关的控制器代码都可以派上用场。 – mensch