Passing chunk of code to every controller |
09-12-2015, 02:28 AM
(This post was last modified: 09-12-2015, 08:14 AM by Keky. Edit Reason: clarification )
Hi,
I want to display some data on every page (like latest news, latest comments etc). So I created the Latest_model.php and autoload it. For example this is the simple function for getting the latest news. Code: public function get_latest_news() I put this in my template view (sidebar.php) Code: <?php foreach ($latest_news as $latest_news_item): ?> Now, let's look at some controller, for example History.php (which main function is to show history stuff in content template). Code: public function index() I want this only in history.php. So, now finally for my main problem. If I want to display latest news, comments etc... in the sidebar on every page, I have to put these lines in EVERY controller Code: $data['latest_news'] = $this->latest_model->get_latest_news(); How can I pass the code for displaying latest things without the need to writing it to every controller?
You can extend CI_Controller with your own MY_Controller. See http://www.codeigniter.com/userguide3/ge...core-class
Then set your data in the constructor : PHP Code: class MY_Controller extends CI_Controller
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
09-13-2015, 01:33 AM
(This post was last modified: 09-13-2015, 02:00 AM by Keky. Edit Reason: typo )
Thank you for your response.
Unfortunately, I can't get it to work. I get this error: Message: Undefined variable: latest_news Sorry, my bad, it is working perfectly! I was just executing it incorrectly. Thanks again! |
Welcome Guest, Not a member yet? Register Sign In |