CakePHP将数据传递给元素

Cam*_*ron 12 php cakephp

我的控制器中有以下代码:

function index()
{
    $posts = $this->set('posts', $this->Portfolio->find('all'));

    if (isset($this->params['requested']))
    {
        return $posts;
    }
    else
    {
        $this->set('posts', $this->Portfolio->find('all'));
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要它做的是a)显示索引的投资组合项目列表,例如/portfolio/b)显示元素内的投资组合项目列表,以便用户可以从我的侧边栏访问整个站点的投资组合项目.

这是侧边栏的元素:

<?php $posts = $this->requestAction('portfolio/index'); ?>
<ul>
    <?php foreach ($posts as $post): ?>
    <li><?php echo $this->Html->link($post['Portfolio']['title'], array('action' => 'view', $post['Portfolio']['id']));?></li>
    <?php endforeach; ?>
</ul>
Run Code Online (Sandbox Code Playgroud)

然后我在我的布局中这样称呼它:

<?php $this->element('portfolio-nav', array('posts' => $posts) ); ?>
Run Code Online (Sandbox Code Playgroud)

但是它会出现以下错误:

Notice (8): Undefined variable: posts [APP/controllers/portfolio_controller.php, line 16]
Run Code Online (Sandbox Code Playgroud)

并且不显示侧栏中的项目列表.

我很确定我在我的控制器中写的是垃圾,所以如果有人能帮助我让它工作,那就太棒了.

谢谢

Bjo*_*orn 27

我昨天回答了同样的问题.为什么你的控制器动作如此复杂?我想你不需要任何东西

function index() {
    $this->set('posts', $this->Portfolio->find('all'));
    // Make sure the model Portfolio is accessible from here, i.e. place this
    // action in PortfoliosController or load it using 
    // ClassRegistry::init('Portfolio')->find... 
}
Run Code Online (Sandbox Code Playgroud)

然后,在index.ctp视图中:

<?php echo $this->element('foobar', array('posts' => $posts)); ?>
Run Code Online (Sandbox Code Playgroud)

如果您希望能够从站点中的每个页面(侧栏或其他内容)请求此项,您可以使用requestAction或放置$this->set...在AppController中.如果你使用requestAction你的元素,你没有通过array('posts' => ...)你的$this->element电话.


好的,很明显你需要更多的方向.让我一步一步解释.首先,我们需要创建一个beforeFilteron AppController,因此$posts可以从应用程序的任何位置访问该变量.

/app/app_controller.php:

<?php
class AppController extends Controller {
    function beforeFilter() {
        parent::beforeFilter();
        $this->set('posts', ClassRegistry::init('Portfolio')->find('all'));
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,我们将创建一个简单的元素app/views/elements/foobar.ctp:

<?php debug($items); ?>
Run Code Online (Sandbox Code Playgroud)

最后,我们从视图中的某个位置调用该元素:

<?php echo $this->element('foobar', array('items' => $posts)); ?>
Run Code Online (Sandbox Code Playgroud)

我们将$ posts(我们在你的AppController中定义)变量赋给了items键,因为我们的元素需要一个$items变量.


Dun*_*zzz 7

element方法中的第二个参数传递数据.你需要的是:

$this->element('portfolio-nav', array('posts' => $posts) );
Run Code Online (Sandbox Code Playgroud)

请阅读文档.


小智 5

带参数的元素

$this->element('elementname', array('var_name'=>$var));
Run Code Online (Sandbox Code Playgroud)