一、示例:
通常在使用codeigniter的時候經常使用這樣的方式載入:
1 | $this ->load->view( 'about' , $data ); |
通過這個類庫,可以將一個視圖載入到這個模板中:
1 | $this ->template->load( 'template' , 'about' , $data ); |
這里將視圖about.php載入到template模板文件中。
二、安裝
下載ci_template_library.zip
解壓后將Template.php放到application/libraries應用類庫目錄中;
應用程序啟動自動加載application/config/autoload.php;
三、創建一個模板文件application/views/template.php
模板中的代碼如下:
3 | <div id= "contents" ><?= $contents ?></div> |
4 | <div id= "footer" >Copyright 2008</div> |
$contents是你在控制器中顯示需要插入的內容。
四、創建一個視圖application/views/about.php
添加如下代碼:
在模板引擎中載入視圖
在你的控制器中可以使用
1 | $this ->template->load( 'template' , 'about' ); |
這個模板引擎工作流程:
視圖被載入到一個變量中,這個變量會被載入到模板中去
01 | var $template_data = array (); |
03 | function set( $name , $value ) |
05 | $this ->template_data[ $name ] = $value ; |
08 | function load( $template = '' , $view = '' , $view_data = array (), $return = FALSE) |
10 | $this ->CI =& get_instance(); |
11 | $this ->set( 'contents' , $this ->CI->load->view( $view , $view_data , TRUE)); |
12 | return $this ->CI->load->view( $template , $this ->template_data, $return ); |
五、技巧總結:
高級技巧1:模板中更簡單的短標記
例子:你如果需要在頁面中顯示標題。
那么在HTML的頭部views/template.php增加:
2 | <title><?= $title ?></title> |
然后直接在控制器中設置:
1 | $this ->template->set( 'title' , 'About me' ); |
高級技巧2:高亮顯示當前導航
導航通常是被用于在模板中,一個體驗好的導航應該告訴用戶當前所處的位置分類是什么。
定義你的導航項目:
引入application/libraries/Template.php,然后在控制器中增加:
1 | $this ->set( 'nav_list' , array ( 'Home' , 'Photos' , 'About' , 'Contact' )); |
更新你的模板:
在application/views/template.php中增加:
1 | <ul class = "navigation" > |
2 | <?php foreach ( $nav_list as $i => $nav_item ): ?> |
3 | <li class = "<?= ($nav == $nav_item ? 'selected' : '')?>" > |
4 | <?= anchor( $nav_item , $nav_item ) ?> |
這里用到了anchor函數,需要在自動加載配置中增加相關的小助手:
1 | $autoload [ 'helper' ] = array ( 'url' ); |
更新你的控制器:
增加:
1 | $this ->template->set( 'nav' , 'About' ); |
需要注意:
1·如果所有的導航都在一個控制器中,你可以在析構函數中增加通用的導航代碼;
2·定義好當前導航的樣式,例如:#navigation .selected
高級技巧3:多模板
最簡單處理多個模板,可以在libraries/Template.php定義多個新的方法來替換已經存在的內容,第二個高級技巧使用自定義的方法:
1 | function load_main( $view = '' , $view_data = array (), $return = FALSE) |
3 | $this ->set( 'nav_list' , array ( 'Home' , 'Photos' , 'About' , 'Contact' )); |
4 | $this ->load( 'template' , $view , $view_data , $return ); |
將代碼粘貼到控制器中
1 | $this ->template->set( 'nav' , 'About' ); |
2 | $this ->template->set( 'title' , 'About me' ); |
3 | $this ->template->load_main( 'about' ); |