Welcome Guest, Not a member yet? Register   Sign In
Getting the HTML output of a view
#1

[eluser]merik[/eluser]
Is there a way that I can pass some parameters to a view, get the output HTML and store it in a variable, and then send it as a parameter to another view?

I need this because I have a "header" view, and a part of it changes based on weather the user is logged in or not (link to profile vs. login form) and I want to keep the logic outside the header view. So I am thinking I can have three views (header, link_to_profile, and login_form) and call one of the last two based on login status and pass its HTML to the header view.
#2

[eluser]TheFuzzy0ne[/eluser]
Yes. Just use $this->load->view() and set the 3rd parameter to TRUE;

That will return the contents of the view for you to insert into another one.

Alternatively, I use this:

./application/libraries/MY_Loader.php
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Loader extends CI_Loader
{

    /**
     * Extends CodeIgniters loader class to allow us to easily load a view from
     * within a view.
     *
     * By using $this->load->vars(), prefix the key with 'view:' and use the
     * path of the view as the value to load a view in-line.
     *
     * @access public
     * @param array $vars An array of key/value pairs, or just a key.
     * @param string $val The value for the key if not using an array.
     * @return void
     */
    function vars($vars = array(), $val = '')
    {
        if ($val != '' && is_string($vars))
        {
            $vars = array($vars => $val);
        }

        $vars = $this->_ci_object_to_array($vars);

        if (is_array($vars) && count($vars) > 0)
        {
            foreach ($vars as $key => $val)
            {
                if(strncmp('view:', $key, 5) == 0)
                {
                    $this->_ci_cached_vars[substr($key,5)] = $this->view($val,'',TRUE);
                }
                else
                {
                    $this->_ci_cached_vars[$key] = $val;
                }
            }
        }
    }
}

// END Loader class

/* End of file MY_Loader.php */
/* Location: ./application/core/MY_Loader.php */

So I can do this:
Code:
$this->load->view('main_template', array(
    'title' => 'My Page',
    'another_var' => TRUE,
    'view:content' => 'my_content_view',
));

My main_template view simply echos the value of the $content variable.

You just need to make sure that you put the content view at the bottom of the array, and any variable that appears before it will be available to it.

However, I would recommend you rethink about not putting logic in your views. It's a noble sentiment, but simple logic within views is perfectly acceptable, and can save you duplicating code.




Theme © iAndrew 2016 - Forum software by © MyBB