Most Simple Template Library for CodeIgniter

Example

How you usually load a view:

$this->load->view('about', $data);

How you load a view into a template with this library:

$this->template->load('template', 'about', $data);

That loads the view about.php into template.php.

Installation

  • Put Template.php into system/application/libraries
  • Autoload it in config/autoload.php:
$autoload['libraries'] = array('template');

How to use it

Create a template file

views/template.php

<html>
<body>
    <div id="contents"><?= $contents ?></div>
    <div id="footer">Copyright 2008</div>
</body>
</html>

$contents is where your view will be inserted.

Create a view

views/about.php

<h1>About</h1>
<p>I'm so human!</p>

Load the view into the template

In your controller:

$this->template->load('template', 'about');

How this library works

The view is loaded into a variable which is given to the template.

var $template_data = array();
 
function set($name, $value)
{
	$this->template_data[$name] = $value;
}
 
function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{               
	$this->CI =& get_instance();
	$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));			
	return $this->CI->load->view($template, $this->template_data, $return);
}

Advanced use 1: more slots in your template

Example: you want to set the page title.

Add an HTML header to views/template.php

<head>
    <title><?= $title ?></title>
</head>

Set the title in your controller before loading the view:

$this->template->set('title', 'About me');

Advanced use 2: highlight the current navigation item

Navigation is usually part of the template. However, it's a good practice to highlight the item corresponding to the current page, so your visitors know where they are.

Define your navigation items

Add to libraries/Template.php under $this->set('contents...:

$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));

Update your template

Add in views/template.php:

<ul class="navigation">
	<?php foreach($nav_list  as $i => $nav_item): ?>
		<li class="<?= ($nav == $nav_item ? 'selected' : '')?>">
			<?= anchor($nav_item, $nav_item) ?>
		</li>
	<?php endforeach ?>
</ul>

To be able to use the anchor function, autoload the url helper in config/autoload.php:

$autoload['helper'] = array('url');

Update your controller

Add:

$this->template->set('nav', 'About');

Notes:

  • if all methods of your controller are under the same nav item, you can set the nav directly in the constructor.
  • to actually highlight the current item, define the corresponding CSS (for #navigation .selected).

Advanced use 3: multiple templates

To easily deal with multiple templates, define new load methods in libraries/Template.php instead of modifying the existing one. Advanced use 2 with a custom method:

function load_main($view = '', $view_data = array(), $return = FALSE)
{
	$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));
	$this->load('template', $view, $view_data, $return);
}

Corresponding code in your controller:

$this->template->set('nav', 'About');
$this->template->set('title', 'About me');
$this->template->load_main('about');

Misc

Last code update: November 1, 2008. Previous version is still available.

Contributors:

  • Jram: fix to use views in subdirectories
  • Moshe Teutsch: view loading with CI method instead of include_once. That makes things much cleaner and simpler!
 

Feedback

I know i'm being dense, but how would you change the nav_list items anchor build? Say you want the menu item in the nav list to say Photos but the link itself for navigation purposes needs to point to a controller that may not be named photos?

It will build like
http://www.someplace.com/ci-app/photos
but i really need
http://www.someplace.com/ci-app/gallery/add

Suzi
November 21, 2008
#1

You're not being dense at all.

In libraries/Template.php, set nav_list like that:

$this->set('nav_list', array('photos' => 'Photos', '/gallery/add' => 'Add Photo'));

Then in views/template.php:

<?php foreach($nav_list  as $id => $nav_item): ?>
	<li class="<?= ($nav == $id ? 'selected' : '')?>">
		<?= anchor($id, $nav_item) ?>
	</li>
<?php endforeach ?>

Jérôme Jaglale
November 21, 2008
#2
That works perfect and actually makes sense to me now! Thanks for the help and making the library available. It really is the most simple template library for CI!
Suzi
November 21, 2008
#3
Thank you! for this library :D
Cristopher
January 22, 2009
#4
It seems like a better idea to me to put things in to a configuration file, instead of altering inside the library file itself.
Gunnar
February 23, 2009
#5
Given that this "library" is only 5 lines long, it didn't seem necessary to me.
Jerome Jaglale
February 23, 2009
#6
Jerome, I am trying to use CI form validation with your Template code and am running into some snags. Seems like defining valiation rules (set_rule) is getting lost in translation with I load my page views via the template. Any suggestions?
Lokase
March 22, 2009
#7
I use CI Form Validation with this template library and it worked fine so far. What happens? You don't get that problem when you directly load the view?
Jérôme Jaglale
March 22, 2009
#8
"You don't get that problem when you directly load the view?" Correct. I am using the FORM VALIDATION library from CI 1.7.1. I define my set_rules function just before I make the call to your template library. When I run the validation back in my controller it always returns FALSE. I have set up one very simple rule for "required" and I am inputting text in the field so that the test "SHOULD" pass and return TRUE, but it never does. All indications is that set_rules is losing its coupling to the form after I call the load in the Template library. Are you using CI 1.7.1? Perhaps I am overlooking something when I set up my validation rules? Could you post some of your code that you use for validation? Thanks for any help you can offer. Lowkase

March 23, 2009
#9
You set the rules before running the validation, right? This is how I do it:
		$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean');

		if ($this->form_validation->run())
		{
			// update database here
			// ...
			
			// redirect
			redirect('home');
			return;
		}

		$this->template->load('template', 'user_form');	
Jérôme Jaglale
March 23, 2009
#10
Jerome, Thank you VERY much for the sample you posted. My problem had nothing to do with the template library and everything to do with my lack of understanding the validation library. Your sample code has set me on the right path and everything is now working as it should. I have found your template library simple, powerful and easy to use. It has been the perfect solution for my template needs. One thousand thank yous!
Lowkase
March 23, 2009
#11
this is an amazing find! thank you so much!
John
April 7, 2009
#12
Thank you very much, I have added a small modification in this class. you can view it here http://www.asim.pk/2009/05/07/template-library-for-codeigniter-simple-fast-and-easy/ Thank you once again
Asim Zeeshan
May 7, 2009
#13
I can't seem to get this library to add show the view in $contents. It merely prints that out in the source instead of loading the view into it. Any ideas?
Robert
May 7, 2009
#14
Robert, short tags may not be enabled on your server, try:
<?php echo $contents;?>
Jérôme Jaglale
May 7, 2009
#15
Wow, this is so elegant. +1 for you.
Ben
May 14, 2009
#16
Love this library but I have one question. How, if you know, is it possible to pass the default 404 page into master template view content area ?
Andy
May 19, 2009
#17
Andy, have a look at Custom 404 error pages with CodeIgniter.
You can call $this->template->load() from the error_404() method.
Jérôme Jaglale
May 19, 2009
#18
Hello I'm starting the use of your library and get some char errors (my first language is portuguese). DO you have any idea how can I fix it?
Daniel Peralles
May 25, 2009
#19
Daniel, use the UTF-8 encoding for your PHP files (check your text editor settings) as well as for your HTML template (<meta http-equiv="Content-type" content="text/html; charset=utf-8" />).
Jérôme Jaglale
May 25, 2009
#20
Great .. It's working perfectly! Tks a lot!

May 26, 2009
#21
$contents not catching nav items like for example $this->set('nav_list', array('photos' => 'Photos', '/gallery/add' => 'Add Photo')); when clicking the link it goest to http://localhost/myci/index.php/photos/ and it says 404 error?
JingCleoVil
May 30, 2009
#22
This is great, thank you so much.. i've been searching for hours before i found your solution. However, i did ran into a little problem. When trying your "Advanced use 2:..." I got "Undefined variable: nav_list" and "Invalid argument supplied for foreach()" both error points to this line of code "<?php foreach($nav_list as $id => $nav_item): ?>" ..any ideas what went wrong?
Raza
June 18, 2009
#23
Raza, have you defined $nav_list in libraries/Template.php?
Jérôme Jaglale
June 18, 2009
#24
Jerome, thanks. I found my mistake. I've inserted the "$this->set('nav_list', array('photos' => 'Photos', '/gallery/add' => 'Add Photo'));" after the "return $this->CI->load->view($template,....." line. I'm totally blinded somehow not seeing that before, but your question revived me. :) Again thank you sooooo much for an awesome, simple yet functional code. You're my hero... :)
Raza
June 18, 2009
#25
Hi Jerome, I am new to CI. I tried your template, but why does it only show the template (the copyright), but it doesn't show the content in the about.php? I am using CodeIgniter_1.7.1. When I simply use $this->load->view('about') it works fine. Thanks.
Ana
July 1, 2009
#26
Hi Ana, have you put <?= $contents ?> in views/template.php? Do you get any error?
Jérôme Jaglale
July 1, 2009
#27
I found out the problem, it turns out that short tags in my config is FALSE, I change it to true, and it works fine:)
Ana
July 1, 2009
#28
Great library! I have a one question how to change this library to work with HMVC library. It's very important form me. I'm a newbe with CI and PHP :)
Peter (Poland)
July 5, 2009
#29
Hi Peter, have a look at this thread:
http://codeigniter.com/forums/viewthread/121545
Jérôme Jaglale
July 5, 2009
#30
hi,it's very nice library,thanks for it :) I'm begginer n I wanna aks, what if I put my template outside CI's system direktori?? how to make it? my case was: I've got template from internet,then extract it to folder 'light' under folder 'templates' my file structure was like this: |system |application |templates |light |images |style.css |header.php |body.php |footer.php |user_guide how to use your library to my template? Help me Please, Thank you :)
Fikri
July 15, 2009
#31
haha,sorry..it seems I can't write well my file structure here.so this the images link of my file structur.check it out please :) http://i32.tinypic.com/148ixix.jpg help me please,TQ
Fikri
July 15, 2009
#32
haha,sorry..it seems I can't write well my file structure here.so this the images link of my file structur.check it out please :) http://i32.tinypic.com/148ixix.jpg help me please,TQ
Fikri
July 15, 2009
#33
good tool. thnx
Nicolas Rios
July 17, 2009
#34
Absolute n00b here... So maybe I'm just missing something but the nav links do not work at all. Additionally it would be great to see how I could use a multi dimensional array for navigation; nested list. Any help would be great!
Jason C
July 19, 2009
#35
Thanks Jérôme Jaglale, i have read this tutorial page it realy help me to understand the Code Igniter template. Thanks again
Santo Soetarmin
August 11, 2009
#36
Thank you for this simple tutorial! It helped me a lot!
Francus
August 19, 2009
#37
that's nice effort :) i am not sure why CI is not taking steps to add some template handling library in new versions...

August 22, 2009
#38
Hello, I am trying to figure out how to pass a variable into the view that is loaded into the template file. eg. views/About.php contains: <h1>About</h1> <p><?php echo $copy; ?></p> In the controller I have: $data['copy'] = 'Some text'; $this->template->load('template', 'about', $data); But the copy value does not seem to get passed through the chain down in to the loaded view. Any ideas on what I can do to make this work?
Natacha
August 28, 2009
#39
Ooops. Trying again without html encoding. Hello, I am trying to figure out how to pass a variable into the view that is loaded into the template file. eg. views/About.php contains: <?php echo $copy; ?> In the controller I have: $data['copy'] = 'Some text'; $this->template->load('template', 'about', $data); But the copy value does not seem to get passed through the chain down in to the loaded view. Any ideas on what I can do to make this work?
Natacha
August 28, 2009
#40
Ahh. I figured it out!! Looks like it WAS working after all. Coding error on my part. Doh!
Natacha
August 28, 2009
#41
Glad you figured it out. Sorry for the poor code rendering here, I will do something about that.
Jérôme Jaglale
August 28, 2009
#42
i'm having the same issue. How do you pass in a variable to the view that being loaded?

August 31, 2009
#43
Use the $data array
$this->template->load('template', 'about', $data);
Jérôme Jaglale
August 31, 2009
#44
i did, but i keep getting the following error: A PHP Error was encountered Severity: Notice Message: Undefined variable: data

August 31, 2009
#45
This is what i did in the controller: $data = array('test','test2'); $this->template->load('template', 'site/welcome', $data); Then in the view i keep getting an error for undefined $data variable.

August 31, 2009
#46
$data is not used in the view. Have a look at "Adding Dynamic Data to the View":
http://codeigniter.com/user_guide/general/views.html
Jérôme Jaglale
August 31, 2009
#47
Thanks, i haven't used CI for a while now and totally forgot the $data array was actually used. BTW, this template system is very very clean and light. I like it alot.

September 1, 2009
#48
Totally love this library... can't believe it's not a default feature of CI Good job!
Erik
September 2, 2009
#49
I hate this library...it is making me redo my entire application because it is so awesome! ;) I can reduce ~20,000 lines of code (no joke) by using this. I'm about 3 days into it and so far so good.
pmoroom
September 3, 2009
#50
Goog library thanks. I will modify it and share if U want. Contact with CI creators they must want your library!!!
Arshak Grigoryan
September 12, 2009
#51
Thanks so much for this. A really simple library but precisely what I needed.
byrnef87
September 15, 2009
#52
Thanks for this, Jérôme. I now dislike CI a little less.
Joe
September 28, 2009
#53
Genial
Roberto Nunes
October 22, 2009
#54
Hello Jérôme. I used your library on a recent project and found it very simple and easy to use... Thank you very much. I am now starting another project and am trying to get your library to work with Matchbox modules but seem to be having some trouble getting it all to work together. Can you provide some assistance or at least point me in the right direction? Thank you in advance...
Sean Brannan
November 2, 2009
#55
This looks very simple and thus promising. Thanks in advance.
Philipp
November 25, 2009
#56
Hello, I have this notice and warning in this url: http://127.0.0.1/CodeIgniter_1.7.2/index.php/welcome/contact A PHP Error was encountered Severity: Notice Message: Undefined variable: nav_list Filename: libraries/Loader.php(673) : eval()'d code Line Number: 6 A PHP Error was encountered Severity: Warning Message: Invalid argument supplied for foreach() Filename: libraries/Loader.php(673) : eval()'d code Line Number: 6 Can you help me? Thanks.
Tomas
December 6, 2009
#57
Hello Just to say thank you for this simple idea of how to manage views ! I love it and its so much more flexible than the template parser imo. :)
Sky
December 13, 2009
#58
Hello, just to thank you a lot for this :), Im a ruby on rails programmer trying to switch to CodeIgniter framework because of the problems with rails (like speed >:( ), I was definitely looking for this and I hope you don't get upset if I use your library for a public project, I won't modify your library at all :P (hope all copyrights are there for you ;) ), thanks a lot :D
MarkNotOnRailsAnymore
December 28, 2009
#59
Hi can anyone please help me to figure out how to use two blocks of data in a template? let's say I have this in template.php
<?php echo $contents ?>
and therefore 2 view files for 1 page (i.e. blog.php and sidebar_blog.php), assuming there will be different data in sidebar on different pages. I tried adding load_sidebar function to library and calling load('template', 'post'); and load_sidebar('template', 'sidebar_post'); in controller but then my template output is duplicated (which is logical, I called it twice). What should I do?
Artem
January 9, 2010
#60
sorry, I mean "calling load('template', 'blog'); and load_sidebar('template', 'sidebar_blog'); in controller"
Artem
January 9, 2010
#61
to artem: probably you want to use this.... make blog view as variable , so does with the sidebar_blog, than just use the set function --> $blog = $this->load->view('blog','',true); $this->template->set('blog', $blog'); $sidebar_blog = $this->load->view('sidebar_blog','',true); $this->template->set('sidebar_blog', $sidebar_blog'); -->
girista
January 29, 2010
#62
Thank you. I am created:


function parser($template = '', $view = '' , $view_data = array(), $return = FALSE)
{
$this->CI =& get_instance();
$this->CI->load->library('parser');
$this->set('contents', $this->CI->parser->parse($view, $view_data, TRUE));
return $this->CI->parser->parse($template, $this->template_data, $return);
}

www.niloofaran.com
Hossein Salemi
February 6, 2010
#63
Hello I'm just starting in CI, I follow the instructions and I get this:

#
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: nav

Filename: views/template.php

Line Number: 14
"> Home

Do you have any advice
Juan Carlos
February 16, 2010
#64
Hi, can you help me? am new to code igniter and am doing a project in this here i want to pass an array of value from the Library(my own library) to the controler. Is it possible in CI, If so then how???
send reply to "pskumr65@gmail.com".

thakyou all...
satheesh
February 19, 2010
#65
I didn't read all the comments and if someone posted this before, sorry!

I keep all my templates in a sub folder of my views for organizational purposes, so to access them I would have to type:

$this->template->load('templates/template', 'view', $data);

To remove the subdirectory from the function call I did this.

I added this to the library:
var $template_path = 'templates/';

and then within the load function, I altered it to this:

$this->CI =& get_instance();
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view($this->template_path.$template, $this->template_data, $return);

This allows to me to change the path to the template file with one line of code and shorten the function call. However if you have multiple developers you may need to inform them about this behavior. Hope this helps!
Nick
February 25, 2010
#66
Doesnot work for present PHP5

This doesnt work
&lt;?= $contents ?&gt;

Need to change this as

&lt;?php echo $contents; ?&gt;

Why is that
phpKiddo
February 27, 2010
#67
Got the issue ,

short_open_tag = Off

This disables use of \&lt;? =


PhpKiddo grows a year more :)
phpKiddo
February 27, 2010
#68
Nice library thanks you
Danu Sukmawijaya
March 19, 2010
#69
Hi,

Not sure what I am doing wrong but I keep getting the following error:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: contents
Filename: views/template.php
Line Number: 11
David
April 19, 2010
#70
David, are you using $this->template->load()?
Jérôme Jaglale
April 19, 2010
#71
yes
David
April 19, 2010
#72
Must be a typo somewhere. $contents is set in the library code.
Jérôme Jaglale
April 19, 2010
#73
I copied the example at the top of the page and pasted it into their associated files and still get the same error. I am using CI 1.7.2.
David
April 19, 2010
#74
Here is my source:

controllers/products.php
class Products extends Controller {
function Products()
{
parent::Controller();
}
function index()
{
$this->template->load('template', 'about');
}
}

views/template.php
&lt;html&gt;
&lt;body&gt;
<div id="contents">&lt;?= $contents ?&gt;</div>
<div id="footer">Copyright 2008</div>
&lt;/body&gt;
&lt;/html&gt;

views/about.php
<h1>About</h1>
<p>I'm so human!</p>

Please let me know if you see something wrong.
David
April 20, 2010
#75
The folder "system/application/libraries" folder already had a Template.php file in it (that contained the CodeIgniter CI_Template class) which did not get overwritten.

I uploaded this libraries Template.php as Template2.php, changed the class name to Template2 inside of it, changed the autoload entry to "template2" and called $this->template2->load
inside of the controller. Everything worked!

I am new to CI, but I would think that the CI Template.php file would be system\libraries folder - any thoughts?
David
April 20, 2010
#76
David, "system/application/libraries" is empty by default.
Jérôme Jaglale
April 20, 2010
#77
Thanks Jerome, not sure how the first template file got there but I am just going to remove it...
David
April 22, 2010
#78
Great thanks for the template library :)
smronju
June 2, 2010
#79
your template stuff makes the site more slow. Every single time to load a view it will have to call $this->CI =& get_instance(); and other stuff... try to think in other solution.
tresloukadu
June 3, 2010
#80
tresloukadu: get_instance() returns an existing instance so it shouldn't slow things down. You should cache your pages anyway.
Jérôme Jaglale
June 3, 2010
#81
Good Work
Mhabub Mamun
June 8, 2010
#82
This library is great! I'm adding a few methods to the library.

CSS/JS loading.
e.g. add, display

I'm also adding a method to set the template. I like to set the template in the constructor. Also if I choose to add functionality for the user to change the template.

e.g. set_template
Daniel Cronin
July 12, 2010
#83
Hi,

How do load contents to selected sections?

48dreads
July 12, 2010
#84
i mean load "view" in selected section.

example:

<div id='menu'?&gt; &lt;?= $menu; ?&gt;</div> <-- this will load html view menu
<div id='content'?&gt; &lt;?= $content; ?&gt;</div> <-- this will load view html content
<div id='footer'?&gt; &lt;?= $footer; ?&gt;</div>

48dreads
July 12, 2010
#85