您的位置:首页 > 编程语言 > PHP开发

yii分析 Yii: 利用Clip片段构建复杂界面

2010-05-07 17:56 134 查看
大家都知道Yii里为我们提供了layout效果,我们可以把一个view嵌入事先设计好的layout。但随着网站设计越来越多变,越来越复杂,光光layout内一个$content 变量在载入view似乎有时候并不能满足我们的需求。如果页面中有好几个地方需要时时变动呢? 没关系, Yii还为我们提供了Clip这个方法,这个其实有点类似与Django中的block。

比如现在我们需要构建一个布局,左边是主要内容,侧边栏上有个子菜单和一段介绍文字,在每个不同的页面上,子菜单和介绍文字都是是不同的。让我们看看代码,这个应该更直接:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Clip</title>
</head>
<body>
<div id="header">
this is header and main menu here
</div>
<div id="main">
<div id="left">
<?php echo $content ?>
</div>

<div id="right">
<div class="block">
<?php echo $this->clips['submenu'] ?>
</div>

<div class="block">
<?php echo $this->clips['desc'] ?>
</div>
</div>
</div>
<div id="footer">
footer section
</div>
</body>
</html>


在这段代码中我们建立了一个layout,div#left 这里我们载入了view,而在侧边栏div#left中文名调用了2个clip片段。
接下来我们看看view的实现:

hello, this is the view 1

<?php $this->beginClip('submenu') ?>
here is the sub menu for view 1
<?php $this->endClip() ?>

<?php $this->beginClip('desc') ?>
here is the description for view 1
<?php $this->endClip() ?>


hi, view 2 is here

<?php $this->beginClip('submenu') ?>
here is the sub menu for view 2
<?php $this->endClip() ?>

<?php $this->beginClip('desc') ?>
here is the description for view 2
<?php $this->endClip() ?>


上面的两个view中,我们为submenu和desc片段都设定了不同的内容,如果是更复杂的页面我们还可以继续添加更多的clip片段。
当然clip也不是非常完美, 和django中的block相比,我们不能为每个clip都设定一个初始值,这样我们要在每个view中都给clip赋值,这有点小麻烦:p
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: