CodeIgniter模板引擎使用執行個體詳解

來源:互聯網
上載者:User
關鍵字 CodeIgniter 模板引擎
這篇文章主要介紹了CodeIgniter模板引擎使用執行個體,需要的朋友可以參考下

一、樣本:

通常在使用codeigniter的時候經常使用這樣的方式載入:

$this->load->view('about', $data);

通過這個類庫,可以將一個視圖載入到這個模板中:

$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
模板中的代碼如下:

<html><body>  <p id="contents"><?= $contents ?></p>  <p id="footer">Copyright 2008</p></body></html>

$contents是你在控制器中顯示需要插入的內容。

四、建立一個視圖application/views/about.php
添加如下代碼:

<h1>About</h1><p>I'm so human!</p>

在模板引擎中載入視圖
在你的控制器中可以使用

$this->template->load('template', 'about');

這個模板引擎工作流程:

視圖被載入到一個變數中,這個變數會被載入到模板中去

var $template_data = array(); function set($name, $value){ $this->template_data[$name] = $value;} function load($template = '', $view = '' , $view_data = array(), $return = FALSE){         $this->CI =& get_instance(); $this->set('contents', $this->CI->load->view($view, $view_data, TRUE));  return $this->CI->load->view($template, $this->template_data, $return);}

五、技巧總結

進階技巧1:模板中更簡單的短標記

例子:你如果需要在頁面中顯示標題。
那麼在HTML的頭部views/template.php增加:

<head>  <title><?= $title ?></title></head>

然後直接在控制器中設定:

$this->template->set('title', 'About me');

進階技巧2:高亮顯示當前置航

導航通常是被用於在模板中,一個體驗好的導航應該告訴使用者當前所處的位置分類是什麼。

定義你的導航項目:

引入application/libraries/Template.php,然後在控制器中增加:

$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));

更新你的模板:

在application/views/template.php中增加:

<ul class="navigation"> <?php foreach($nav_list as $i => $nav_item): ?> <li class="<?= ($nav == $nav_item ? 'selected' : '')?>"> <?= anchor($nav_item, $nav_item) ?> </li> <?php endforeach ?></ul>

這裡用到了anchor函數,需要在自動載入配置中增加相關的小助手:

$autoload['helper'] = array('url');

更新你的控制器:

增加:

$this->template->set('nav', 'About');

需要注意:
1·如果所有的導航都在一個控制器中,你可以在解構函式中增加通用的導航代碼;
2·定義好當前置航的樣式,例如:#navigation .selected

進階技巧3:多模板

最簡單處理多個模板,可以在libraries/Template.php定義多個新的方法來替換已經存在的內容,第二個進階技巧使用自訂的方法:

function load_main($view = '', $view_data = array(), $return = FALSE){ $this->set('nav_list', array('Home', 'Photos', 'About', 'Contact')); $this->load('template', $view, $view_data, $return);}

將代碼粘貼到控制器中

$this->template->set('nav', 'About');$this->template->set('title', 'About me');$this->template->load_main('about');
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.