How to Deal With Codeigniter Templates?

2019-01-16 14:34发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

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


回答4:

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



回答5:

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.



回答6:

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?



回答7:

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)


回答8:

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.



回答9:

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.



回答10:

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



回答11:

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.



回答12:

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