Autoload a view on every page with codeigniter - php

So I have my views split up basically between three (3) files:
-- Header file
$this->load->view('templates/header', $data);
-- Main Body file
$this->load->view('login_view', $data);
-- Footer file
$this->load->view('templates/footer', $data);
Now I just recently started building, but I've noticed it's really annoying to retype the header and footer on every controller to tell it to load. Is there a way to automatically load the header and footer view on every request?

I found an article long time ago, but i can't seem to find it now, basically the author, (which i forgot) override the showing of output. this method of output will access your views regarding the given controller/method and will try to search in your views directory automatically.
Use at your own risk
Application/core/MY_COntroller.php
----------------------------------------------------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
----------------------------------------------------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
This is what i use to create my template. Basically you need a directory structure as follows.
+Views
|+layouts
||-layout.php
the layout.php will serve as your master template
How to use?
extend the controller
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
Just create directory in your views and name it with the controller name i.e user then inside it add a file you named your method i.e create_user
So now your Directory structure would be
+Views
| +layouts
| |-layout.php
| |-second_master_layout.php
| +user
| |-create_user.php
Just Edit the code to give you a dynamic header or footer

Here is the simple example which i always do with my CI project.
Pass the body part as a $main variable on controller's function
function test(){
$data['main']='pages/about_us'; // this is the view file which you want to load
$data['something']='some data';// your other data which you may need on view
$this->load->view('index',$data);
}
now on the view load the $main variable
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('includes/header');?>
<div id="body">
<?$this->load->view($main);?>
</div>
<?php $this->load->view('includes/footer');?>
</div>
</body>
</html>
In this way you can always use index.php for your all the functions just value of $main will be different.
Happy codeing

Using MY_Controller:
class MY_Controller extends CI_Controller {
public $template_dir;
public $header;
public $footer;
public function __construct() {
parent::__construct();
$template_dir = 'templates'; // your template directory
$header = 'header';
$footer = 'footer';
$this->template_dir = $template_dir;
$this->header = $header;
$this->footer = $footer;
}
function load_views ($main, $data = [], $include_temps = true) {
if ($include_temps = true) {
$this->load->view('$this->template_dir.'/'.$this->header);
$this->load->view($main);
$this->load->view('$this->template_dir.'/'.$this->footer);
} else {
$this->load->view($main);
}
}
}
Then load it like: $this->load_views('login_view', $data);

You can do with library.
Create a new library file called template.php and write a function called load_template. In that function, use above code.
public function load_template($view_file_name,$data_array=array()) {
$ci = &get_instatnce();
$ci->load->view("header");
$ci->load->view($view_file_name,$data_array);
$ci->> load->view("footer");
}
You have to load this library in autoload file in config folder. so you don't want to load in all controller.
You can call
$this->template->load_template("index",$data_array);
If you want to pass date to view file, then you can send via $data_array

There is an article on this topic on ellislab forums. Please take a look. It may help you.
http://ellislab.com/forums/viewthread/86991/
Alternative way: Load your header and footer views inside the concern body view file. This way you can have batter control over files you want to include in case you have multiple headers and footer files for different purposes. Sample code shown below.
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('header');?>
<div id="body">
body
</div>
<?php $this->load->view('footer');?>
</div>
</body>
</html>

Related

call a function in themes in yii

I have a file in my yii first project. my project has a new theme with this path
first_proj\themes\project\views\layouts\main.php
and i want to call a function in it like below
<?php
if($is_project_manager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and have function in
first_proj\protected\controllers\project.php
this is
public function actionIsProjectmanager(){
$project_manager = false;
$crt = new CDbCriteria;
$crt->condition = 'user_id=:uid and role=1';
$crt->params = array('uid'=>Yii::app()->user->id);
$project_manager= projectMember::model()->findAll($crt);
// $model_result = MyModel::model()->test();
$this->render('the url to theme and main.php file', array('is_project_manager' => $project_manager));
}
how can i reach to that main.php file ? what i must write instead of
the url to theme and main.php file in my function ?
You set the controllers layout to the file. So it would look like this:
$this->layout = 'main';
Layouts must be rendered with a view file as well though.
$this->render('index', array('is_project_manager' => $project_manager));
Then place an index.php file in your views/project folder with the actions content.
This assumes you've setup your config to have the theme as project
First thing you need to know is: No need to pass layout file to the view. When you use render() function, yii automatically add layout to your view. Then, For specifying the layout, you need to use $this->layout = '//layouts/main in your action.
use this in your view
<?php
if($this->isProjectmanager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and create a helper function (not an action!) in your controller
public function IsProjectmanager(){
if ($someConditon) {
return true;
}
else {
return false;
}
}

MVC view-controller

I start to learning MVC and I write my own MVC pattern, and I can do only main-controller and main-view, but I can't understand how to make another controller/action and I want to make some link from my main-view to another page. So I have next folders and and next simle code:
In my index.php I have simple:
<?php
ini_set('display_errors',1);
require_once 'myapp/bootstrap.php';
Next, in my bootstrap.php I connect my base classes view.php, controller.php, route.php and I run the Route function run():
<?php
require_once 'base/view.php';
require_once 'base/controller.php';
require_once 'base/route.php';
include_once 'Numbers/Words.php';
Route::run(); //start routing
?>
In my route.php I write this function run()
<?php
class Route
{
static function run()
{
// controller and action by defalt
$controller_name = 'Main';
$action_name = 'index';
$routes = explode('/', $_SERVER['REQUEST_URI']);
// get controller name
if ( !empty($routes[1]) )
{
$controller_name = $routes[1];
}
// get action name
if ( !empty($routes[2]) )
{
$action_name = $routes[2];
}
// add prefix
$controller_name = 'Controller_'.$controller_name;
$action_name = 'action_'.$action_name;
// add file with controller class
$controller_file = strtolower($controller_name).'.php';
$controller_path = "myapp/controllers/".$controller_file;
if(file_exists($controller_path))
{
include "myapp/controllers/".$controller_file;
}
else
{
Route::ErrorPage404();
}
// create controller
$controller = new $controller_name;
$action = $action_name;
if(method_exists($controller, $action))
{
// invoke action of controller
$controller->$action();
}
else
{
Route::ErrorPage404();
}
}
function ErrorPage404()
{
$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
header('HTTP/1.1 404 Not Found');
header("Status: 404 Not Found");
header('Location:'.$host.'404');
}
}
It is defines my controllers and acrions routes.
And I also have my Controller_Main:
<?php
class Controller_Main extends Controller
{
function action_index()
{
$this->view->generate('main_view.php', 'template_view.php');
}
}
It loads my view and tamplate:
<div class="title">
<h1>Paymentwall PHP Test</h1>
<h2>Number To String Convertion</h2>
</div>
<div class="convertion_form">
<form name="form" class="form" method="POST" action="main/index">
<label>Enter your Number Please:</label>
<input class="number_input" type="text" name="number_input">
<input type="submit" value="Convert">
</form>
</div>
Tamplate:
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<link rel="stylesheet" href="http://localhost:81/css/style.css">
<meta charset="utf-8">
</head>
<body>
<?php include 'myapp/views/'.$content_view; ?>
</body>
</html>
So, my question is - what I need to do in my route.php to create another controller with action, and load another veiw? And how to write a link in my Main_View to another view? And I also have some web form, what I need to write in action="" ???
Please help me because I can not understand myself and find the answer.
You can create another action in your controller like this:
public function action_submit()
{
$this->view->generate('blabla');
}
And link it as /main/submit or you can create a new controller file and put some actions in it. Anyway look into some frameworks, CodeIgniter would be good for beginner, but don't stop on it once you understand how it works you can learn more complex ones, eventually coming to Symfony2/ZF2.
Edit: Actually better learn on your mistakes first, it will give you much better in-depth knowledge. And about frameworks - replace CodeIgniter (yeah it's shit, I just remember that I was learning with it at my first steps) with Silex.

ob_start() Alternative for templates in PHP?

Question Updated
I am building an MVC framework, for my templates and views, I will have a main page template file and my views will be included into this template.
The only way I have seen to do this is to use output buffereing
ob_start();
include 'userProfile.php';
$content = ob_get_clean();
Is there any other way of doing this? I think output buffering is not the best on performance as it uses a lot of memory
Here is a sample controller, the $this->view->load('userProfile', $profileData);
is the part that will be loaded using output biffering so that it can be included into the main template below into the $content part
view class
public function load($view,$data = null) {
if($data) {
$this->data = $data;
extract($data);
} elseif($this->data != null) {
extract($this->data);
}
ob_start();
require(APP_PATH . "Views/$view.php");
$content = ob_get_clean();
}
controller
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
// load a Model
$this->loadModel('profile');
//GET data from a Model
$profileData = $this->profile_model->getProfile($userId);
// load view file
$this->view->load('userProfile', $profileData);
}
}
main site template
<html>
<head>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
Using a template system is not necessarily tied to output buffering. There are a couple of things in the example code you give that should certainly not be taken for granted:
One:
flushblocks(); // what does this do??
And two:
$s = ob_get_clean();
Why does the code capture the template output into a variable? Is it necessary to do some processing on this before outputting it? If not, you could simply lose the output buffering calls and let the output be sent to the browser immediately.

How to load MVC views into main template file

I am working on my own MVC framework. Below is an example controller I have so far.
I have a way of loading models into my controller and also view files.
I am wanting to also have different template options for my site. My template will just be a page layout that inserts the views that are created from my controller into the middle of my template file.
/**
* Example Controller
*/
class User_Controller extends Core_Controller {
// domain.com/user/id-53463463
function profile($userId)
{
// load a Model
$this->loadModel('profile');
//GET data from a Model
$profileData = $this->profile_model->getProfile($userId);
// load view file and pass the Model data into it
$this->view->load('userProfile', $profileData);
}
}
Here is a basic idea of the template file...
DefaultLayout.php
<!doctype html>
<html lang="en">
<head>
</head>
<body>
Is the controller has data set for the sidebar variable, then we will load the sidebar and the content
<?php if( ! empty($sidebar)) { ?>
<?php print $content; ?>
<?php print $sidebar; ?>
If no sidebar is set, then we will just load the content
<?php } else { ?>
<?php print $content; ?>
<?php } ?>
</body>
</html>
Another Template without any header, footer, anything else, can be used for AJAX calls
EmptyLayout.php
<?php
$content
?>
I am looking for ideas on how I can load my main template file and then include and view files into the content area of my main layout file?
In the sample layout file, you can see that the content area has a variable called $content. I am not sure how I can populate that with the views content, to be inserted into my main layout template. If you have any ideas, please post sample
Something a little bit like
function loadView ($strViewPath, $arrayOfData)
{
// This makes $arrayOfData['content'] turn into $content
extract($arrayOfData);
// Require the file
ob_start();
require($strViewPath);
// Return the string
$strView = ob_get_contents();
ob_end_clean();
return $strView;
}
Then use with
$sidebarView = loadView('sidebar.php', array('stuff' => 'for', 'sidebar' => 'only');
$mainView = loadView('main.php', array('content' => 'hello',, 'sidebar' => $sidebarView);

Codeigniter - Load a specific JS library on a specific view

I'm trying to load the google maps API ie:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">
in my head template. But because I've only got one page with a google map on it (I'd rather not have the API load for all files), how would I send the message from the controller through to the view that I wish to load this particular JS file?
Thanks for your help.
CodeIgniter has a segments class. You would be able to run some code like:
<?php if($this->uri->segment(1) == 'map') { ?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">
<?php } ?>
When on page http://yoursite.com/map/ it will load the script.
One solution is to either use a template library that has javascript/css "injection" - see:
http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html#utilities
$this->template->add_js('js/jquery.js');
$this->template->add_js('alert("Hello!");', 'embed');
for more information.
If you don't want to use a template library, do something like this:
*assuming on the "Map" controller, and that you need the JS file on the default page.
class Map extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$scripts = array(
'<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">' . "\n",
'<script>something</script>');
/* this method lets you add multiple...*/
$data['scripts'] = $scripts;
$this->load->view('my_map/index', $data);
}
}
in your view:
if(isset($scripts))
{
foreach($scripts as $script)
{
echo $script;
}
}
essentially you build an array of script files/css files (whatever), then check for its prescence and dump it in the head section of your view.
I'd personally go for the template option.
Also note CI2.0 has a new javascript driver might be worth a read
<?php
/**
* Head files loader
* #author azhar
**/
function headscripts($path)
{
if(is_string($path))
{
echo "<script type='text/javascript' src='". base_url($path) ."'></script>\n";
}elseif(is_array ($path)){
foreach ($path as $p) {
echo "<script type='text/javascript' src='". base_url($p) ."'></script>\n";
}
}
}
function headlinks($path)
{
if(is_string($path))
{
echo "<link rel='stylesheet' href='". base_url($path) ."'/>\n";
}elseif(is_array ($path)){
foreach ($path as $p) {
echo "<link rel='stylesheet' href='". base_url($p) ."'/>\n";
}
}
}
?>
Add this file in your helper_directory under the name head_helper. In your controller inside an action use this code
$data['headscripts'] = array('js/main.js');
And in your view file use this function
headscripts($headscripts);
For stylesheet use this
headlinks($headlinks);
And yes do not forget to load the helper using autoload.php file in config folder like this
$autoload['helper'] = array('url', 'file','head');
Thanks for your answers guys, I ended up doing a mixture of Ross and leaf dev's suggestions before I found your answers here, so I guess I was on the right track.
My controller has:
$data['head'] = array('specificjs');
$this->load->view('view',$data);`
and my view has:
if(isset($head)){
foreach($head as $item){
$this->load->view('js/'.$item);
}
}
and my 'specificjs' view has what's required.
This way I can load as many custom scripts as I want and have the code in a view not a controller.
Thanks again, but keep any further suggestions coming!
write a helper for this. Pass the scripts names in an array and inside the helper function iterate over them and print the scripts

Categories