Passing common title to all view and models CodeIgniter

三世轮回 提交于 2019-12-04 06:27:24

问题


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?


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/17110968/passing-common-title-to-all-view-and-models-codeigniter

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