Views are your template files. They are what is output to the browser, and should be mostly HTML code, with some PHP code. Put simply, views are HTML files of your template; they can also be page segments, such as a header or footer. View files can also call other views, if you need such flexibility.
Views are located in the system/application/views/
folder, and can be stored in subfolders inside this main views
folder.
Loading a view is done in the same way as loading a model; it takes just one line of code.
$this->load->view('view_name');
Here, view_name
would be the name of the view file that you wish to load. You can also pass an array of data to a view file by passing an array as the second parameter of the load->view
function.
$data['title'] = "My Web Page"; $this->load->view('view_name', $data);
You would then be able to use the variable $title
in your view file to echo out the page title.
You load multiple views in the same way as you load just one view. CodeIgniter intelligently handles multiple calls to $this->load->view
, and will append these calls together. Here is an example:
function index() { $data['title'] = "My Web Page"; $this->load->view('header', $data); $this->load->view('navigation'); $this->load->view('content'); $this->load->view('footer'); }
Adding data to a view file is a very simple process, which we have touched upon already. You pass data to a view file by using the second parameter of the load->view
function. All view data must be passed as an array or an object. This is because CI runs this array or object through PHP's extract function, which simply takes an object or array key and creates a variable for it with the same name. Let's look at an example:
$data = array( 'title' => "My Web Page", 'heading' => "Welcome to my web page", 'content' => "This is my first web page using Codeigniter!" ); $this->load->view('main', $data);
You will then be able to use this data in your view, as illustrated below:
Creating loops in view files has been a stumbling block for a few developers. By passing a multidimensional array to a view file, you can easily establish a loop in any of your view files. Let's take a look at an example.
<?php class Todo extends Controller { function index() { $data['todo_list'] = array("buy food", "clean up", "mow lawn"); $this->load->view('todo', $data); } } ?>
This is a very simple Controller. Your view file for this would be as follows:
You are also able to return view files as data; this can be useful if you wish to process this data in some way. Simply set the third parameter to boolean TRUE
—and it will return the view data.
$this->load->view('welcome', NULL, TRUE);
CodeIgniter uses an output buffer to take all calls to the load view function, and processes them all at once, sending the whole page to the browser at the same time. So when you return views as data, you will be able to save the contents of the view inside a variable for whatever use you need.