官术网_书友最值得收藏!

Using clips

One of the Yii features you can use in your views is clips. The basic idea is that you can record some output and then reuse it later in a view. A good example will be defining additional content regions for your layout and filling them elsewhere.

Getting ready

Set up a new application using yiic webapp.

How to do it...

  1. For our example, we need to define two regions in our layout: beforeContent and footer. Open protected/views/layouts/main.php and insert the following just before the content output (<?php echo $content; ?>):
    <?php if(!empty($this->clips['beforeContent'])) echo $this->clips['beforeContent']?>

    Then, insert the following into <div id="footer">:

    <?php if(!empty($this->clips['footer'])) echo $this->clips['footer']?>
  2. That is it. Now, we need to fill these regions somehow. We will use a controller action for the beforeContent region. Open protected/controllers/SiteController.php and add the following to actionIndex:
    $this->beginClip('beforeContent');
    echo 'Your IP is '.Yii::app()->request->userHostAddress;
    $this->endClip();
  3. As for footer, we will set its content from a view. Open protected/views/site/index.php and add the following:
    <?php $this->beginClip('footer')?>
    This application was built with Yii.
    <?php $this->endClip()?>
  4. Now, when you open your website's index page, you should get your IP just before the page content and "built with" note in the footer.

How it works...

We mark regions with the code that just checks for existence of a clip specified and, if clip exists, the code outputs it. Then, we record content for clips we defined using special controller methods named beginClip and endClip.

See also

  • The recipe named Using controller context in a view in this chapter
主站蜘蛛池模板: 莲花县| 济宁市| 昔阳县| 清河县| 汕尾市| 赫章县| 碌曲县| 建德市| 淮北市| 全州县| 年辖:市辖区| 南京市| 双流县| 佳木斯市| 宜春市| 六枝特区| 库车县| 苍溪县| 桐庐县| 林口县| 西峡县| 佛学| 恭城| 抚松县| 宜良县| 灵寿县| 衡阳市| 田东县| 六安市| 大埔区| 阿鲁科尔沁旗| 博野县| 建平县| 五家渠市| 观塘区| 台州市| 湛江市| 潜山县| 上蔡县| 灌阳县| 彭泽县|