27

I'm fairly new to MVC, and I've found CodeIgniter recently. I'm still learning everyday, but one problem is its template engine. What is the best way to create templates in CodeIgniter?

CakePHP comes with its own template library, is there a similar feature in CodeIgniter?

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74
Martin
  • 271
  • 1
  • 3
  • 3
  • 1
    Hello @Martin, I see this is a pretty old post and you've still didn't mark any answer as correct. Did you find a solution to your problem? – John Skoumbourdis Oct 25 '16 at 05:44

12 Answers12

25

Unlike other frameworks CodeIgniter does not have a global template system. Each Controller controls it's own output independent of the system and views are FIFO unless otherwise specified.

For instance if we have a global header:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" >
<html>
    <head>
        <title><?=$title?></title>
        <!-- Javascript -->
        <?=$javascript ?>
        <!-- Stylesheets -->
        <?=$css ?>
    </head>
    <body>
        <div id="header">
            <!-- Logos, menus, etc... -->
        </div>
        <div id="content">

and a global footer:

        </div>
        <div id="footer">
            <!-- Copyright, sitemap, links, etc... -->
        </div>
    </body>
</html>

then our controller would have to look like

<?php
class Welcome extends Controller {

    function index() {
        $data['title'] = 'My title';
        // Javascript, CSS, etc...

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

        $data = array();
        // Content view data
        $this->load->view('my_content_view', $data);

        $data = array();
        // Copyright, sitemap, links, etc...
        $this->load->view('footer', $data);
    }
}

There are other combinations, but better solutions exist through user libraries like:

See Comments Below

Ryan Schumacher
  • 1,816
  • 2
  • 21
  • 33
  • I got here from google, the above links don't work anymore and redirect to the github repo for CodeIgniter, but you can go to the wiki pages on there and search for 'template' to find a dozen or so different implementations for this problem. – sg3s Oct 08 '12 at 09:01
  • There are also a number of great Template libraries which I have used that are not part of CodeIgniter, but can be easily integrated, Mustache(https://github.com/bobthecow/mustache.php) and Twig(http://twig.sensiolabs.org/) – Ryan Schumacher Oct 08 '12 at 14:10
  • Because when the question was given and answered 6 years ago it was relevant. – Ryan Schumacher Jul 10 '15 at 11:32
14

I've tried several ways to do codeigniter templates and the way that I stay is the fastest and simplest, is as follows.

In controller:

    //Charge the view inside array
    $data['body'] = $this->load->view('pages/contact', '', true);


    //charge the view "contact" in the other view template
    $this->load->view('template', $data);

In view template.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es"> 
<head> 
    <title>Template codeigniter</title> 
</head> 
<body> 
    <div> 
        <?=$body?>
    </div> 
    <div class="clear"></div> 
    <div>Footer</div> 
    </div> 
</body> 
</html> 

$body is the view contact.

zkanoca
  • 9,664
  • 9
  • 50
  • 94
jruzafa
  • 4,156
  • 1
  • 24
  • 26
  • When I use this method, I get lots of undefined variables--they don't seem to be getting passed from the controller to the $body variable. – russellmania Mar 27 '14 at 04:06
13

Make a library that includes all your views and send it data that you need to send to your content view. This is all!

<?php
class Display_lib
{

    public function user_page($data,$name)
    {
        $CI =& get_instance ();

        $CI->load->view('preheader_view',$data);
        $CI->load->view('header_view');
        $CI->load->view('top_navigation_view');
        $CI->load->view($name.'_view',$data);
        $CI->load->view('leftblock_view',$data);
        $CI->load->view('rightblock_view',$data);
        $CI->load->view('footer_view');        
    }
}
zkanoca
  • 9,664
  • 9
  • 50
  • 94
SpartakusMd
  • 131
  • 1
  • 2
5

This library, easy to use and customize, does exactly what you'd expect:

  • avoid HTML duplication (header, footer..)
  • no need to learn a new language (!)

Most Simple Template Library for CodeIgniter

Jerome Jaglale
  • 1,863
  • 18
  • 22
  • 2
    The thing I like most about this is that rather than switch over to a different syntax for something like Smarty, it preserves what I like most about CI basic templates: PHP short tags. – russellmania Mar 27 '14 at 04:57
4

I use CodeIgniter with Smarty and it's great (if you like Smarty, I do).

Say you have an article controller, you could do somehting like this in it:

class Article extends Controller {
  function show_all() {
    $articles = $this->article_model->get_all();
    $this->smarty->assign('entities', $articles);
    $this->smarty->view('list');
  }
}

And then in your template:

{include file="header.tpl"}
  <ul>
  {foreach from=$entities item=entity}
  <li>{$entity.title}</li>
  {/foreach}
  </ul>
{include file="footer.tpl"}

The nice part about this is that the controller doesn't really need to know about headers and footers. It just knows that a group of articles should be shown as a list. From there, it's just the templates that are responsible for defining how a list of things are displayed, in this case, in a ul between a header and footer.

Another cool thing you can do is use this list template for things that aren't articles. You could have a list of users or pages or whatever. In some cases reusing a template like this can be useful. Not always, but sometimes.

Setting up CodeIgniter for smarty is pretty straightforward. It's a matter of copying the Smarty files to your library folder and creating a simple wrapper for it. You can find instructions here:

http://devcha.blogspot.com/2007/12/smarty-as-template-engine-in-code.html

Once you get is set up it's great.

GloryFish
  • 13,078
  • 16
  • 53
  • 43
2

Well you can actually use a codeigniter library for templates. The most famous ones are:

  1. Codeigniter Simplicity (Actively Developed)
  2. Phil Sturgeon's Template Library (Not actively developed)
  3. An Introduction to Views & Templating in CodeIgniter (Here you actually create a template library from scratch)
John Skoumbourdis
  • 3,041
  • 28
  • 34
2

I have two primary templates; one for the site and one for our admin panel. Here is my setup for our main site (mostly static)... I decided on one controller called site It calls the template file and each page and gets its view file.

Why doesn't anyone mention template engine use? Are -just- views better/faster?

  • In config/template.php I defined the template(s). Note *site_template* is in the views folder:

    $template['site']['template'] = 'site_template';
    $template['site']['regions'] = array('title','section','col2','content',);
    $template['site']['parser'] = 'parser';
    $template['site']['parser_method'] = 'parse';
    $template['site']['parse_template'] = FALSE;
    
  • In config/routers.php I setup rules to handle the requests for the site controller which are single segments urls mostly but we do have one section that is structured as such; /who-we-are and then for selected people /who-we-are/robert-wayne and so:

    $route['what-we-do'] = 'site/what_we_do';
    $route['who-we-are'] = 'site/who_we_are';
    $route['who-we-are/(:any)'] = "site/who_we_are/$1"
    
  • And controllers/site.php Again with a function for each page/section:

    class Site extends CI_Controller
    {
    function __construct() {
        parent::__construct();
        $this->template->set_template('site'); // ask for the site template
        $this->load->library('mobile');
    }
    public function index()
    {
    $data = array('section' => 'home');
    $this->template->write_view('col2', 'site/menu.php', $data);
    $this->template->write('title', "COOL PAGE TITLE", TRUE);
    $this->template->write('section', $data['section'], TRUE);
    $this->template->write_view('content', 'site/welcome', $data);
    $this->template->render();
    }
    public function who_we_are()
    {
    // this bit readies the second segment.
    $slug = str_replace('-', '_', $this->uri->segment(2, 0));
    if($slug) // IF there is a second segment we load the person.
    {
    $data['bio'] = $this->load->view('site/people/'.$slug, '', true)
    } else {
    // where it loads the general view who_we_are
    }
    // and so on for each page...
    

and as fine point notice the router lets us leave out `/site/' in the url, http://the site.com/who-we-are

thoughts? anyone? bueller?

Robert
  • 204
  • 1
  • 10
1

I'm biased towards this template library made by Carmelo Capinpin because it is so easy to use: link text. Just copy the file in your library and you're ready to go. Instructions on how to use it is in the link I provided.

Randell
  • 6,112
  • 6
  • 45
  • 70
1

There is a library which allows you to use templates in CodeIgniter in a native style. To load a template/theme just do:

$this->load->theme(‘theme_name’);

To load CSS and javascript files from your views you can do:

$this->load->css(‘path/file.css’);
$this->load->js(‘path/file.js’);

You can optionally control the way browsers cache CSS & JS files.

richq
  • 55,548
  • 20
  • 150
  • 144
VangelisB
  • 438
  • 5
  • 10
0

A Codeigniter template is generally just a PHP file. You can use all the usual PHP syntax to output variables, do loops, and call other PHP code.

Sample controller:

<?php
class Blog extends Controller {

    function index()
    {
        $data['title'] = "My Real Title";
        $data['heading'] = "My Real Heading";

        $this->load->view('blogview', $data);
    }
}
?>

Sample view:

<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
    <h1><?php echo $heading;?></h1>
</body>
</html>

Read more in the docs here: CodeIgniter User Guide: Views

pix0r
  • 31,139
  • 18
  • 86
  • 102
  • Well, yes. But i would to know if there's anyway to speed up this process and make it more organized - so i won't have to type in
    , , style etc... I want to have it in just one folder or library. Think of it as wordpress, you could change template without editing every single view.
    – Martin Jun 23 '09 at 00:10
0

Allow me propose an easier way to do this. Consider my answer to a similar question.

Pros:

  1. Your template file can be a full HTML file. You don't have to break up the header and the footer.
  2. Any view file can be turned into a template with minimal effort.
  3. Data for the specific view can be generated in the template.

Cons: 1. You may have to add a template (or layout—if you want to do it the Rails way) directory under views in order to structure your code properly. This follows from Pros[2]. 2. Data for the specific view from the controller must first of all be passed to the template.

Community
  • 1
  • 1
Igbanam
  • 5,904
  • 5
  • 44
  • 68
0

Well codeignier does not have such library by default. But if you want different themes, views, and assets to be managed try using this:

https://github.com/mahadazad/php-layout-manager