Don P
Don P

Reputation: 63567

CodeIgniter passing data into views

I need my data to get passed all the way from my controller -> page (view) -> users (view). How can I pass the data from my controller to the most nested view?

  1. In my controller, I get some data called $users.
  2. In my controller, I load a view called "page".
  3. In my view called "page", I load views called "users".

Here is an example of how I think I can do it. Is this smart or incorrect?

In my controller I can do:

$data['users'] = $array_of_user_objects;
$this->load->view('page', $data); 

Then in my page (view) I can do:

<div>
  <h1>Im a page!</h1>
  <?php $this->load->view('users', $users); ?>    
</div>

Then in my users (view) I can do:

<h1>Hi my name is: <?php echo $name; ?></h1>

Upvotes: 0

Views: 455

Answers (3)

Fu Xu
Fu Xu

Reputation: 766

you do not need use <?php $this->load->view('users', $users); ?>

but <?php $this->load->view('users'); ?>

and you need a loop in your users view like this

<?php foreach($users as $user): ?>
Hi my name is: <?php echo $user->name; ?>
<?php endforeach;?>

Upvotes: 0

ABorty
ABorty

Reputation: 2522

if you are doing things in controller like

$data['users'] = $array_of_user_objects;
$this->load->view('page', $data);

then in page(view) you can do simply

<div>
    <h1>Im a page!</h1>
    <?php echo $users->name ?> //if its an object otherwise $users['name']   
</div>

and in your users(view)

<h1>Hi my name is: <?php echo $users->name; ?></h1> //if its an object otherwise $users['name']

please let me know if you face any problem.

Upvotes: 2

M7R
M7R

Reputation: 1

in controller

$users = $array_of_user_objects;
$data['users'] = $this->load->view('users', $users, true);
$this->load->view('page', $data); 

in 'page' view

<div>
<h1>Im a page!</h1>
  <?=$users ?>    
</div>

Upvotes: 0

Related Questions