Partial Views in CodeIgniter - php

I am a beginner in using CodeIgniter Framework. Previously, I have learned Laravel. and my problem is I want to make dynamic template like Blade in Laravel. So, in every pages I just load the style and script that only needed by that page.
Here is the code, that I created with CodeIgniter so It could be dynamic to load custom style and custom script.
template.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// <hmtl>
$this->load->view($header);
if(isset($style))
$this->load->view($style);
// <body>
$this->load->view($navbar);
if(isset($sidebar))
$this->load->view($sidebar);
$this->load->view($content);
$this->load->view($footer);
// </body>
if(isset($script))
$this->load->view($script);
// </html>
and my controller
public function index()
{
$data = [
'title' => 'Home',
'header' => 'partials/_header',
'navbar' => 'partials/_navbar',
'content' => 'guest/public',
'footer' => 'partials/_footer'
];
$this->load->view('template', $data);
}
maybe you have better thought, because I am stuck with it. in Laravel it's easy because there is #yield and #section. any ideas from you guys, would be so helpful to me, thank you.

finally, I just figured it out the best way make it dynamic. how to load custom script and css in every different pages.
here is the code for template.php (inside views folder)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$this->load->view($header);
$this->load->view($navbar);
$this->load->view($content);
$this->load->view($footer);
and the controller controller
public function index() {
$data = [
'header' => 'partials/_header',
'style' => 'partials/style/_public_css',
'navbar' => 'partials/_navbar',
'content' => 'guest/public',
'footer' => 'partials/_footer',
'script' => 'partials/script/_public_js'
];
$this->load->view('template', $data);
}
and in the partials view of _header.php
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>...</title>
<!-- Partial CSS Here -->
<?php if(isset($style)) $this->load->view($style); ?>
</head>
<body>
_navbar.php
<header>
<nav class="navbar navbar-inverse navbar-fixed-top">
....
</nav>
</header>
then the content variable in controller, it loads public.php (in my case, you have to replace with any pages you want to load)
<div class="container">
....
</div>
and the last one is _footer.php
<footer>
....
</footer>
<!-- JQuery HERE -->
<!-- any js that you will you in all pages HERE -->
<!-- Partial Script Here -->
<?php if(isset($script)) $this->load->view($script); ?>
</body>
<html>
Remember, if your footer does static in every pages place your JQuery in _footer.php and if it doesn't just place the jquery in the _header.php even it's not the best practice to load the script first.

I did something similar once, sometime ago admittedly now, but I did it all in a template library.
Using setters like
$this->template_library->set_css_script('page.css');
$this->template_library->set_layout('product_page');
The controller would end with a call like:
$this->template_library->render_page();
The template library would then use the load->view functions to create the page and output it depending on the values that were set or not set, and the page layout meant I could have various set layouts like home_page, product_page, checkout_page, message_page etc etc.
For the layouts, I had one master layout that did the main page, and variations for the different pages.
In the end though I reverted to simple views, with common files for header and footer and any variants. It was just easier to maintain lots of different view files than it was to maintain all the layouts and templates and partials.
One thing that helps a lot is that a view can load another view. So for the sake of keeping everything DRY, this means that any derivative page part views can be kept in a 'partials' folder for things like 'related products' or 'blog_list' etc.
Hope that helps.

Related

Is it possible to link to a header.php and footer.php from different folder sources?

I'm a beginner at PHP.
I have multiple webpages residing in different locations. So when I wish to link to header.php and footer.php from the webpages in different folders, is it possible to do so? As shown in the picture, I have to create three different folders, containing same files, header.php and footer.php, to be able to link from three different sources.
With Best regards!
Yes it is possible to use a single footer.php and single header.php files and load them anytime you need.
What I would suggest you can do is that you create an include folder, then inside the include folder create another folder called common where by you will place website that elements that are always the same throughout the website ie, footer and header.
then I would also place a functions file inside the includes where I will place my website functions. Included in this function file is a function that I will use anytime I want to use the header.php and footer.php files.
Functions.php
<?php
function loadView($viename,$meta=[]){
//load footer/header page
include_once "common/$viename.php";
}
//any other functions
The loadView() function is used anytime you want to load these two dynamic files. This functions takes two parameters 1 optional. The first parameter is the name of the view you want to load which is header or footer then the second optional is the meta information important for the header file, as the page title and meta description needs to be dynamic and change according to the page.
header.php
<!DOCTYPE html>
<html>
<head>
<title><?=$meta['pagetitle']?><!-- Dynamic page title --></title>
<meta name="description" content="<?=$meta['pagedescription']?>"><!-- Dynamic description -->
<!-- load your styles -->
</head>
<body>
<header>
<nav>
<!-- Your page navigation -->
<ul>
<li>Home</li>
<li>About</li>
<li>Another Page
</ul>
</nav>
</header>
footer.php
<footer>
footer content
<p>© website name <?=date('Y')?>
</footer>
</body>
</html>
Main website pages
Your main website pages are pages such as index, about,services etc.
In these pages you would load the functions file, then be able to load the header and footer.
index.php
<?php
include 'includes/functions.php';
//meta info
$meta = array(
'pagetitle' => 'Welcome to my site | site | bla bla',
'pagedescription' => 'This is your website description'
);
loadview('header',$meta); //load heade
?>
<section>
<div id="content">
<p>Page Content</p>
</div>
</section>
<?php
loadview("footer"); //load footer
?>
About Page
<?php
include 'includes/functions.php';
$meta = array(
'pagetitle' => 'About Us',
'pagedescription' => 'This is about page'
);
loadview('header',$meta);
?>
<section>
<div id="content">
<p>Page Content</p>
</div>
</section>
<!-- load footer -->
<?php
loadview("footer");
?>
Hope this gives you the idea on how you could achieve your goal, there are many ways you can achieve this.
Let me know when you need any help
Assign values for $h_path and $f_path dynamically.
<?php
$h_path = '';
$f_path = '';
include($h_path.'header.php');
include($f_path.'footer.php');
?>
My apologies for not providing enough information about the issues. My issue is that, when the index.php refers to the header and footer by "includes/header.php" and "includes/footer.php" respectively, and other webpages are located inside another folder which needs to access the includes folder via "../includes/header.php". There is no problem while referring to the files but the issue occurs when headers.php targets the webpages inside when it is written to only work with index.php. For example, would only work on index.php but not on the php files inside the folder which needs , But I'll try with $h_path = ''; and $f_path = '' soon.

What is the best practice to include header and footer in PHP?

everytime I create a website I usually end up by creating a simple index.php file that will load the requested pages.
Example:
include ('header.php');
if(isset($_GET['page']))
{
$page = $_GET['page'];
$display = $page.'.php';
}
else
{
include ('homepage.php');
}
include ('footer.php'); ?>
THE PROBLEM:
If I want to create a connection.php file that will access my database usally it won't work in other pages beacuse I have to rewrite "include('connection.php')", in every single file that isn't the index.php.
THE REQUEST:
How can I embed header, footer, connection, etc... In a proper and safe way ? So I don't have to include it in every other file ?
How do you usually include the header and the footer in every page, in order to create a dynamic website ?
There's multiple ways to fix this.
Use a templating engine, like Blade or Twig.
Create an autoloader
Blade will allow you to make a layout, which can look like this:
<html>
<head>
<title>App Name - #yield('title')</title>
#yield('css')
</head>
<body>
<!-- Include all your files -->
#php
include('myfile.php');
#endphp
<div class="container">
#yield('content')
</div>
#yield('js')
</body>
</html>
Then for every other page you can create a blade file that extends the layout.
#extends('layout.file')
#section('title', 'Page Title')
#section('content')
<p>This content will be placed in the container in the layout.</p>
#endsection
You can write an auto-loader by yourself or use a pre-written one. I'm not going to attempt writing one because I usually go with the pre-written ones.
This should give you an idea though.

Laravel - How to load content with new URL

I have inherited a Laravel project to which I need to add a new page with some functionality that I have created. What I've got appears to be a main "app.blade.php" file, which includes some stuff that will always be visible.. like sidebar, login auth stuff and so on.
Now adding stuff to this is no problem. But what I want is a separate .php file that is loaded in the main content area of the app.blade.php when I go to a certain URL, let's call it "mypage.com/newpage". (Essentially, I want a link in the sidebar to load this new content.)
So my custom content should appear in the main content area, but the standard sidebar, etc, should still be there. I'm guessing it's something with routes, but... How do I proceed? Which files do I edit? What do I add and where? I already got my new HTML and Javascript code ready - I simply need to add it into the Laravel project the right way.
Suppose , bellow code is your app.blade.php file which you want to inherit.
<html>
<head>
<title>App Name - #yield('title')</title>
</head>
<body>
#section('sidebar')
This is the master sidebar.
#show
<div class="container">
#yield('content')
</div>
</body>
</html>
and you want to load the app.blade.php file here. You need to extends the page and declare the sections like this.
#extends('app')
#section('title', 'Page Title')
#section('sidebar')
#parent
<p>This is appended to the master sidebar.</p>
#endsection
#section('content')
<p>This is my body content.</p>
#endsection
Extending a layout on laravel This may help you.
What you're looking for is template inheritance. You create a layout template that you use as the main layout and your pages inherit that main layout template. See the Laravel Blade documentation: https://laravel.com/docs/5.2/blade#template-inheritance

Codeigniter + Smarty integration, header/footer templating

I've implemented smarty on my CI installation via this tutorial: http://www.coolphptools.com/codeigniter-smarty
It works fine, except that the header and footer is loaded by including the files from within the template.
ie.
{include file="header.tpl" title="Example Smarty Page" name="$Name"}
...
{include file="footer.tpl"}
Is there a way to load them from the controller or from the Smarty library class?
To give a clearer example of what I want; Without a templating engine I would just extend the view method via a custom loader.
eg.
class MY_Loader extends CI_Loader {
function view( $template, $data = array(), $return = false ) {
$content = parent::view( 'header', $data, $return );
$content .= parent::view( $template, $data, $return );
$content .= parent::view( 'footer', $data, $return );
if( $content )
return $content;
}
}
This has always worked for me, but now I'm trying out smarty and I could not for the life of me figure out how to make it work like this one.
If anyone could point me to the right direction. That'd be great.
PS. Apologies if this has already been answered before, I've been Googling this for the past 2 hours and I can't seem to find anything. My PHP skills are intermediate at best.
I'm no expert but I did have to go through this not too long ago.
What I did is something like this:
header.tpl
<html>
<head>
</head>
<body>
content.tpl
{include file="header.tpl"}
{include file="$content"}
{include file="footer.tpl"}
footer.tpl
</body>
</html>
Then you could just have smarty call content.tpl always and pass the actual body content through $content.
Like I said, though, I'm not expert so the syntax might be off and there might be a more "correct" way of doing this, but I think the idea is there.
Hope that helps.
You should use the {extends} syntax to take advantage of template inheritance.
Start with your base template file (we'll call it template.php). This file will include your header and footer code, and will specify the location for the main content (and any other blocks of template code you'd like to specify, such as an aside for instance).
(I'm using really bare bones HTML here, just for example purposes. Please don't code like this.)
template.php:
<html>
<head>
<title>{$title|default:'Default Page Title'}</title>
<meta>
<meta>
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<!-- Navigation -->
</nav>
</header>
<section class="content">
{block name="content"}{/block}
</section>
<footer>
© 2013 My Website
</footer>
</body>
Then, your individual pages would {extend} the main template file, and specify the necessary content for all of the blocks. Note that you can make blocks optional and with default values, so there is no requirement to fill all blocks (unless you code it that way).
content_page.php:
{extends file="template.php"}
{block name="content"}
<h2>Content Page</h2>
<p>Some text.</p>
{/block}
you can user following way to include smarty tpl view in your controller:
$this->smarty->view('content.tpl')
and header.tpl in content page:
{include file='header.tpl'}

Laravel 4 - including a "partial" view within a view (without using Blade template)

In Laravel 3, I used to do this.
<?php render('partials.header'); ?>
This was done in "PHP" views, without using Laravel's Blade templates.
What's the equivalent of this in version 4?
I tried
<?php #include('partials.header'); ?>
This doesn't work.
If I do
#include('partials.header')
I have to save my file as ".blade.php"
How do I include a "subview" without using the blade template?
There are different ways to include a view within a view in Laravel 4. Your choice will depend on any one of the outcomes outlined below...
For Flexibility
You can compile (render) the partial views in the appropriate Controller, and pass these views to the Main View using the $data[''] array.
This may become tedious as the number of views increase, but hey, at least there's a lot of flexibility :)
See the code below for an example:
Controller
...
public function showMyView()
{
/* Header partial view */
$data['header'] = View::make('partials.header');
/* Flexible enough for any kind of partial views you require (e.g. a Header Menu partial view) */
$data['header_menu'] = View::make('partials.header_menu');
/* Footer partial view */
$data['footer'] = View::make('partials.footer');
return View::make('myView', $data);
}
...
View
You can include the partials above as follows (at any position in your View code):
<html>
<head></head>
<body>
<!-- include partial views -->
<?php echo ($header) ?>
<?php echo ($header_menu) ?>
<div id="main-content-area"></div>
<?php echo ($footer) ?>
</body>
</html>
Your partial views will now be added to your main View.
For Simplicity
There's actually a much easier way than using the method above: Simply include this in the html of the view...
View
<html>
<head></head>
<body>
<!-- include partial view: header -->
<?php echo View::make('partials.header') ?>
<div id="main-content-area">
</div>
<!-- include partial view: footer -->
<?php echo View::make('partials.footer') ?>
</body>
</html>
Make sure that the folder structure for the partials is [views/partials/header.php] in order to provide the correct file-path to the View::make() function of Laravel.
WARNING
If you try to pass the $data['page_title'] in a controller, the nested views wont receive the data.
To pass data to these nested views you need to do it like this:
<html>
<head></head>
<body>
<?php
/* Pass page title to header partial view */
$data ['page_title'] = "My awesome website";
echo View::make('partials.header', $data);
?>
<div id="main-content-area"></div>
<?php echo View::make('partials.footer') ?>
</body>
</html>
NOTE
The question clearly stated: "Without using Blade template", so I have made sure to give a solution that does not include any Blade templating code.
Good luck :)
You can nest your partials in views try this
View::make('folder.viewFile')->nest('anyname', 'folder.FileName');
Then access the nested view file from your template {{ $anyname }} this way you don't have to include files in your view and this should work for .php file also.
I am not sure how many people have been using Laravel 4 in this post, since this post, but if you are looking to include partials or separate your view types you can do it with #includes
for example, if you want a partials folder for your header, footer, sidebar etc
create a directory for the partials under
app/views/partials
Then create a partial
app/views/partials/navigation.blade.php
Then in your master template file add the line
#include('partials.navigation')
That is all it takes.
** Bonus you can also pass data to a partial or include nested partials within a partial
I know this is a bit of a late answer, but I figured since I didn't see this solution amongst the other answers it was ok.
If you want to include your header and footer on every page I would add them into the before and after filters. Just go to filters.php in your app folder
App::before(function($request)
{
echo View::make('partials.header');
});
App::after(function($request, $response)
{
echo View::make('partials.footer');
});
When doing it this way you don't need to add anything in the view files to include them.
You can use View's nest function
View::make('default.layout')->nest('header', 'default.header');
Use the third parameter to pass data to the template
View::make('default.layout')->nest('header', 'default.header', ['name' => 'John Doe', 'test' => 'It works!']);
on your views/default/header.blade.php
<div>hey {{ $name }}! {{ $test }}</div>
I am still pretty new to Laravel, but I think the below is pretty ideal ...
Route::get('/', function()
{
$data['title'] = 'sample';
return View::make('page', $data);
});
# /views/partials/header.php
# /views/partials/footer.php
View::composer('page', function($view)
{
$view->with('header', View::make('partials.header', $view->getData()));
$view->with('footer', View::make('partials.footer', $view->getData()));
});
See Laravel View Composers .. http://laravel.com/docs/responses#view-composers
/views/page.php
<?php echo $header; ?>
<div>CONTENT</div>
<?php echo $footer; ?>
From within a view, just echo the other view:
echo View::make('header'); //This will look for a view called header.php

Categories