Designing a Better View
At this stage, you might ask why we are going through so much effort to serve up a simple HTML page. Why not put everything in one file? For a simple site, that's a valid point—but whoever heard of a simple site? One of the coolest things about CI is the way it helps us to develop a consistent structure, so that as we add to and develop our site, it is internally consistent, well laid out, and simple to maintain.
At the start, we need three common steps:
• Write a stylesheet
• Update our config file to specify where the stylesheet is
After this is done, we need to update our controller to accept parameters from the URL, and pass variables to the view.
First, let's redesign our view and save it as:
system/application/views/testview.php.
Strict//EN'http:\/\/www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http:\/\/www.w3.org/199 9/xhtml'>
<title>Web test Site</title>
<base href= <?php echo "$base"; ?> >
<link rel="stylesheet" type="text/css" href="<?php echo "$base/$css";?>">
<h1><?php echo $mytitle; ?> </h1> <p class='test'> <?php echo $mytext; ?> </p>
It's still mostly HTML, but notice the PHP 'code islands' in the highlighted lines.
You'll notice that the first bits of PHP code build in a link to a stylesheet. Let's save a simple stylesheet as mystyles.css, in the site's root folder. It just says:
margin: 5px; padding-left: 10px; padding-right: 10px; background: #ffffff; color: blue; width: 100%;
margin: 5px; padding-left: 10px; padding-right: 10px;
background: #ffffff; color: red; width: 100%;
That gives us two styles to play with, and you'll see we've used them both in the view.
Firstly, let's add an entry to the config file: $config['css'] = "mystyles.css";
This is simply to tell the site the name and address of the CSS file that we've just written.
But note that the link to the stylesheet is referenced at $base/$css—where do those variables $base and $css, get their values? And come to think of it, those variables $mytitle and $mytext at the end of the code? We need a new controller!
Post a comment