視圖是用戶用戶能看到你的網站的所有。 他們使用一個統一的接口, 而且可以根據需要進行修改。 MVC 的好處之一是你分開了表示層和邏輯層, 一切都顯得很干淨。視圖實際上是一組包含有你的內容的HTML結構。結構中有各種元素,如顏色,字體,文字布局等; 不過視圖不關心這些,它要做的只是取來內容,顯示出來。
一般我們在控制器中這樣定義:
function index() {
$data['mytitle'] = "A website monitoring tool";
$data['mytext'] = "This website helps you to keep track of the other websites you control.";
$this->load->view('basic_view',$data);
}
我們把$data數組作為$this->load->view()的第二個三數,在視圖名稱之後。視圖接收到$data數組後,使用PHP函數extract()把數組中的每個元素轉換成內存變量,數組的鍵名即為變量名,值為變量內所包含的值。這些變量的值能直接被視圖引用:
<html> <head> </head> <body> <h1 class='test'><?php echo $mytitle; ?></h1> <p class='test'><?php echo $mytext; ?></p> </body> </html>
雖然你只能傳送一個變量到視圖, 但是通過建立數組,你能把大量變量整潔地傳入視圖。它似乎復雜, 但是實際上是一種緊湊和優秀的信息傳輸方式。
如果傳遞過來的數組是包含多個數據,那麼就需要遍歷,操作一般如下。先是控制器:
$data["notice"] =array('aaa','bbb');
$this->load->view('api/notice',$data);
視圖中解析:
<?php
if(count($notice)>0){
foreach($notice as $key =>$value ){
?>
<a href="#"><?php echo $value?></a>
<?php
}
?>
再說下二維數組的傳遞與遍歷問題。下面的程序實現遍歷某個目錄下的文件。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Data extends CI_Controller {
public function index()
{
$this->load->helper('url');
$data['page_title'] = '幫客之家';
$data['pre_url'] = 'application/views/default/';
$this->load->view('default/header', $data);
$this->load->view('default/index', $data);
$this->load->view('default/footer');
//$this->load->view('index');
}
public function gdnews()
{
$this->load->helper('url');
$arr = array();
function tree($directory)
{
$mydir = dir($directory);
while($file = $mydir->read())
{
// 是目錄的話
if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!=".."))
{
//echo "<li><font color=\"#ff00cc\"><b>$file</b></font></li>\n";
//tree("$directory/$file");
}
// 不是目錄
else
{
$arr['name'][] = @iconv('GB2312','UTF-8',$file);
$arr['time'][] = @iconv('GB2312','UTF-8',date('Y-m-d H:i:s', filemtime($file)));
}
}
$mydir->close();
return $arr;
}
$dir = "datas/gdnews/";
$arr = tree($dir);
$data['files'] = $arr;
$data['page_title'] = '幫客之家' ;
$data['dir'] = $dir;
$this->load->view('default/header', $data);
$this->load->view('default/data', $data);
$this->load->view('default/footer');
}
}
?>
在視圖中這麼輸出就可以:
<?php
if(count($files)>0)
{
foreach($files['name'] as $key =>$value ){
?>
<p class="postmetadata">
<span ><?=$files['time'][$key]?></span> <?=$files['name'][$key]?>
<span><a href="<?=base_url().$dir.$files['name'][$key]?>" target="_blank">查看</a> <a href="#">刪除</a></span>
</p>
<?php
}
}
?>