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);

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

Installation

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

How to use it

Create a template file

application/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

application/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 passed 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 application/libraries/Template.php under $this->set('contents...:

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

Update your template

Add in application/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 update: November 10, 2011 (updated folder paths for CodeIgniter 2). 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
Nov 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
Nov 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
Nov 21, 2008
#3
Thank you! for this library :D
Cristopher
Jan 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
Feb 23, 2009
#5
Given that this "library" is only 5 lines long, it didn't seem necessary to me.
Jerome Jaglale
Feb 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
Mar 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
Mar 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

Mar 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
Mar 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
Mar 23, 2009
#11
this is an amazing find! thank you so much!
John
Apr 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
Jun 18, 2009
#23
Raza, have you defined $nav_list in libraries/Template.php?
Jérôme Jaglale
Jun 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
Jun 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
Jul 1, 2009
#26
Hi Ana, have you put <?= $contents ?> in views/template.php? Do you get any error?
Jérôme Jaglale
Jul 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
Jul 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)
Jul 5, 2009
#29
Hi Peter, have a look at this thread:
http://codeigniter.com/forums/viewthread/121545
Jérôme Jaglale
Jul 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
Jul 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
Jul 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
Jul 15, 2009
#33
good tool. thnx
Nicolas Rios
Jul 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
Jul 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
Aug 11, 2009
#36
Thank you for this simple tutorial! It helped me a lot!
Francus
Aug 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...

Aug 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
Aug 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
Aug 28, 2009
#40
Ahh. I figured it out!! Looks like it WAS working after all. Coding error on my part. Doh!
Natacha
Aug 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
Aug 28, 2009
#42
i'm having the same issue. How do you pass in a variable to the view that being loaded?

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

Aug 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.

Aug 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
Aug 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.

Sep 1, 2009
#48
Totally love this library... can't believe it's not a default feature of CI Good job!
Erik
Sep 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
Sep 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
Sep 12, 2009
#51
Thanks so much for this. A really simple library but precisely what I needed.
byrnef87
Sep 15, 2009
#52
Thanks for this, Jérôme. I now dislike CI a little less.
Joe
Sep 28, 2009
#53
Genial
Roberto Nunes
Oct 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
Nov 2, 2009
#55
This looks very simple and thus promising. Thanks in advance.
Philipp
Nov 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
Dec 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
Dec 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
Dec 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
Jan 9, 2010
#60
sorry, I mean "calling load('template', 'blog'); and load_sidebar('template', 'sidebar_blog'); in controller"
Artem
Jan 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
Jan 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
Feb 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
Feb 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
Feb 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
Feb 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
Feb 27, 2010
#67
Got the issue ,

short_open_tag = Off

This disables use of \&lt;? =


PhpKiddo grows a year more :)
phpKiddo
Feb 27, 2010
#68
Nice library thanks you
Danu Sukmawijaya
Mar 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
Apr 19, 2010
#70
David, are you using $this->template->load()?
Jérôme Jaglale
Apr 19, 2010
#71
yes
David
Apr 19, 2010
#72
Must be a typo somewhere. $contents is set in the library code.
Jérôme Jaglale
Apr 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
Apr 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
Apr 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
Apr 20, 2010
#76
David, "system/application/libraries" is empty by default.
Jérôme Jaglale
Apr 20, 2010
#77
Thanks Jerome, not sure how the first template file got there but I am just going to remove it...
David
Apr 22, 2010
#78
Great thanks for the template library :)
smronju
Jun 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
Jun 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
Jun 3, 2010
#81
Good Work
Mhabub Mamun
Jun 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
Jul 12, 2010
#83
Hi,

How do load contents to selected sections?

48dreads
Jul 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
Jul 12, 2010
#85
Thanks for this dude! By the way, how can I use this using my images and CSS?
Joenas Ejes
Jul 31, 2010
#86
Hi All, I am Developing a web site. my below code work perfectly. but i have a problem i want "$statsid". this is printed from other query. i want to pass this as variable or id to controller to get the data from table where equls to this "$statsistatsid
it is just like face book like Tom post a comments and there friends comments on tom comments
&lt;?php $statsid=$rows->status_id; ?&gt;
&lt;?php foreach($query2->result() as $rs):?&gt;
<li id="mypost">
<div id="dailyupdate">
<div id="upict"><img >config->item('base_url').$rows->profile_picture_path;?&gt;" /></div>
<div id="comments_update">
<span class="u_title">&lt;?=$rs->user_name;?&gt; </span>&lt;?=$rs->status_comment;?&gt;
</div>
</div>
</li>
&lt;?php endforeach;?&gt;
liaqat Ali
Aug 11, 2010
#87
Just wanted to THANK for such a helpfull code!!!
Best regards :)
María Antignolo
Dec 7, 2010
#88
I can see in my Template.php code it got the contents, but it will not display the contents in the template. Any ideas? My setup is the same as you have shown.
Kidd Chaos
Dec 9, 2010
#89
I think it was the php short tags being off. Nevermind.
Kidd Chaos
Dec 9, 2010
#90
Hi, Jerome, scuse me for grammatic, but i don't speak english...
i have this problem:
#
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: nav

Filename: views/template.php

Line Number: 10
"> Home
for all links
this is my template.php:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 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('nav_list', array('Home', 'Web sites', 'Grafica', 'Contact'));
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view($template, $this->template_data, $return);

}
}

/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */

i'm a very dummie in php and codeigniter, what is the error?

thank's for script and help
pierpaolo(italy)
Dec 16, 2010
#91
i understand, i've not add to my controller:
$this->template->set('nav', 'About');
but now all links are for page not found...
i see the helper'html' don't work, is possible the helper 'url' don't work too, but i don't undertand for what.
pierpaolo(italy)
Dec 16, 2010
#92
now the helpers are good, but the links return page not found
pierpaolo(italy)
Dec 17, 2010
#93
Hi jerome
I'm realy interested in your tutorial.
It worked, and since I'm newbie, but my job demands me to get along with codeigniter and javascript. I wanna know, what would it looks like if the changing of the page content of your "simple sample" was triggered by a button click,which means you have to include some script to make it happen? I hope I could see your reply, ASAP. And I hope you could understand my words, since I'm Indonesian. Thx a lot
Sian
Dec 20, 2010
#94
I have a correction, what if your content is triggered from a link, and it controlled by javascript.Thx in advance.
Sian
Dec 20, 2010
#95
Can this be converted to use the parser class?
thanks in advance!
BuKToP
Jan 27, 2011
#96
Thanks for the library. I am new to CodeIgniter and just downloaded 2.0.0. The Template parser class provids a similar funtionality. From the performance point of view, is there an advantage to using this method over the 2.0.0 template parser class:

http://codeigniter.com/user_guide/libraries/parser.html


Saeed D.
Feb 12, 2011
#97
Thank you! Vere usefull..
Stas
Feb 16, 2011
#98
Why you store as reference here:

$this->CI =& get_instance();

and not:


$this->CI = get_instance();

This is causing all types of problems when using magic methods like __get and __set.
johnmerlino
Feb 27, 2011
#99
@Saeed D.
You can load a page inside of a "themed" template.

The parser is just replacing PHP's code with readable code.
InspireDat.com
Apr 3, 2011
#100
I placed Template.php in the system/application/libraries folder. I've added template to the library array in autoload.php as suggested above, but get this error:

Severity: Notice

Message: Undefined property: Welcome::$template

Filename: controllers/welcome.php

Line Number: 28

If I load the library in the controller like this:

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

It works.

I'm still getting my legs with CI but I was under the impression that autoloading a library precluded the need to load it at the controller level. Do I have that wrong?
Randy
Apr 4, 2011
#101
Ah, never mind. I was autoloading another library after I loaded the template library. All I needed to do was this:

$autoload['libraries'] = array('form_validation', 'template');

Nice library. Thank you. This is how I imagined the template system would work by default in CI. Very sensible.
Randy
Apr 4, 2011
#102
Thank you very much. Just what I needed, simple and elegant solution.
broadband
Apr 16, 2011
#103
This template library does not allow you to link external stylesheets within the template. I tried and the browser cannot find the external stylesheet.
john
Apr 17, 2011
#104
The stylesheets problem is simple to solve :
I've created an assets folder on the root of my project, with a css folder in it, you only need to put a variable in your code to find the css file and it works fine.
Luiz
Apr 19, 2011
#105
very very good , i am beginner with codeigniter
thanks alot
in arabic "???? ??" :D
mohamed
Apr 21, 2011
#106
i could not for the life of me figure out why it was only showing the home link in my menu div.

silly boy that i am i never defined the 'li' tag in my css to 'display: inline'.

working like a charm now.

super library, only started to learn oop yesterday. i can't believe how powerful it is :)

many thanks for sharing this
Dave
May 1, 2011
#107
Is it possible to have an empty view?

i.e. sometimes I just want to load the tempalte without any view content, if I don't pass that I get an error "Unable to load the requested file: .php"

thanks
Gr
May 5, 2011
#108
Thank you!
Paul du Long
May 11, 2011
#109
thanks.
artiom
May 16, 2011
#110
I am very new to codeigniotr and I am sure I am just missing something. I am unable to get this library to load. For one my codeignitor setup did not have a system/applications/libraries folder.
I am getting this message when I try to auto load the library as well as load it from my controller.
Message: Undefined property: Home::$template.
Controller code:
$this->load->library('template');
$this->template->load('template');
Config autoload
$autoload['libraries'] = array('template');

Any help would be greatly appreciated!
Allen
May 16, 2011
#111
@GR, regarding the empty view, just create a blank php file, name it empty_view, and call it via template

@allen, put it in Application\Libraries\Template.php
kyri
May 20, 2011
#112
please...am stuck!!! i got a template that does load css within it and has 3 pages namely home, about, fixtures and results.
the problem comes when i want to load the about view with some content in div that has a styling of h2 and p. How do i go about it
kenyana
Jun 3, 2011
#113
Hello, I'm creating a website and I'm using a theme that I downloaded from ThemeForest.

I put all the theme in a folder called template in the view folder so when i load i just go with
$this->template->load('template/index', 'blog', $data);

The problem is with css and images.
How can i include css (better dynamically) and js? The files are in "views/template/css" and "views/template/js"

Thanks a lot.
M
Mike
Jun 9, 2011
#114
This is very helpfull to me...


Thank & Regards,
Nilesh Pangul
Nilesh Pangul
Jun 11, 2011
#115
I have added this function at the end of file &#40;out of the class&#41; next function thats validate if a variable has been seted.

&lt;?php
function section(&$name){
echo isset($name) ? $name : null;
}
?&gt;

In the template use:

&lt;?php section($variable)?&gt;

porquero
Jul 6, 2011
#116
I not understand how use the Template Library with the Parser. I can't use "{var}" in my template/views...

Any tips, folks?
Tárcio Zemel
Jul 20, 2011
#117
OK, only now I saw the Hossein Salemi function (#63). It work now! ;-)
Tárcio Zemel
Jul 21, 2011
#118
If you want to use the parse() function in many controllers, here's a tip: put the Hossein Salemi function (#63) in MY_Controller (http://codeigniter.com/user_guide/general/core_classes.html).

Regards!
Tárcio Zemel
Jul 25, 2011
#119
How to load helper('url') into template ?
Gilliano
Sep 1, 2011
#120
@Gilliano:
As long as the helper is called in the calling controller, it should work fine.
Rystraum Gamonez
Sep 4, 2011
#121
Hello sir Jérôme Jaglale,
i just want to ask on how to put link into the menu...

<b>('Home', 'Photos', 'About', 'Contact')</b>

this tutorial is the best!

:)

Cheers!


Mark Diaz
Sep 29, 2011
#122
I also crate a template library that very look like to Wordpress theme. If you are familiar with wp theme, you can try my <a href="http://www.webinone.net/code-snippet/codeigniter-template-library-for-wordpress-fun/">template library here.</a>
webinone
Oct 19, 2011
#123
I need to query for my nav_list in the Template class. Setting is statically is easy, like you showed... but how can I make a model available in the load function of Template class?

BTW, very nice work!
liftnheavy
Nov 26, 2011
#124
Hi,

this is working great for me, but is it compatible with CI localization support, ie application/language/english/{files}_lang.php ?
alasdair
Dec 13, 2011
#125
You probably shouldn't use short tags for code you publish for other people to use.

I appreciate your work (It helped me a lot), but using short tags instead of the full syntax really had me pulling out my hair.

I'm referring to:
&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;

Where &lt;?= $contents ?&gt; should really be &lt;?php echo $contents; ?&gt;

If you're developing an app that is to be distributed, you can't rely on short tags always being available.
Axel
Jan 17, 2012
#126
Hi, I think you're french but anyway...

Just a question. Is it possible to "$this->set" a variable to the view itself instead of the layout file ?

For example if I do

$this->template->set('title', 'toto');
$this->template->load('layout', 'home');

I can call $title in the layout.php file but not in the home.php is it normal ?

Thanks for your help & and of course for your library

Vinz
Vinz
Jan 24, 2012
#127
Well, I did like that ...

function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{

$this->CI =& get_instance();
// Added start
if(!empty($this->template_data)){
$view_data = array_merge($this->template_data,$view_data);
}
// end
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view($template, $this->template_data, $return);
}

And now I can set a variable with $this->template->set('foo','bar'); in the construct controller for example and call it in all methods and views.

Just take care with name conflict I guess

I hope it's not so bad

Vinz
Vinz
Jan 24, 2012
#128
This awesome halpful for me,,

I'm too new in CI, and just try to learn everything about it.
I'm using CI 2.1.0 + this library;

frist install i got some error. but after I try to change :

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);
}


become :

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



My first CI can run properly..

thanks for awesome work :D
feryardiant
Feb 11, 2012
#129
In Advanced use 1:
while setting the 'title' in the controller like below its not working
$this->template->set('title', 'About me');

The error is showing like
Message: Undefined variable: title
Ashish
Mar 9, 2012
#130
It might be a small library, but it is very useful. Thanks also for the instructions and the examples. It was just what I needed :-)
Philip
Apr 11, 2012
#131
I've expanded a bit this library to fits my needs.

function set($data, $value = FALSE)
{
if(! is_array($data)) {
$this->template_data[$data] = $value;
} else {
$this->template_data = $data;
}
}

Now you can pass an array of data, if you are lazy like me and you want to pass in some more data, so instead of writing:

$this->template->set('some_data', 'some value');

you could now do it like:

$tpl_data = array(
'title' => 'About Page',
'meta' => 'CodeIgniter Template library, CI library ...'
);
$this->template->set($tpl_data);


Cheers,
- shkabo
shkabo
Jul 2, 2012
#132
thank you for tutor
funny
Sep 4, 2012
#133
Hello Jérôme!

What nice library! Thanks for share it.

I was doing it on more complex way. ;)

Well, to fill my needs (and allow more clear way to change from my method to yours) I made a few changes on your code, which I would like to suggest you:

1. I've included a test on the library to make sure that the given template is available on the application. If not available, then the library returns the content itself (without a template).

2. I've created 3 new constants to handle the templates' (or layouts) path and place them at ./index.php. This way, if you need to change the structure of application directories (some day) you'll just need to do it on a unique file.

Now, let me show you the changes ...

1. ./application/libraries/Template.php

...

function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{
$this->CI =& get_instance();

/*
* Make sure that the given template exists
* If not exists, then return the content itself.
* The LAYOUT_APP_PATH and LAYOUT_PATH constants are defined at ./index.php
*/

if (file_exists(LAYOUT_APP_PATH.$template.EXT))
{
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view(LAYOUT_PATH.$template, $this->template_data, $return);
}
else
{
return $this->CI->load->view($view, $view_data, $return);
}
}

...


2. ./index.php

...

/*
|---------------------------------------------------------------
| DEFINE LAYOUT APPLICATION CONSTANTS
|---------------------------------------------------------------
*/

define('LAYOUT_DIR', 'layouts/');
define('LAYOUT_PATH', '../'.LAYOUT_DIR);
define('LAYOUT_APP_PATH', APPPATH.LAYOUT_DIR);

/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------

...


Well, that's it! What do you think?

Let me know at rogerio [dot] taques [at] gmail [dot] com.

Cheers.
Rogério
Oct 5, 2012
#134
Very nice information, with help of your tut i have just created a layout.

<a href="http://phpflow.com">phpflow.com</a>
parvez
Oct 24, 2012
#135
Very helpful. Integrated into my entire site very quickly and easily. Thanks!
Joe Masilotti
Nov 22, 2012
#136
I was having a problem of assigning array from my controller and calling it from the $contents in my view.. So i did a little adjusted to your library which goes thus:

function load($template = '', $view = '' , $view_data = array(), $return = FALSE){
$contentx = $this->CI->load->view($view, $this->template_data, TRUE);
$this->template_data = array(); // Custome me
$this->set('contents', $contentx);
return $this->CI->load->view( $template, $this->template_data, $return);
}

This way i can easily write something like this my controller

$this->template->set('nav_list', array('home','contact','thankyou'));
$this->template->load('column1', 'welcome');

And to imitate your sample code above which says:
Add to application/libraries/Template.php under $this->set('contents...:

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


You will just have to Add the below code above: [$contentx = $this->CI->load->view($view, $this->template_data, TRUE);]

$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));
Danwiky
Dec 19, 2012
#137
Before i forget.. Thanks for the library. You made CI interesting for me :)
Danwiky
Dec 19, 2012
#138
thanks... this is great..
aho
Jan 2, 2013
#139
gr8...., work
lv
Feb 15, 2013
#140
Hi
how I can load multi view in template?
your variable is $contents and I can use it once in my template.
I want to use it like:
$this->template->load('template', 'login_form');
$this->template->load('template', 'upload_form');
$this->template->load('template', 'items');
Pouria
Feb 21, 2013
#141
Hi, I have tried the form validation, but it really didn't work inside the view page with $this->template->load('template', 'contact'); but work it $this->load->view('contact');
Please Help
Naresh Suwal
Feb 27, 2013
#142
doesn´t work
Marcelo
Mar 29, 2013
#143
Hey Jerome,

I am having trouble with the link concept. Can you please elaborate more. Or better yet, give an example to an already existing nav. Thank you
Brian
Apr 10, 2013
#144
Worked Perfectly with such ease :) been pulling my hair out for ages trying to figure out how to do this and your tutorial was clear and concise... Many thanks
Chris
Apr 15, 2013
#145
Thanks for sharing :)
Thks4S
Apr 18, 2013
#146
Hi, even though i am new to CI and i can say this library is awesome!
Sam
May 9, 2013
#147
But how to setup if the template page is in a folder outside of the application folder. like a folder call template??

I think that is better put all template page separete from the view folder.

But not work here :-/
Ted
May 14, 2013
#148
Thanks for so much helping code
Suraj
Sep 3, 2013
#149
thanks before. but i have an error messg :

Fatal error: Cannot redeclare class Template in C:\xampp\htdocs\project\system\application\libraries\Template.php on line 3

how i can fix it ?
zara
Nov 24, 2013
#150
Are u success? If u success to make a template according to this post. Please give me your link. Then I am able to take an idea about it, because I new to CI.
Kabir
Feb 2, 2014
#151
hi jerome, nice to find your tuts...
i've question , how about to create template
if we have more than one view ex : header.php, body.php, menu.php, footer.php and so on. i don't understand how to figure it w/ your library. thanks for advance jerome :D
fatur
Mar 2, 2014
#152
Simple and elegant. My favorite kind of solution!
ruzel
Mar 27, 2014
#153
nice
clears
May 30, 2014
#154
so cool! thanks
smallerpig
Jul 7, 2014
#155
wow! very nice. thank you so much!
UndressBonifacio
Aug 28, 2014
#156
Great,thanks.

Sep 1, 2014
#157
very helpful for codings. thank you for sharing
code development services
Sep 4, 2014
#158
Fatal error: Call to undefined function lang() in C:\xampp\htdocs\new\themes\default\views\calendar.php on line 63
mallikarjun
Jun 24, 2015
#159
Hi guys,

I've been using successfully this library on CI2.2.0 and now I'm going to CI 3.0.4 and after updating this library version I'm still facing troubles.

A PHP Error was encountered

Severity: Error

Message: Call to undefined method Template::write_view()

Filename: controllers/perfil.php

Line Number: 35

Please, what am'I doing wrong ?

Thanks in advance
Paulo Mendes
Jan 25, 2016
#160
Ok. I found the isso. There is no write_view method anymore.

Jan 25, 2016
#161
In register Page, how to put dropdown in Register.php so that it should be showing over there?
Arry Broad
Feb 14, 2016
#162
simple and easy to use,
this library really helpful to integrate boostrap with ci
thanks


derry
May 12, 2016
#163
Great, thanks.
Ricardo
May 13, 2016
#164
Still helpful 5 years later. Thank you for sharing the library and tut! :)
evkwan
Jun 4, 2016
#165
First off, great work!
Second, now that it worked, how do I pass data from model into the sub view. You know, that contents view that is inside the body content, not the template itself.

Thanks
Nathan
May 2, 2017
#166
Nathan, use the $data array (see the example at the beginning of the page).
Jérôme Jaglale
May 2, 2017
#167