Table of Contents
Welcome to my Blog!
My Todo List
Home php教程 php手册 [PHP]CodeIgniter学习手册(二):视图view的介绍与使用

[PHP]CodeIgniter学习手册(二):视图view的介绍与使用

Jun 06, 2016 pm 07:57 PM
codeigniter php view study manual view

简而言之,一个视图就是一个html网页,或是网页的部分,如头部,底部,侧边栏等等。 事实上,如果你需要这种层次类型,视图可以很灵活的嵌入到其他视图中。 视图从不直接调用,必须被一个控制器来调用。记住,在一个 MVC 框架中,控制器扮演着交通警察的角色

简而言之,一个视图就是一个html网页,或是网页的部分,如头部,底部,侧边栏等等。

事实上,如果你需要这种层次类型,视图可以很灵活的嵌入到其他视图中。

视图从不直接调用,必须被一个控制器来调用。记住,在一个 MVC 框架中,控制器扮演着交通警察的角色,那么,他有责任去取回某一特定的视图。


创建视图

使用你的文本编辑器,创建一个名为 blogview.php 的文件,写入以下代码:

<title>My Blog</title>


<h1 id="Welcome-to-my-Blog">Welcome to my Blog!</h1>

Copy after login

然后保存文件到 application/views/ 文件夹。


载入视图
你必须使用下面的函数来载入一个视图文件:
$this->load->view('name');
Copy after login
上面的 name 便是你的视图文件的名字。注意:.php 文件的扩展名(后缀名)没有必要专门写出,除非你使用了其他的扩展名。
现在, 打开你先前写的名为 blog.php 控制器文件,并且使用视图载入函数替换echo段代码:


<?php class Blog extends CI_Controller{
	function index(){
		$this->load->view('blogview'); 
	}
}
?>
Copy after login

如果你使用先前你用的 URL 浏览你的网站,你将会看到你的新视图.

URL 与下面的类似:example.com/index.php/blog/


载入多个视图
CodeIgniter 能智能的处理多个从控制器发起的视图载入函数调用 $this->load->view。如果有多个调用,那么他们将会被合并到一起。例如,你可能希望有一个标题视图、一个菜单视图、一个内容视图、和一个页脚视图。他们看起来应该是这样:
<?php class Page extends CI_Controller {
   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('header');
      $this->load->view('menu');
      $this->load->view('content', $data);
      $this->load->view('footer');
   }
}
?>
Copy after login
在上面的例子中,我们使用了“动态添加数据”,你将在下面看到。


用子文件夹存储视图

如果你想让文件更有组织性,你也可以用子文件夹来存储你的视图文件.. 当你在载入视图时,必须加上子文件夹的名字. 示例如下:
$this->load->view('folder_name/file_name');
Copy after login

给视图添加动态数据

数据通过控制器以一个数组或是对象的形式传入视图 , 这个数组或对象作为视图载入函数的第二个参数 .

下面便是使用数组的示例:

function testView()
{
	$data = array(
		'title' => 'My Title',
		'heading' => 'My Heading',
		'message' => 'My Message'
	);
	$this->load->view('blogview', $data);
}
Copy after login

这里是使用对象的示例:
$data = new Someclass();
$this->load->view('blogview', $data);
Copy after login

当我们一次性载入多个视图的时候,你只需在第一个视图传入数据就可以了(header视图显示title,content视图显示message),比如:
<?php class Page extends CI_Controller {

   function index()
   {
      $data['title'] = 'Your title';
      $data['message'] = 'Your message';
      $this->load->view('header',$data);
      $this->load->view('content');
      $this->load->view('footer');
   }

}
?>
Copy after login

注意:如果你使用一个对象,那么类变量将转换为数组元素。

打开控制器并添加以下代码:

<?php class Blog extends CI_Controller {
	function index() {
		$data['title'] = "My Real Title";
		$data['heading'] = "My Real Heading";
		$this->load->view('blogview', $data); 
	} 
} 
?>

Copy after login

现在,打开你的视图文件,将其中的文本替换成与数组对应的变量:
 
 
<title><?php echo $title;?></title> 
 
 
<h1><?php echo $heading;?></h1> 
 

Copy after login
然后使用你先前用过的URL载入页面,你将看到变量已经被替换。


创建循环

你传入视图文件的数据,不仅仅局限于简单的变量。你可以传递多维数组。例如:你从数据库里面取出数据就是典型的多维数据。
这里是个简单的示例。添加以下代码到你的控制器:
<?php class Blog extends CI_Controller{
    function index() { 
        $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); 
        $data['title'] = "My Real Title"; $data['heading'] = "My Real Heading"; 
        $this->load->view('blogview', $data); 
    }
}
?>
Copy after login


现在打开你的视图文件,创建一个循环:

 

<title><?php echo $title;?></title> 
 
 
<h1><?php echo $heading;?></h1> 
<h3 id="My-Todo-List">My Todo List</h3> 
Copy after login

注意: 上面的例子中我们使用PHP替代语法。


获取视图内容

view函数第三个可选参数可以改变函数的行为,让数据作为字符串返回而不是发送到浏览器。如果想用其它方式对数据进一步处理,这样做很有用。如果将view第三个参数设置为true(布尔)则函数返回数据。

view函数缺省行为是 false, 将数据发送到浏览器。如果想返回数据,记得将它赋到一个变量中:

$string = $this->load->view('myfile', '', true);
Copy after login

例子:有些情况下,你并不想直接输出视图,而是仅仅想得到视图的内容以备后用。那么可以参考如下代码。
<?php class Blog extends CI_Controller { 
	function index() { 
		$data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); 
		$data['title'] = "My Real Title";
		$data['heading'] = "My Real Heading"; 
		$buffer = $this->load->view('blogview', $data, true); 
	}
} 
?>

Copy after login


view方法中的第三个参数表示不输出视图,而只是将结果返回给一个变量。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles