Welcome Guest, Not a member yet? Register   Sign In
pass variable to template file
#1

[eluser]mazdaFan[/eluser]
Hi! I'm new in CI and need some help.

I have function that return site menu and the result of the function is passed to template file, but i don't want to have this in each function:

Code:
$this->load->model('Products');
$data['menu'] = $this->Products->showMenu();
//$data['body'] = 'bla bla';
$this->load->view('welcome_message', $data);


is there a way to globally set $data['menu']...

Sorry for bad english ;(
#2

[eluser]Dam1an[/eluser]
Hi, take a look at extending core classes
You'll want to create a MY_Controller which you other controllers then extend, and in there, you have the above login in the constructor.
But you'll need to make the data array a variable of the MY_Controller class, so use $this->data in MY_Controller and your other controllers
#3

[eluser]mazdaFan[/eluser]
something like this?
Code:
<?php
class MY_Controller extends Controller {
    var $data = array();
    
    function MY_Controller()
    {
        parent::Controller();
        $this->data['menu'] = 'menu1, menu2...';
    }
    
}
and
Code:
$this->load->model(‘Products’);
//$data[‘menu’] = $this->Products->showMenu();
$this->data[‘body’] = ‘bla bla’;
$this->load->view(‘welcome_message’, $this->data);
but get error:
<p>Message: Undefined variable: menu</p>
<p>Filename: views/welcome_message.php</p>
#4

[eluser]Dam1an[/eluser]
Thats the general idea
2 things come to mind that might be causing the problem
1) Did you change the [insert name of controller here] to extend MY_Controller instead of Controller (and you put MY_Controller in application/libraries)
2) Do you have nested views? If so, you'll probably want to use
Code:
$this->load->vars($this->data);
instead of passing it as the second parameter
#5

[eluser]mazdaFan[/eluser]
Thanks you!

Working code:
Code:
&lt;?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends Controller {
    var $data = array();
    
    function MY_Controller()
    {
        parent::Controller();
        $this->data['menu'] = 'menu1, menu2...';
    }
}
and...
Code:
class Welcome extends MY_Controller {

    var $data = array();
    
    function Welcome()
    {
        parent::MY_Controller();
    }
    
    function index()
    {
        $this->data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');    
        $this->load->view('welcome_message', $data);
    }




Theme © iAndrew 2016 - Forum software by © MyBB