In CodeIgniter, or core PHP; is there an equivalent of Rails's view partials and templates?
A partial would let me render another view fragment inside my view. I could have a common navbar.php
view that I could point to the inside my homepage.php
view. Templates would define the overall shell of an HTML page in one place, and let each view just fill in the body.
The closest thing I could find in the CodeIgniter documentation was Loading multiple views, where several views are rendered sequentially in the controller. It seems strange to be dictating the visual look of my page inside the controller. (i.e. to move the navbar my designer would have to edit the controller).
I've been searching on stackoverflow for a PHP way to accomplish this. I have found this page, which talks about simulating partials with ob_start. Is that the recommended approach inside CodeIgniter?
Symfony does this with their partial/component setup.
this is essentially what I use:
this allows you to call something like:
and in /path/to/person.phtml have:
this is some magic going on though that may help you get a better picture of what's going on. full file: view.class.php
CodeIgniter and Smarty play nicely together.
Here is a blog post describing how to use smarty with codeigniter. The asp.net like masterpage is also implemented.
I found myself moving from Rails to CI too, and what I did with partials is basically render the partials in the view as a variable and set it from the controller.
So in the view you would have something like (_partial.php):
And you can set it from the controller like:
Personally, I prefer to use CI's view instead of ob_start, but that's me =) PS: When loading views, first argument is the view name, second one is the parameters to be passed to the view, and the third one is "ECHO" flag, which basically tells CI whether to render it directly or return the value of the view instead, which is basically what I did in the example.
I don't think it's a good solution though, but it works for me. Anyone has better solutions?
I may be breaking some MVC rule, but I've always just placed my "fragments" in individual views and load them, CodeIgniter style, from within the other views that need them. Pretty much all of my views load a header and footer view at the top and bottom, respectively:
The header could then include a NavBar in the same fashion, etc.