我正在使用 CakePHP 2.2.4 并且有类似的布局。然而,对于一页来说,<head>
内容是相同的,但本质上是整个正文不同。我所拥有的是一个带有导航栏的网站,该导航栏来自 twitter 的引导程序。在这一页上,导航栏完全不同。我知道快速解决方法是为该页面创建一个布局,但是如果我遇到另一个需要使用不同导航栏制作的页面怎么办?这样做的“正确” MVC 方式是什么?
问问题
630 次
2 回答
2
我想这取决于差异的复杂程度。
一种方法是拥有一个通用的布局文件
// in app/View/Common/layout.ctp
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Your header content -->
</head>
<body>
<div id="wrap">
<div class="navbar">
<?php echo $this->fetch('menu'); ?>
</div>
<div class="container">
<?php echo $this->fetch('content'); ?>
</div>
</div>
<div id="footer">
<?php echo $this->fetch('footer'); ?>
</div>
</body>
</html>
让你的布局文件扩展它
//app/View/Layouts/default.ctp
<?php
$this->extend('/Common/layout');
$this->assign('menu', $this->element('menu'));
echo $this->fetch('content');
$this->assign('footer', $this->element('footer'));
?>
于 2013-01-09T09:19:57.987 回答
2
如果每个视图都有某种导航栏,那么您可以只使用CakePHP Elements来显示该栏,您可以将元素调用放在您的一个布局文件中,并从控制器设置一个变量,将其传递给元素以显示具体元素...
echo $this->element('navbar', array(
"which_element" => "thisone"
));
在上面的示例中,您的 navbar.ctp 必须包含所有导航栏并使用PHP Switch 语句或其他东西来根据 $which_element...
或者更好的是,只需使用控制器中的变量直接调用元素
$this->set('navbar', "thisone"); // this line is in your controller and sets the file name of your nav bar, minus the .ctp extension
echo $this->element($navbar); //this line is in your layout.ctp and renders elements/thisone.ctp, in the above example.
如果有些页面会有导航栏但有些没有,请使用查看块
$this->start('navbar');
echo $this->element($navbar);
$this->end();
于 2013-01-09T09:16:11.030 回答