Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Passing common title to all view and models CodeIgniter

I have this controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

     function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('text');

    }

    public function index()
    {
        $this->home();
    }

    public function home()
    {
            $data['title']="Somesite";
        $this->load->view("view_home", $data);

    }

        public function blog()
    {
            $data['title']="Somesite";
        $this->load->view("view_blog", $data);

    }
        public function answers()
    {
            $data['title']="Somesite";
        $this->load->view("view_answers", $data);

    }
    }

As you may see $data['title'] is same for all functions, how to make it simpler, to include at the beggining and not to write it in every function, repeat again, and then transfer to view. Is there a way to tranfer it to function?

Upvotes: 0

Views: 1513

Answers (3)

Sumith Harshan
Sumith Harshan

Reputation: 6445

I'm using this method in every projects.

Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

 //Global variable
 public $outputData = array();  
 public $loggedInUser;


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

 public function index()    {
    $this->load->helper('url');

    $this->load->view('users/users');
 }


 public function register() {

     parent::__construct();

     $this->load->helper('url');
     $this->load->model('users_model');

     //get country names
     $countryList = $this->users_model->getCountries();
     $this->outputData['countryList'] = $countryList;   


     $this->outputData['pageTitle'] = "User Registration";


    $this->load->view('users/register',$this->outputData);
 } 

}

View file

<?php if(isset($pageTitle)) echo $pageTitle; ?>

<?php
    if(isset($countryList)){
       print_r($countryList);
    }
?>

Upvotes: 0

Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Here si simple solution and elegant for transfering one variable to all views :)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    //Class-wide variable to store stats line
    protected $title;

    function __construct()
    {
        parent::__construct();
        $data->title = "Some site";
        $this->load->vars($data);
    }

Upvotes: 2

Sasha
Sasha

Reputation: 8705

Before construct function add this:

public $data = array();

Then in the construct function write:

$this->data['title']="Somesite";

And finally before load view add this:

$data = $this->data + $data;

Now you have same $title everywhere.

Upvotes: 3

Related Questions