sunnyfriend 发表于 2011-6-15 19:07:01

一个简洁的Helper,让CI的视图支持Layout

本帖最后由 sunnyfriend 于 2011-6-19 23:25 编辑

实现原理: 利用Hook,在Controller执行完毕后,Output输出前修改输出,将输出赋值给Layout。
特点:简单, 支持在模板中修改Layout的Css、Script等。
使用:
1. 将Helper文件放在 application/helpers下(下载)

2. 配置钩子:修改文件application/config/hooks.php,添加:

$hook['post_controller'][] = array(
      'class'    => '',
      'function' => 'layout_hook_post_controller',
      'filename' => 'layout_helper.php',
      'filepath' => 'helpers',
      'params'   => NULL
);


3. 建立Layout视图, 建立 application/views/_layouts/main.php,demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html lang="zh-CN" xml:lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=<?php echo config_item('charset');?>">
    <title>Layout</title>

    <link rel="stylesheet" href="<?php echo base_url();?>static/screen.css" type="text/css" media="screen, projection">
    <link rel="stylesheet" href="<?php echo base_url();?>static/print.css" type="text/css" media="print">
    <!-->
    <link rel="stylesheet" href="<?php echo base_url();?>static/ie.css" type="text/css" media="screen, projection">
    <!-->
</head>
<body>
         
      <div id="content"><?php echo $content;?></div>

</body>
</html>


4. 建立内容视图建立application/views/post/create.php, demo:

<?php// 助手函数可以添加<head>标签中的js.css,meta等
$this->load->helper('layout');
layout_register_meta_tag("一个视图Demo","keywords");
layout_register_css_file(base_url().'static/style.css');
layout_register_script_file(base_url().'static/jquery.min.js');
layout_register_script('init','alert("Hello World!");');
?>

<h3>这是视图内容<h3>



5. 在控制器中使用

class Post extends CI_Controller
{
    public function create()
    {
      $this->load->view('post/create');
    }
}


6.指定控制器的layout或不使用layout:

默认的Layout视图为 : application/views/_layouts/main.php,可以参见函数layout_hook_post_controller()
也可以在控制器中指定控制器的 layout或者不使用layout

class Post extends CI_Controller
{    // 使用 views/layout/column1.php作为layout
    $this->layout = 'layout/column1'.EXT;   

    // 这样表示这个控制器不使用layout
    //$this->layout=false;

    public function create()
    {
      $this->load->view('post/create');
    }
}

其他: 这个demo的目录结构
application
    |- config
      |- hooks.php
    |- controllers
      |- post.php
    |- helpers
      |- layout_helper.php
    |- views
      |- _layouts
            |- main.php
            |- column1.php








jaclon 发表于 2011-6-16 19:57:24

沙发,
页: [1]
查看完整版本: 一个简洁的Helper,让CI的视图支持Layout