CodeIgniter: Load View from Database (more or less)

I have seen a few people asking how to load a view from a database (or something other than a physical file in the “views” folder).

In my particular case, a client wants the ability to edit HTML and TEXT email templates. Without giving them direct access to editing the physical files, I decided to move the views being used for email to the database instead.

Instead of something like this…

$data = $this->db->get_where('users', array('user_id' => $user_id), 1)->row();
$this->load->library('email', array('mailtype' => 'html'));
$this->email->from('admin@domain.com');
$this->email->to($data->user_email);
$this->email->subject('My Subject');
$this->email->message($this->load->view('emails/welcome_html', $data, TRUE));
$this->email->set_alt_message($this->load->view('emails/welcome_text', $data, TRUE));
$this->email->send();

Try something like this…

$template = $this->db->get_where('email_templates', array('template_key' => 'user_welcome'), 1)->row();
$this->load->library(array('parser', 'email'));
$this->email->initialize(array('mailtype' => 'html'));
$this->email->from('admin@domain.com');
$this->email->to($data->user_email);
$this->email->subject($this->parser->parse_string($template->template_subject, $data, TRUE));
$this->email->message($this->parser->parse_string($template->template_html, $data, TRUE));
$this->email->set_alt_message($this->parser->parse_string($template->template_text, $data, TRUE));
$this->email->send();

Then you can use {curly_braced} items in the resulting email. For instance, if $template->template_subject was “Welcome to my site {user_first_name}” it would arrive to my inbox as “Welcome to my site Robert!”. That of course applies to the HTML and TEXT message as well.

Note: You could add some conditions to initialize the email class differently based on whether or not an HTML email message format is available. Thereby negating alt message and HTML format configuration.

Warning: This is not intended for use with batch mode. I am only offering a solution for one-off personalized emails or messages being sent within a loop. While message content can be customized using this method, personalization is not possible when using “bcc_batch_mode”

Here is the basic table structure used for this example…

CREATE TABLE IF NOT EXISTS `email_templates` (
  `template_key` varchar(32) NOT NULL,
  `template_subject` varchar(255) NOT NULL,
  `template_text` text NOT NULL,
  `template_html` mediumtext NOT NULL,
  PRIMARY KEY (`template_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Feel free to comment.

2 thoughts on “CodeIgniter: Load View from Database (more or less)”

Leave a Reply

Your email address will not be published. Required fields are marked *