我在我的网站上使用CakePHP,我需要解析变量并将其写入布局中。该变量位于MySQL,表“articles”,列“author”。
如果在我写的文章中,它会向我显示作者, 但如果我在views / layout / default.thtml中写它,它不会向我显示任何内容。
有一种简单的方法吗?
答案 0 :(得分:1)
您是否在正确的控制器功能中获得此变量?也许你需要将它插入到beforeRender函数中(http://planetcakephp.org/aggregator/items/1398-utilizing-the-appcontrollerbeforerender-to-assign-cakephps-controller-attribut)
答案 1 :(得分: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)); ?>