Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter - how to reuse code to generate a block of HTML

I think I might be approaching this in the wrong way, so I would appreciate any comments/guidance. Hopefully I can explain coherently enough what I am trying to achieve:

  • I want to create a block of HTML (e.g. a box containing a user's profile), which I will load as part of my layout on most pages that I generate.

  • I would also like to be able to re-generate the content within this box on its own from a separate URL. This is so I can update the box with an AJAX call.

  • I don't want to duplicate the code that creates this HTML.

I appreciate that I could initally load this box using an AJAX call, but that would seem to me to add an unnecessary call to the server?

The way I thought I could do it is by having a method in my controller that just renders this block of HTML, but how would I then request the output from this method within another controller / view?

How would you approach this?

Thanks in advance

like image 558
Tom Haigh Avatar asked Nov 28 '08 12:11

Tom Haigh


1 Answers

Create a view to generate the block of HTML for the user's profile and call it from your controller using:

$user_html = $this->load->view('user_view', $user_data, true);

The third parameter returns the view as a string instead of displaying it. This can then be passed into another view in the usual way.

$data['user_block'] = $user_html;
$this->load->view('page_view', $data);
like image 75
foxy Avatar answered Sep 30 '22 07:09

foxy