Saturday, February 18, 2012

Codeigniter: Working with template views

Codeigniter doesn't provide a template engine, and it makes that each views has all html code.
Including files is a good idea, but I'm not happy adding every time de include code, is not DRY.

Well the best way to work with templates is the Decorator Design Pattern, and for make it possible in Codeigniter I was used the Most Simple Template Library for CodeIgniter until that discovered the next: Using another view like template.

Using it is very easy, is not neccesary use other library and you can add any functionality.

How to make it.

Simple use

Controller
public function action(){
   $data = array(
     'view' => 'view_name',
     'title' => 'Hello World'
   );
   $this->load->view('template_tpl', $data);
}

View
php  + view html

Template view
php + general html
$this->load->view($view);
php + general html

File system
/application/views/template_tpl.php
/application/views/view_name.php


Advanced use

If you use different sections in your site/application the simple use is not ver helpful. Following the same philosophy you can make possible it.

Controller
public function action(){
   $data = array(
     'section1' => 'section1',
     'section2' => 'section2',
     'view' => 'view_name',
     'title' => 'Hello World'
   );
   $this->load->view('template_tpl', $data);
}

View
php  + view html

Section
php  + section html

Template view
php + general html
section($section1);
php + general html
$this->load->view($view);
section($section2);
php + general html

File system
/application/views/template_tpl.php
/application/views/view_name.php
/application/views/section_name.php


Solve a little problem

To work with sections, we need to solve a little problem: If you don't send a section name to template, codeigniter show the next error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: variable_nameFilename: views/file.php
Line Number: x
To solve it we need to add this function to our template:
function section(&$name){
    $CI = & get_instance();
    isset($name) ? $CI->load->view($name) : null;
}




Tuesday, February 07, 2012

Codeigniter: Language lines into javascript


I’ve extend language_helper and I’ve added a langJs function.

For use it you only call it with an array including lines for pass to javascript.

Example

In the controller
$this->load->helper('language');
$this->lang->load('calendar', 'spanish');

In the view
[php]

echo langJs(array('cal_wednesday', 'cal_january'));

[javascript]
alert(_msg.cal_wednesday);

Load all lines
If you need load all lines, you can do something like this:

In the Controller

$this->load->helper('language');
$this->lang->load('calendar', 'spanish');
$data['lang_keys'] = array_keys($this->lang->language);

In the View
echo langJs($lang_keys);

As you can see, is very easy passing messages to javascript.
Download Language Helper