繼續(xù)對codeigniter的mvc框架進行學習,本文學習的mvc中的視圖view。視圖層是主要用來顯示內(nèi)容的框架,包括頭,尾等,主要是靜態(tài)的html骨架。前面一篇文章有了控制層,控制可以調(diào)用view視圖層進行前端頁面的展示。
1.首先ci的視圖位置是在:application/views/下
2.視圖文件創(chuàng)建,默認的可以創(chuàng)建.php視圖,可以使用其他擴展名的視圖,比如html,tpl等。
比如創(chuàng)建上一篇文章的pages視圖,命名為pages.php,代碼
<html>
<head><title>
<?php echo $title;?>
</title>
</head><body>this is a view .
</body></html>
可以在視圖內(nèi)創(chuàng)建文件夾,方便管理。
3.訪問視圖,訪問圖是通過控制器來操作的,還是上一篇文章的控制器
當url請求為www.anypoetry.com/index.php/pages 的時候會調(diào)用控制器pages,并調(diào)用index函數(shù),
那么我們定義控制器的index函數(shù)。
class pages extends ci_controller{
function __contruct(){
parent::__contruct();
}
publiction index(){
$this->load->view('pages') //這里調(diào)用對應(yīng)的視圖
}
}
當調(diào)用文件夾內(nèi)的視圖時,比如 jy/pages 視圖
則調(diào)用時加上文件夾即可
$this->load->view('jy/pages');
當使用其他后綴的視圖時,則要加上視圖的后綴名
比如pages.tpl
$this->load->view(pages.tpp);
4.給視圖view傳遞數(shù)據(jù)。傳遞的數(shù)據(jù)是數(shù)組格式。
比如
$data['title']='this is view show';
$data['content']='this is view content';
傳遞方法
$this->load->view(pages,$data);
這樣就將$data數(shù)組傳遞個pages。
在 pages 的view頁面中可以直接使用
<html>
<head><title>
<?php echo $title;?> 這里會輸出this isview show
</title>
</head><body><?php echo $content;?>這里會輸出 this is view content
</body></html>
5.獲取視圖的返回字符串,即通過load->view
獲取view返回的字符串,不直接輸出
這個只是個load->view 的參數(shù),在最后面添加 布爾值 true。默認為false,不做操作直接輸出
舉例,在控制器里面調(diào)用pages
$string = $this->load->view(pages,$data,true);
$string = $this->load->view(pages,true);
這樣頁面返回的內(nèi)容將給$string,而不會直接輸出。
更多信息請查看IT技術(shù)專欄