Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter or PHP Equivalent of Rails Partials and Templates

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 could have a common navbar.php view that I could point to the inside my homepage.php view. Templates would define the overall shell of an HTML page in one place, and let each view just fill in the body.

The closest thing I could find in the CodeIgniter documentation was Loading multiple views, where several views are rendered sequentially in the controller. It seems strange to be dictating the visual look of my page inside the controller. (i.e. to move the navbar my designer would have to edit the controller).

I've been searching on stackoverflow for a PHP way to accomplish this. I have found this page, which talks about simulating partials with ob_start. Is that the recommended approach inside CodeIgniter?

like image 555
Wayne Kao Avatar asked Apr 19 '09 18:04

Wayne Kao


3 Answers

I may be breaking some MVC rule, but I've always just placed my "fragments" in individual views and load them, CodeIgniter style, from within the other views that need them. Pretty much all of my views load a header and footer view at the top and bottom, respectively:

<? $this->load->view( "header" ); ?>
//Page content...
<? $this->load->view( "footer" ); ?>

The header could then include a NavBar in the same fashion, etc.

like image 160
Brent Avatar answered Nov 17 '22 19:11

Brent


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

like image 26
mike wyatt Avatar answered Nov 17 '22 19:11

mike wyatt


In PHP you'd use include

like image 3
troelskn Avatar answered Nov 17 '22 20:11

troelskn