Sunday, May 10, 2009

Creating CodeIgniter Views [ Step 4 ]

It's not considerate a good practice to send an information to your web-browser directly from your controller so create a correspondent view file to do that I name this one blog_view.php in the views folder Unlike controllers which must be named identically to class name,
view files can be what ever you want, I simply choose this that correlation is clear for a
tutorial, but you can name what ever type of abstraction your like. Your can add further organization by organization a sub folders within a view folder to give you a dipper structure if you want.For now I just paste some simple html
<html>
<head>
<title> My First page </title>
</head>
<body>
<h1> My First Heading </h1>
</body>
</html>
with a title and page heading, now that's done, I go back to the controller blog.php and load a view file form the controller by replacing the echo statement with a view load function
class Blog extends Controller
{
function Index()
{
this->load->view (blog_view);
}
}
you know that a parameter I using is a same as filename for the view file, you can use the file extension if you want but it not necessary.I can now go back to a browser and reload a page and see new view file is been serve up from the controller, at this point, view file is just a static web page, so I want to replace some of the static elements with the dynamic once.

Adding dynamic data to view.

Going back to the controller blog.php I create a data array which control some dynamic information that pass to the view file,
class Blog extends Controller
{
function Index()
{
data['title'] = "My blog title";
data['heaading'] = "My blog heading";
this->load->view ('blog_view', $data );
}
}
Now I can take this data array and place it as a second parameter in view loading function and pass that information under the view file, in doing this the index of the var array will also be a converted to variables to make them easily work with a view files. So I go to a view file and replace static information with dynamic information, with some simple PHP
<html>
<head>
<title> <?php echo $title; ?> </title>
</head>
<body>
<h1> <?php echo $heading ; ?> </h1>
</body>
</html>
If now I save and reload page in a browser you can see that now our controller is dynamically passing the title and a heeding in the view file. If you service support PHP short tags you can simplify this a bit , replace "?php echo" statement with an equal sine eliminating semicolons, and simplify control structure. If you build you site with a help of the web-designer, this can be beneficial because it reduce the amount a PHP code on the page and make a page look cleaner.
<html>
<head>
<title> <?=$title; ?> </title>
</head>
<body>
<h1> <?=$heading ; ?> </h1>
</body>
</html>

No comments:

Post a Comment