CodeIgniter Tip: Body class tags

WordPress 2.8 came out with the body_class() function which allows you to hang your per-page (or per-whatever) CSS off of dynamically generated class attributes on the body HTML tag. I’m going to show you how to have some of that flexibility when using the CodeIgniter PHP framework.

CodeIgniter URLs often take the form of http://my-cool-website.com/account/change-password, where account is the controller and change-password is the function. I want CodeIgniter to automatically put a CSS class “account-change-password” on the body tag whenver a user visits that page.

Step 1. Edit controllers/application.php

Application is the superclass of all of my other controllers, including the Account controller. Here we add 2 variables and populate them in the Application() constructor.

class Application extends Controller {
 
  var $controller;
  var $function;
 
	function Application() {
	  parent::Controller();
	  $this->controller = $this->uri->rsegment(1); // The Controller
          $this->function = $this->uri->rsegment(2); // The Function
	}

Step 2. Edit the body tag in your layout template

<body class="<?php echo $this->controller; ?>-<?php echo $this->function; ?>">

now you’re ready to make up some CSS such as

body.account-change-password  #main-content ul {
  list-style-type: none;
}

So now your page elements can have alternate CSS targeted to which controller-function page is currently displaying.