Passing common title to all view and models CodeIgniter

你。 提交于 2019-12-02 08:18:34

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.

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);
    }

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);
    }
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!