Welcome Guest, Not a member yet? Register   Sign In
Can't Pass Controller to View
#1

[eluser]Chris CMC[/eluser]
UPDATE: I'm embarrassed. The problem is that I was using $data['title'] instead of just $title in the view. Please keep reading only if you were having the same problem.

I'm a newbie to CI, and after a couple hours going through the User Guide, I still can't pass a variable from the controller to the view.

Here's the controller:
Code:
class Welcome extends Controller {

    function index()
    {    
        $data = array(
                       'title' => 'My Title',
                       'heading' => 'My Heading',
                       'message' => 'My Message'
                  );

        $this->load->view('blogview', $data);
    }
}

Here's blogview:
Code:
Title: <?php echo $data['title']; ?>

And here's the result:
Quote:Title:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/blogview.php

Line Number: 1

I'm a bit embarrassed as I imagine it may be a simple config mistake, but I've been trying for 2 hours now and I can't get it to work.

Also, if I define $data directly in blogview, it works fine ... so it must be an issue of not being able to pass the variable from the controller to the view.

Any thoughts?
#2

[eluser]bretticus[/eluser]
When you call load->view, whatever associative array elements are extracted to variables (see extract function.)

try
Code:
echo $title;
instead.

Welcome to CI and the forums.
#3

[eluser]Chris CMC[/eluser]
thanks so much, works like a charm!
#4

[eluser]bretticus[/eluser]
You can also pass a single scalar variable that will not get extracted (not as useful as multiple variables though.) Smile
#5

[eluser]Chris CMC[/eluser]
i was wondering about that, great to know - thx!




Theme © iAndrew 2016 - Forum software by © MyBB