I answered the very same question yesterday. Why is your controller action so complex? I guess you don't need anything more than
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...
}
Then, in your index.ctp view:
<?php echo $this->element('foobar', array('posts' => $posts)); ?>
If you want to be able to request this from every page in your site (sidebar or something), you can use requestAction
, or place the $this->set...
in your AppController. If you use requestAction
in your element, you don't have to pass array('posts' => ...)
in your $this->element
call.
Ok, It's clear you need much more direction. Let me explain this step by step. First we need to create a beforeFilter
on your AppController
, so the $posts
variable is accessible from everywhere in your application.
/app/app_controller.php
:
<?php
class AppController extends Controller {
function beforeFilter() {
parent::beforeFilter();
$this->set('posts', ClassRegistry::init('Portfolio')->find('all'));
}
}
Next, we're creating a simple element in app/views/elements/foobar.ctp
:
<?php debug($items); ?>
Lastly, we call the element from somewhere in a view:
<?php echo $this->element('foobar', array('items' => $posts)); ?>
We are assigning the $posts (which we have defined in your AppController) variable the items
key, because our element expects a $items
variable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…