Views in CodeIgniter
×

Views in CodeIgniter

2270

  • A view is a webpage or part of a webpage that contains HTML content executed by the user browser.
  • Views interact directly with the user.
  • View files are created into the application/views directory.
  • It can be a webpage or an RSS (Really Simple Syndication) page.

Related Topic:

Codeigniter Features
Codeigniter Interview Questions

Syntax:

<html>
<head>
<title>page Title</title>
</head>
<body>
.......
</body>
</html>

Creating a view:

Create a file first_view.php into the application/views directory.

first_view.php

<html>
<head>
<title>First View</title>
</head>
<body>
<h2>This is the very first view of my application</h2>
</body>
</html>

Loading a view:

We can access the view file with the help of controllers.

Syntax:

$this->load->view("view_name");

Explanation:

  • this: This keyword is used for self-referencing.
  • load: The load is the object of CI_Controller class which we inherit in the controller class.
  • view: This is a method of CI_Controller class that we used to display the content of a view file.
  • view_name: It represents the name of the view which we want to access.

Now, we add this line into our controller file application/controllers/Demo.php to display our view first_view.

Demo.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Demo extends CI_Controller {
public function index()
{
$this->load->view("first_view");
}

public function example()
{
echo "This the example function of Demo";
}
}
?>

Now, enter the following URL into the browser to call the index() function of the Demo controller.

http://localhost/ci/index.php/Demo

Output:

Related Topics:

Codeigniter MVC Framework
Codeigniter controllers
Models in Codeigniter

Note:

We can access more than view by calling the view method in the controller class more than one time.

For example:

We have two other views in the application/views folder.

  • header.php
  • <html>
    <head>
    <title>First View</title>
    </head>
    <body>
    <h2>This is the content of header file</h2>

  • data.php
  • <h2>This is the content of data file</h2>

  • footer.php
  • <h2>This is the content of footer file</h2>
    </body>
    </html>

    Now, access the above three files in the Demo controller.

  • Demo.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Demo extends CI_Controller {
public function index()
{
$this->load->view("header");
$this->load->view("data");
$this->load->view("footer");
}
}
?>

Enter the following URL into the browser to check the result.

http://localhost/ci/index.php/Demo

output:



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments