Welcome Guest, Not a member yet? Register   Sign In
My modification to the the load->view() function
#1

[eluser]richthegeek[/eluser]
Hi all,

I made a minor modification to the view() function, which makes it easier to loop through a database result set with a seperate view for each.

Here is how I would do it with the vanilla CI view():
Code:
<?php
foreach( $posts->result() as $post ) {
    $this->load->view('blog_post', $post);
} ?>

Not too stressfull... but with my mod, it can be simplified to this:
Code:
<?php
$this->load->view('blog_post', $post, false, true);
?>
The 3rd parameter is an existing "return" value, which defaults to false. The fourth is the one I added.

Here is my modified load function: (found in System/libraries/Loader.php):
Code:
function view($view, $vars = array(), $return = FALSE, $loop = FALSE)

    {
        if( $loop ) {
            foreach( $vars as $var ) {
                $rt = $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($var), '_ci_return' => $return));
                $return .= $rt;
            }
            return $return;
        } else {

            return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }

    }

Tell me if you find this useful - I sure do...
#2

[eluser]xwero[/eluser]
You only replaced the loop, i don't see the benefit of the replacement. This only slows down the view method.
#3

[eluser]wiredesignz[/eluser]
Also putting the loop inside the View and passing in the $post array, will remove the need to repeatedly call $this->load->view
#4

[eluser]xwero[/eluser]
True wiredesignz but what when you have a several site themes and in those themes the place of the data elements is different. Then you have to use a view loop.
#5

[eluser]webthink[/eluser]
The OP brings up a valid point. Loading a view multiple times in a loop is obviously not going to be as efficient as loading it once and passing an array then looping through that from within the view, but we're talking about adding a degree of modularity to views which is definitely has potential benefit from an organizational perspective.

As for this implementation I agree with xwero, it's not necessary and you don't gain anything by doing it. If anything you lose some performance when loading normal non-looped views which will still be the majority use.




Theme © iAndrew 2016 - Forum software by © MyBB