Template views with Codeigniter Tutorial
Codeigniter is a MVC that allows you to organize views and load any whenever needed. It allows you to slice the view files into parts and load whichever is needed for the time. You can create multiple views and call them according to your needs. We will today divide view files into 4 parts.
- The header: Header is the top part of your webpage where the body tag starts and it contains all Meta tags, titles and other tags for your web page which are not visible to the user but very important.
- The Navigation: Navigation is links to your other pages or contents or files, a navigation system allows the user to easily navigate through your website and browse contents.
- The body: The body part holds all structural information, content, images, videos of your web page it is the actual visual part of your webpage which a user on your webpage will view.
- The footer: Footer is the end part of your web page which may also contain links to style sheets, scripts and contains certain information that remains on every page of your website then it closes the body and html to complete your webpage.
Download the sample file of templated views I have attached with the post below, unzip them and check how the html is broken in chunks, you can also break them in chunks and create your own views.
Loading template view files:
Earlier we broke down html in chunks, now we will dynamically include those chunks in a single view using codeigniter, for that copy all the chunks and paste them inside the views directory and now we are going to load the files and display them in our home controller.
Open the controllers directory, then open up Home.php, inside the index function we will load all parts of the page. For that add the following sample codes inside the index controller to load the template views.
Note: Remove the previously created home.php we no more need that file.
It is important that you load the view templates in a sequence you want to display, so the webpage looks complete rather looking messed up.
Line 1 requests codeigniter to load the view named header (header.php).
Line 2 requests codeigniter to load the view named navigation (navigation.php).
Line 3 requests codeigniter to load the view named home (home.php)
Line 4 requests codeigniter to load the view named footer (footer.php)
Ok so let us move on to browser and load our page. Open your browser and type URL of your home controller then go to that url if you see a structured result then you have successfully created templates. Else check what errors you have made and rectify them.