How to Parse HTML template in Codeigniter


Sometimes we need to parse HTML data, for example to send an email with HTML template. In this tutorial I will explain how to parse HTML template in CodeIgniter. In CodeIgniter a Template Parser Class exists, which handle html template parsing process. The Template Parser Class parses pseudo and simple variables tag pairs contained within the view files.

Pseudo-variable are enclosed in braces like below:

{title}
{body}

So you need to add pseudo-variables in your html to parse html template in CodeIgniter. Create a view file in application/view/parse-template.php and add some pseudo-variables with html to parse html template in codeigniter.

<html>
<head>
</head>
<body>
<h1>{title}</h1>
<p>{body}</p>
</body>
</html>

Now we need to replace these pseudo-variables to our variable values.
First we need initializing the Class like below:

$this->load->library('parser');

Now after initiate class we can use template parser class function $this->parser->parse() to parse html like.


$data = array('title' => $title, 'body' => $body);

//loading view file to parse function.
$message = $this->parser->parse('parse-template', $data, true);

Note: if you do want the data returned instead of sent to the output class you can pass TRUE (boolean) to the third parameter.

This is an example to show how easily you can manage html template parsing in CodeIgniter. For more information CodeIgniter doc section have good tutorials follow Template Parser Class.