Setting Up a Template and Assets in CodeIgniter

In this article, I’d like to walk you through my first few steps when setting up a new CodeIgniter Project: – Setting up a way to render pages in a layout – Setting up a way to easily handle assets (CSS & JavaScript files).

Step 1: Creating A Template

To start, we are going to make two new files, a layout view, and a localized controller. Let’s start by creating a layout.php file in,views and add the following:

<!doctype html>
<!–[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]–>
<!–[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]–>
<!–[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]–>
<!–[if gt IE 8]><!–> <html lang="en"> <!–<![endif]–>
<meta charset=’UTF-8′>
<meta http-equiv=’X-UA-Compatible’ content=’IE=edge,chrome=1′>
<meta name="viewport" content="width=device-width" />
<title>Title Goes Here</title>
<!–[if IE 9]>
<style type="text/css"> .gradient { filter: none;} </style>
<![endif]–>
<!–[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]–>
</head>
<body>
</body>
</html>

I based this code on the HTML5 set up from Paul Irish. We’ll use this as the basis for all of our pages. Now, to use this, we are going to create a MY_Controller inside of appliction/core/MY_Controller.php, and create a new function that we’ll call render

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { protected $layout = 'layout'; protected function render($content) { $view_data = array( 'content' =&gt; $content<br />
    );<br />
    $this-&gt;load-&gt;view($this-&gt;layout,$view_data);<br />
  }<br />
}<br />

This code will allow us to use the layout file to wrap all of our content. We’ve also stored the layout file as a protected variable of the MY_Controller so that we can use different layouts for different controllers if we so choose. Now, let’s modify the template file to be able to render the content. Change the body tag so that it looks like this:

<br />
&lt;body&gt;<br />
  &lt;?= $content; ?&gt;<br />
&lt;/body&gt;<br />

Now, let’s set up an example view and an example controller to see how it works.

<br />
&lt;h1&gt;Hello, World!&lt;/h1&gt;<br />
&lt;p&gt; Example page using layouts &lt;/p&gt;<br />

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Example extends MY_Controller { public function index() { $content = $this-&gt;load-&gt;view('example/index',null,true);<br />
    $this-&gt;render($content);<br />
  }<br />
}<br />

Step 2: Adding the Asset Helper

To help us manage our CSS, JavaScript, and image files, we are going to add some tools for asset manage. First, let’s include this Asset Helper In our project, and update our autoload.php file, so that we include it automatically. Now we are going to set up the directory structure for this. Here is how to do it from the base of your CodeIgniter project (assuming you are using the standard naming conventions):

<br />
mkdir assets<br />
mkdir assets/css<br />
touch assets/css/app.css<br />
mkdir assets/js<br />
touch assets/js/app.js<br />
mkdir assets/images<br />

Now, we are going to keep a list of all the CSS and JavaScript files inside of our MY_Controller, and pass them along to the layout:

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { protected $layout = 'layout'; protected $stylesheets = array( 'app.css' ); protected $javascripts = array( 'app.js' ); protected function render($content) { $view_data = array( 'content' =&gt; $content,<br />
      'stylesheets' =&gt; $this-&gt;get_stylesheets(),<br />
      'javascripts' =&gt; $this-&gt;get_javascripts()<br />
    );<br />
    $this-&gt;load-&gt;view($this-&gt;layout,$view_data);<br />
  }</p>
<p>  protected function get_stylesheets() {<br />
    return $this-&gt;stylesheets;<br />
  }</p>
<p>  protected function get_javascripts() {<br />
    return $this-&gt;javascripts;<br />
  }<br />
}<br />

And now we’ll update our template using the css_asset() and js_asset() functions from the helper we included earlier:

<br />
&lt;!-- in the &lt;head&gt; .. --&gt;<br />
&lt;? foreach($stylesheets as $stylesheet): ?&gt;<br />
  &lt;?= css_asset($stylesheet); ?&gt;<br />
&lt;? endforeach; ?&gt;</p>
<p>&lt;!-- right before &lt;body&gt; --&gt;<br />
&lt;? foreach($javascripts as $javascript): ?&gt;<br />
  &lt;?= js_asset($javascript); ?&gt;<br />
&lt;? endforeach; ?&gt;<br />

If you view the source, you should see that your app.css and app.js files are included.

Step 3: Adding Local Assets

One of the better ideas Rails 3.0 brought to the table was the idea of the ‘asset pipeline’, which includes being able to define JavaScript and CSS files that are specific to a particular controller. Now let’s set up our CodeIgniter project to be able to behave in a similar manner.

That was my motivation for writing the get_stylesheets() and get_javascripts() functions in the MY_Controller class earlier. Since we are going to be changing how we get the arrays, we can now do so without touching the render() function since we have abstracted out the interface in which we get our files.

So let’s update those two functions, and add two more protected variables to our MY_Controller file:

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');<br />
class MY_Controller extends CI_Controller {<br />
  protected $layout = 'layout';<br />
  protected $stylesheets = array(<br />
    'app.css'<br />
  );<br />
  protected $javascripts = array(<br />
  'app.js'<br />
  );<br />
  protected $local_stylesheets = array();<br />
  protected $local_javascripts = array();</p>
<p>  //other parts of the class..</p>
<p>  protected function get_stylesheets() {<br />
    return array_merge($this-&gt;stylesheets,$this-&gt;local_stylesheets);<br />
  }</p>
<p>  protected function get_javascripts() {<br />
    return array_merge($this-&gt;javascripts,$this-&gt;local_javascripts);<br />
  }</p>
<p>}<br />

Now we can add additional asset files to the local_stylesheets and local_javascripts variables in classes that extend MY_Controller, allowing us to keep our code separate and more organized. With this and templates, we now have a system in place to manage the visual aspects of our web application.

Miss your last deadline? Download a Free Chapter of “Dependable: Deliver Software on Time and within Budget”
Click Here to Leave a Comment Below 4 comments
Peter Pike - a couple of years ago

Hi there, am a relative newbie when it comes to PHP and codeigniter, but have one app as PHP under my belt which I realise is a big mess, so am in the process of rewriting. Came across this article of yours and it is exactly what I am looking for. Have followed your steps and am using https://github.com/sekati/codeigniter-asset-helper as my asset helper. THe only difference being the function names which are different. However I am getting the errors as per the screen shot attached. Am also attaching the view source output if that helps. Would appreciate any assistance you or anyone else might be able to offer.
Cheers

Reply
    bhavin jagad - a couple of years ago

    can you show me how you put stylesheet there ? it seems you forget to declare or pass the stylesheet variable.

    Reply
    Akhmad Syarifudin - 9 months ago

    try to use:
    <?php foreach($stylesheets as $stylesheet): ?>

    instead of:
    <? foreach($stylesheets as $stylesheet): ?>

    Reply
Ewen - a couple of years ago

As soon as I saw the short-form php tags, you instantly lost me. Do not follow this example if you are a newbie as it will just introduce you to bad coding practices and a habit that will be hard to kick. In addition, the opening head tag is missing in the html template. Seriously dude…if you’re going to post tutorials, make sure your own code is good.

Reply

Leave a Reply: