When I first began to consider building a web application using CodeIgniter, one of the key aspects I had in my mind was to keep the HTML template files (the View in Model-View-Controller) as PHP-free as humanly possible.
At that time, I was planning to develop an e-commerce application (this was before the launch of Magento), so my reasoning was that a distributed web app should make it easy for programmers to work on backend code while allowing designers to hack on the templates without having to understand a bunch of complicated PHP statements.
CodeIgniter’s Template Parser Class
To pass data from the Controller to the View in CodeIgniter, you would normally load the view template and pass in an array of data:
$this->load->view('my_template', array(
'page_name' => 'About Us',
'page_content' => 'Hey, we are a great company!'
));
The array of data is transformed into local variables for use within the template:
<h1><?= $page_name ?></h1>
<p><?= $page_content ?></p>
That’s all very well with basic variables, but when it comes to arrays your template can quickly become cluttered with nested if, else, and foreach statements - and that can be confusing for non-technical designers or purely front-end (HTML/CSS) developers.
The Template Parser Class replaces those PHP echo statements with special variables that, in theory, are easier to understand:
<h1>{page_title}</h1>
<p>{page_content}</p>
<ul>
{link_list}
<li>{link_description}</li>
{/link_list}
</ul>
For simple strings and basic arrays, the Parser class is easy to use - but once you start wanting to use different HTML depending on the values of your data, it can get messy. With embedded PHP in the templates, it is easy to throw a little logic into the View file - if it’s this then add that class name - but following a strict “No PHP” rule can have you jumping through hoops if your HTML isn’t architected to cope with displaying different types of data in the same way.
Of course, the whole point of MVC is that you shouldn’t be putting logic in your Views, so there really shouldn’t be any major hurdles in solely using the Parser class - but it’s going to take me a little while to get used to thinking that way.


Leave a Reply