- Yii Application Development Cookbook(Second Edition)
- Alexander Makarov
- 226字
- 2021-11-12 16:36:15
Defining multiple layouts
Most applications use a single layout for all their views. However, there are situations when multiple layouts are needed. For example, an application can use different layouts on different pages: two additional columns for blogs, one additional column for articles, and no additional columns for portfolios.
Getting ready
Set up a new application using yiic webapp
.
How to do it...
- Create two layouts in
protected/views/layouts
:blog
andarticles
. Blog will contain the following code:<?php $this->beginContent('//layouts/main')?> <div> <?php echo $content?> </div> <div class="sidebar tags"> <ul> <li><a href="#php">PHP</a></li> <li><a href="#yii">Yii</a></li> </ul> </div> <div class="sidebar links"> <ul> <li><a >Yiiframework</a></li> <li><a >PHP</a></li> </ul> </div> <?php $this->endContent()?>
- Articles will contain the following code:
<?php $this->beginContent('//layouts/main')?> <div> <?php echo $content?> </div> <div class="sidebar toc"> <ul> <li><a href="#intro">1. Introduction</a></li> <li><a href="#quick-start">2. Quick start</a></li> </ul> </div> <?php $this->endContent()?>
- Create three controllers named
BlogController
,ArticleController
, andPortfolioController
withindex
actions in all three:class BlogController extends Controller { function actionIndex() { $this->layout = 'blog'; $this->render('//site/index'); } } class ArticleController extends Controller { function actionIndex() { $this->layout = 'articles'; $this->render('//site/index'); } } class PortfolioController extends Controller { function actionIndex() { $this->render('//site/index'); } }
- Now try
http://example.com/blog
,http://example.com/article
, andhttp://example.com/portfolio
.
How it works...
We defined two additional layouts for the blog and articles. As we don't want to copy and paste common parts from the main
layout, we apply additional layout decorators using $this->beginContent
and $this->endContent
, as shown in the following diagram:

So, we use a view rendered inside articles
layout as the main
layout's $content
.
See also
- The Using the controller context in a view recipe
- The Using decorators recipe
推薦閱讀
- 解析QUIC/HTTP3:未來(lái)互聯(lián)網(wǎng)的基石
- 高校網(wǎng)絡(luò)道德教育研究
- 光網(wǎng)絡(luò)評(píng)估及案例分析
- Hands-On Industrial Internet of Things
- Hands-On Chatbots and Conversational UI Development
- Oracle SOA Suite 11g Performance Tuning Cookbook
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- 物聯(lián)網(wǎng)通信技術(shù)
- Android UI Design
- 人人都該都懂的互聯(lián)網(wǎng)思維
- 設(shè)備監(jiān)控技術(shù)詳解
- 物聯(lián)網(wǎng)的機(jī)遇與利用
- 商業(yè)的本質(zhì)和互聯(lián)網(wǎng)
- Cisco無(wú)線局域網(wǎng)配置基礎(chǔ)
- SEO攻略:搜索引擎優(yōu)化策略與實(shí)戰(zhàn)案例詳解