How to Deal With Codeigniter Templates?

前端 未结 12 1863
梦谈多话
梦谈多话 2020-12-08 01:02

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

12条回答
  •  离开以前
    2020-12-08 01:54

    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"}
      
      {foreach from=$entities item=entity}
    • {$entity.title}
    • {/foreach}
    {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.

提交回复
热议问题