CodeIgniter or PHP Equivalent of Rails Partials and Templates

后端 未结 11 1739
猫巷女王i
猫巷女王i 2020-12-30 14:13

In CodeIgniter, or core PHP; is there an equivalent of Rails\'s view partials and templates?

A partial would let me render another view fragment inside my view. I co

相关标签:
11条回答
  • 2020-12-30 15:02

    this is essentially what I use:

    function render_partial($file, $data = false, $locals = array()) {
        $contents = '';
    
        foreach($locals AS $key => $value) {
            ${$key} = $value;
        }
    
        ${$name . '_counter'} = 0;
        foreach($data AS $object) {
            ${$name} = $object;
    
            ob_start();
            include $file;
            $contents .= ob_get_contents();
            ob_end_clean();
    
            ${$name . '_counter'}++;
        }
    
        return $contents;
    }
    

    this allows you to call something like:

    render_partial('/path/to/person.phtml', array('dennis', 'dee', 'mac', 'charlie'), array('say_hello' => true));
    

    and in /path/to/person.phtml have:

    <?= if($say_hello) { "Hello, " } ?><?= $person ?> (<?= $person_counter ?>)
    

    this is some magic going on though that may help you get a better picture of what's going on. full file: view.class.php

    0 讨论(0)
  • 2020-12-30 15:03

    Here is a blog post describing how to use smarty with codeigniter. The asp.net like masterpage is also implemented.

    0 讨论(0)
  • 2020-12-30 15:05

    CodeIgniter and Smarty play nicely together.

    0 讨论(0)
  • 2020-12-30 15:11

    I found myself moving from Rails to CI too, and what I did with partials is basically render the partials in the view as a variable and set it from the controller.

    So in the view you would have something like (_partial.php):

    <h2>Here Comes The Partials</h2>
    <?= $some_partials ?>
    

    And you can set it from the controller like:

    $this->load->view('the_view', 
       array('some_partials', 
             $this->load->view('_partial', array(), TRUE)
       )
    );
    

    Personally, I prefer to use CI's view instead of ob_start, but that's me =) PS: When loading views, first argument is the view name, second one is the parameters to be passed to the view, and the third one is "ECHO" flag, which basically tells CI whether to render it directly or return the value of the view instead, which is basically what I did in the example.

    I don't think it's a good solution though, but it works for me. Anyone has better solutions?

    0 讨论(0)
  • 2020-12-30 15:12

    You can check it, for partials and template

        http://code.google.com/p/ocular/wiki/Introduction
    
    0 讨论(0)
提交回复
热议问题