Cakephp 一个布局中的多个视图
我知道如何使用元素在布局中渲染多个视图 我想问的是,假设我有一个多控制器,可以处理多种事情。例如,UsersController、ArticlesController和BooksController。假设我想从每个控制器中提取五个最新数据,并将它们放在一个布局中,就像在主页中一样Cakephp 一个布局中的多个视图,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,我知道如何使用元素在布局中渲染多个视图 我想问的是,假设我有一个多控制器,可以处理多种事情。例如,UsersController、ArticlesController和BooksController。假设我想从每个控制器中提取五个最新数据,并将它们放在一个布局中,就像在主页中一样 如何做到这一点?您应该为不同的控制器提取不同变量中的数据。并在布局中使用这些变量。PagesController.php class PagesController extends AppController {
如何做到这一点?您应该为不同的控制器提取不同变量中的数据。并在布局中使用这些变量。PagesController.php
class PagesController extends AppController {
public function initialize() {
parent::initialize();
$this -> loadModel('Users');
$this -> loadModel('Articles');
$this -> loadModel('Books');
}
public function home() {
$users = $this -> Users -> find('all') -> order(['Users.id' => 'desc']) -> limit(5);
$articles = $this -> Articles -> find('all') -> order(['Articles.id' => 'desc']) -> limit(5);
$books = $this -> Books -> find('all') -> order(['Books.id' => 'desc']) -> limit(5);
$this -> set(compact('users', 'articles', 'books'));
}
}
现在您可以在中看到最后5个用户、文章和书籍
Pages/Home.ctp虽然公认的答案肯定是可行的,但这听起来非常像是一个应用程序的用例。
class PagesController extends AppController {
public function initialize() {
parent::initialize();
$this -> loadModel('Users');
$this -> loadModel('Articles');
$this -> loadModel('Books');
}
public function home() {
$users = $this -> Users -> find('all') -> order(['Users.id' => 'desc']) -> limit(5);
$articles = $this -> Articles -> find('all') -> order(['Articles.id' => 'desc']) -> limit(5);
$books = $this -> Books -> find('all') -> order(['Books.id' => 'desc']) -> limit(5);
$this -> set(compact('users', 'articles', 'books'));
}
}