How do I place the content in the correct place in the codeignor?

advertisements

I have this code, and when I call the function with mydomain/index.php/blog everything works, but the content i.e "index" in this case is being displayed in the top of the page. I want it to be displayed in the content area, that i have defined in my css. Whats the problem?

<?php
    class Blog extends CI_Controller{

        public function __construct(){
            parent::__construct();
        }

        public function index(){

            $this->load->view('template/header');
            echo "index";
            $this->load->view('template/footer');
        }

    }
    ?>


There are two ways to display output to the browser in CodeIgniter. Using the CI views and just echoing out the data. The echo command executes immediately, so that's why it is at the top of the page. The load->view method is executed within CI in the output library - so it's not executed exactly in order of your echo statement.

I would say to create another view for your content, then call all views like this:

$data = array('content_html' => 'index');
$this->load->view('template/header');
$this->load->view('template/content', $data);
$this->load->view('template/footer');

Your content view could just echo out the content_html variable:

// views/template/content.php
echo $content_html;

Alternatively, you can control the content in your controller (although, not the best of ideas):

$header = $this->load->view('template/header', array(), TRUE);
$footer = $this->load->view('template/footer', array(), TRUE);

echo $header;
echo "index";
echo $footer;

Passing TRUE as the third parameter to the load->view method returns the view as a string instead of outputting it to the browser - allowing you to control the output.