I just go to the point.
Nvm need to add more text to much code..
Trying to load a Template with php inside it but php prints in html instead.
Init.php
class Init {
public static $ROOT = '';
public static $TEMPLATE = '';
public static $SERVICE = '';
public static function start() {
// Init Paths
Init::$ROOT = str_replace("\\", "/", __DIR__);
Init::$TEMPLATE = Init::$ROOT . "/Template/";
Init::$SERVICE = Init::$ROOT . "/Service/";
// Init Template.php class
require_once(Init::$SERVICE . "Template.php");
// Load template Top.php
$top = new Template(Init::$TEMPLATE . "Layout/Top.php");
echo $top->load(); // Show Top.php
}
}
Top.php
<!DOCTYPE html>
<html>
<?
// Load template Head.php
$head = new Template(Init::$TEMPLATE . "Layout/Head.php");
$head->set("TITLE", "Dashboard"); //Set [#TITLE] to Dashboard
$head->load(); // Show Head.php
?>
</html>
Head.php
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[#TITLE] | cwEye</title> <!-- [#TITLE] will be Dashboard-->
<?
echo "Hello"; // ERROR -> This will print <? echo"Hello"; ?> in my page
?>
</head>
Template.php
<?
class Template {
protected $file;
protected $values = array();
private static $templateFile = null;
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
// This code works but it will not load php inside
public function load() {
if (!file_exists($this->file)) return "Error loading template file ($this->file).";
ob_start();
include_once($this->file);
$data = ob_get_clean();
foreach ($this->values as $key => $value) {
echo str_replace("[#$key]", $value, $data);
}
if(count($this->values) == 0) echo $data;
}
}
?>
Ive played with allot of functions to make it but it does not work...
It just prints the php in html.
Tried with
ob_start();
include_once(FILE);
$data = ob_get_clean();
Don't use short tags like <? or <?=, use <?php instead. You probably have your short_open_tag set to false in php.ini. If you are using PHP 7 then you should know short tags were removed completely and wont work anymore.
In head.php use the full tag. Change
to
<?php echo "hello"; ?>
I really don't enjoy writing in every controller:
$this->load->view('templates/header');
$this->load->view('body');
$this->load->view('templates/footer');
Is it possible to do, that header and footer would be included automatically and if we need to change it, we could also do that? How do you deal with that? Or it's not a problem in your opinion? Thanks.
Here's what I do:
<?php
/**
* /application/core/MY_Loader.php
*
*/
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
For CI 3.x:
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
if($return):
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
return $content;
else:
$this->view('templates/header', $vars);
$this->view($template_name, $vars);
$this->view('templates/footer', $vars);
endif;
}
}
Then, in your controller, this is all you have to do:
<?php
$this->load->template('body');
Yes.
Create a file called template.php in your views folder.
The contents of template.php:
$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');
Then from your controller you can do something like:
$d['v'] = 'body';
$this->load->view('template', $d);
This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:
Consider if you create a view called init.php that contains the single line:
$this->load->view('html');
Now create the view html.php with contents:
<!DOCTYPE html>
<html lang="en">
<? $this->load->view('head'); ?>
<? $this->load->view('body'); ?>
</html>
Now create a view head.php with contents:
<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>
And a body.php view with contents:
<body>
<div id="mainWrap">
<? $this->load->view('header'); ?>
<? //FINALLY LOAD THE VIEW!!! ?>
<? $this->load->view($v); ?>
<? $this->load->view('footer'); ?>
</div>
</body>
And create header.php and footer.php views as appropriate.
Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html> and <body> tags, your headers and footers will be loaded in.
$d['v'] = 'fooview'
$this->load->view('init', $d);
Try following
Folder structure
-application
--controller
---dashboards.php
--views
---layouts
----application.php
---dashboards
----index.php
Controller
class Dashboards extends CI_Controller
{
public function __construct()
{
parent::__construct();
$data = array();
$data['js'] = 'dashboards.js'
$data['css'] = 'dashbaord.css'
}
public function index()
{
$data = array();
$data['yield'] = 'dashboards/index';
$this->load->view('layouts/application', $data);
}
}
View
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Some Title</title>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/app.css" />
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/<?php echo $css; ?>" />
</head>
<body>
<header></header>
<section id="container" role="main">
<?php $this->load->view($yield); ?>
</section>
<footer></footer>
<script src="<php echo base_url(); ?>assets/js/app.js"></script>
<script src="<php echo base_url(); ?>assets/js/<?php echo $js; ?>"></script>
</body>
</html>
When you need to load different js, css or whatever in the header or footer use the __construct function to $this->load->vars
Kind of a rails like approach here
Or more complex, but makes life easy is to use more constants in boot.
So subclasses can be defined freely, and a single method to show view.
Also selected constants can be passed to javascript in the header.
<?php
/*
* extends codeigniter main controller
*/
class CH_Controller extends CI_Controller {
protected $viewdata;
public function __construct() {
parent::__construct();
//hard code / override and transfer only required constants (for security) server constants
//such as domain name to client - this is for code porting and no passwords or database details
//should be used - ajax is for this
$this->viewdata = array(
"constants_js" => array(
"TOP_DOMAIN"=>TOP_DOMAIN,
"C_UROOT" => C_UROOT,
"UROOT" => UROOT,
"DOMAIN"=> DOMAIN
)
);
}
public function show($viewloc) {
$this->load->view('templates/header', $this->viewdata);
$this->load->view($viewloc, $this->viewdata);
$this->load->view('templates/footer', $this->viewdata);
}
//loads custom class objects if not already loaded
public function loadplugin($newclass) {
if (!class_exists("PL_" . $newclass)) {
require(CI_PLUGIN . "PL_" . $newclass . ".php");
}
}
then simply:
$this->show("<path>/views/viewname/whatever_V.php");
will load header, view and footer.
I tried almost all the answers proposed on this page and many other stuff. The best option I finally keeped on all my websites is the following architecture:
A single view
I display only one view in the browser. Here is my main view (/views/page.php):
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<?= $header ?? '' ?>
</head>
<body>
<div style="width:1200px">
<?= $content ?? '' ?>
</div>
</body>
</html>
Controllers deal with multiple views
Of course, I had several views but they are concatenated to build the $header and the $content variables. Here is my controller:
$data['header'] = $this->load->view('templates/google-analytics', '', TRUE)
.$this->load->view('templates/javascript', '', TRUE)
.$this->load->view('templates/css', '', TRUE);
$data['content'] = $this->load->view('templates/navbar', '', TRUE)
.$this->load->view('templates/alert', $myData, TRUE)
.$this->load->view('home/index', $myData, TRUE)
.$this->load->view('home/footer', '', TRUE)
.$this->load->view('templates/modal-login', '', TRUE);
$this->load->view('templates/page', $data);
Look how beautiful and clear is the source code.
You no longer have HTML markup opened in one view and closed in another.
Each view is now dedicated to one and only one stuff.
Look how views are concatenated: method chaining pattern, or should we say: concatanated chaining pattern!
You can add optional parts (for example a third $javascript variable at the end of the body)
I frequently extend CI_Controller to overload $this->load->view with extra parameters dedicated to my application to keep my controllers clean.
If you are always loading the same views on several pages (this is finally the answer to the question), two options depending on your needs:
load views in views
extend CI_Controller or CI_Loader
I'm so proud of this architecture...
A simple rewrite of #Landons MY_Loader, to include multiple files for the body, e.i. page unique sidebars...
<?php
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
$content = $this->view('frontend/templates/header', $vars, $return);
if(is_array($template_name)) { //return all values in contents
foreach($template_name as $file_to_load) {
$content .= $this->view('frontend/'.$file_to_load, $vars, $return);
}
}
else {
$content .= $this->view('frontend/'.$template_name, $vars, $return);
}
$content .= $this->view('frontend/templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
This works both ways...
Including one file to template:
$data['moo'] = 'my data'];
$this->load->template('home', $data);
Include multiple files to template:
$data['catalog'] = 'catalog load 1';
$data['sidebar'] = 'sidebar load 2';
$load = array('catalog/catalog', 'catalog/sidebar');
$this->load->template($load, $data);
CodeIgniter-Assets is easy to configure repository to have custom header and footer with CodeIgniter I hope this will solve your problem.
Redefine the CI_Loader::view function by adding a file named as 'MY_Loader.php' in your application/core folder and adding the following content
/**
* /application/core/MY_Loader.php
*/
class MY_Loader extends CI_Loader
{
public function view($view, $vars = array(), $return = FALSE, $include_template=TRUE)
{
$header='';
$footer='';
if($include_template)
{
$header=parent::view('templates/header',$vars,$return);
}
$content=parent::view($view, $vars,$return);
if($include_template)
{
$footer=parent::view('templates/footer',$vars,$return);
}
if($return)
return "$header$content$footer";
return $this;
}
}
You can use your config.php file, and also use the power of helpers in CodeIgniter.
$config['header_css'] = array('style.css','prettyPhoto.css','nivo-slider.css');
$config['header_js'] = array('core.js','core.js',
'jquery-1.4.1.min.js',
'jquery-slidedeck.pack.lite.js',
'jquery-prettyPhoto.js',
'jquery.nivo.slider.js');
Source: https://jamshidhashimi.com/dynamically-add-javascript-and-css-files-in-codeigniter-header-page/
Here is how I handle mine. I create a file called template.php in my views folder. This file contains all of my my main site layout. Then from this template file I call my additional views. Here is an example:
<!doctype html>
<html lang="en">
<head>
<meta charset=utf-8">
<title><?php echo $title; ?></title>
<link href="<?php echo base_url() ;?>assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url() ;?>assets/css/main.css" rel="stylesheet" type="text/css" />
<noscript>
Javascript is not enabled! Please turn on Javascript to use this site.
</noscript>
<script type="text/javascript">
//<![CDATA[
base_url = '<?php echo base_url();?>';
//]]>
</script>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="top">
<?php $this->load->view('top');?>
</div>
<div id="main">
<?php $this->load->view($main);?>
</div>
<div id="footer">
<?php $this->load->view('bottom');?>
</div>
</div><!-- end container -->
</div><!-- end wrapper -->
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-1.8.2.min.js" ></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
</body>
</html>
From my controller, I will pass the name of the view to $data['main']. So I will do something like this then:
class Main extends CI_Controller {
public function index()
{
$data['main'] = 'main_view';
$data['title'] = 'Site Title';
$this->load->vars($data);
$this->load->view('template', $data);
}
}
I had this problem where I want a controller to end with a message such as 'Thanks for that form' and generic 'not found etc'.
I do this under views->message->message_v.php
<?php
$title = "Message";
$this->load->view('templates/message_header', array("title" => $title));
?>
<h1>Message</h1>
<?php echo $msg_text; ?>
<h2>Thanks</h2>
<?php $this->load->view('templates/message_footer'); ?>
which allows me to change message rendering site wide in that single file for any thing that calls
$this->load->view("message/message_v", $data);
This question has been answered properly, but I would like to add my approach, it's not that different than what the others have mentioned.
I use different layouts pages to call different headers/footers, some call this layout, some call it template etc.
Edit core/Loader.php and add your own function to load your layout, I called the function e.g.layout.
Create your own template page and make it call header/footer for you, I called it default.php and put in a new directory e.g. view/layout/default.php
Call your own view page from your controller as you would normally. But instead of calling $this-load->view use $this->load->layout, layout function will call the default.php and default.php will call your header and footer.
1)
In core/Loader.php under view() function I duplicated it and added mine
public function layout($view, $vars = array(), $return = FALSE)
{
$vars["display_page"] = $view;//will be called from the layout page
$layout = isset($vars["layout"]) ? $vars["layout"] : "default";
return $this->_ci_load(array('_ci_view' => "layouts/$layout", '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
2) Create layout folder and put default.php in it in view/layout/default.php
$this->load->view('parts/header');//or wherever your header is
$this->load->view($display_page);
$this->load->view('parts/footer');or wherever your footer is
3) From your controller, call your layout
$this->load->layout('projects');// will use 'view/layout/default.php' layout which in return will call header and footer as well.
To use another layout, include the new layout name in your $data array
$data["layout"] = "full_width";
$this->load->layout('projects', $data);// will use full_width.php layout
and of course you must have your new layout in the layout directory as in:
view/layout/full_width.php
Using This Helper For Dynamic Template Loading
// get Template
function get_template($template_name, $vars = array(), $return = FALSE) {
$CI = & get_instance();
$content = "";
$last = $CI - > uri - > total_segments();
if ($CI - > uri - > segment($last) != 'tab') {
$content = $CI - > load - > view('Header', $vars, $return);
$content. = $CI - > load - > view('Sidebar', $vars, $return);
}
$content. = $CI - > load - > view($template_name, $vars, $return);
if ($CI - > uri - > segment($last) != 'tab') {
$content. = $CI - > load - > view('Footer', $vars, $return);
}
if ($return) {
return $content;
}
}
i had reached for this and i hope to help all create my_controller in application/core
then put this code in it with change as your file's name
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// this is page helper to load pages daunamically
class MY_Controller extends CI_Controller {
function loadPage($user,$data,$page='home'){
switch($user){
case 'user':
$this->load->view('Temp/head',$data);
$this->load->view('Temp/us_sidebar',$data);
$this->load->view('Users/'.$page,$data);
$this->load->view('Temp/footer',$data);
break;
case 'admin':
$this->load->view('Temp/head',$data);
$this->load->view('Temp/ad_sidebar',$data);
$this->load->view('Admin/'.$page,$data);
$this->load->view('Temp/footer',$data);
break;
case 'visitor';
$this->load->view('Temp/head',$data);
$this->load->view($page);
$this->load->view('Temp/footer',$data);
break;
default:
echo 'wrong argument';
die();
}//end switch
}//end function loadPage
}
in your controller
use this
class yourControllerName extends MY_Controller
note : about name of controller prefix you have to be sure about your prefix on config.php file
i hope that give help to any one
Here is my code:
My root directory is: root
An index.php file located at the root/index.php
<?php
require_once('root/includes/initialize.php');
<?php template('header.php', 'TITLE');?>;
?>
<div id="main">
//SOME CONTENT
</div>
My initialize.php file gets all my core include files and puts them into one "require_once". Located in root/includes/initialize.php
<?php
//Define Path
defined('LIB_PATH') ? null : define('LIB_PATH', 'root/includes/');
//Core Functions
require_once(LIB_PATH.'functions.php');
//Core Objects
require_once(LIB_PATH.'_database.php');
require_once(LIB_PATH.'_session.php');
//Classes
require_once(LIB_PATH.'_user.php');
?>
updated**
My functions.php file includes a simple templating function that grabs a template file such as my header.php. It is located in root/includes/functions.php
<?php
//Templating
function template($path="", $pageTitle=NULL) {
if ($pageTitle != NULL) {
$_POST['page_title'] = $pageTitle;
}
include(root/public/templates/'.$path);
}
?>
My _session.php file takes care of my session control. Located in root/includes/_session.php
<?php
/**
* Class for Sessions
*/
class Session
{
public $logged_in = FALSE;
public $uid;
function __construct() {
session_start();
$this->check_login();
}
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
} else {
unset($this->uid);
$this->logged_in = FALSE;
}
}
public function logged_in() {
return $this->logged_in;
}
public function login($user) {
if ($user) {
$this->uid = $_SESSION['uid'] = $user;
$this->logged_in = TRUE;
}
}
public function logout() {
unset($_SESSION['uid']);
session_unset();
session_destroy();
redirect(WEB_ROOT);
}
}
$session = new Session();
?>
updated**
My header.php holds the top of all the pages in my site. Located in root/public/templates/header.php. This is the file I'm having trouble with, I cant figure out why I am unable to echo out the $session->uid or the $_SESSION['uid'] in this file.
<html>
<head>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="root/public/css/style.css">
<title>MY SITE</title>
</head>
<body>
<div id="header">
<div id="logo">
<?php echo $_POST['page_title'];?>
</div>
<?php echo $session->uid;?> //DOESN'T WORK
</div>
I am able to echo out everything just fine in my index.php file and the other files on my site, but not in the included header.php. Any one know why? Thanks.
session_start() must be called at the start of EVERY php file that is going to either set or get a session variable. The only place I see you calling session_start() is in the one file.
http://www.php.net/manual/en/session.examples.basic.php
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Also on a side note. I'm looking at your class Session and I'm not seeing any $mySession = new Session(); anywhere to also start a session.
UPDATE:
I recreated your basic file structure and code in my IDE and got it work by adding this line in the class.
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
}
else {
unset($this->uid);
$this->logged_in = FALSE;
$_SESSION['uid'] = session_id();
/*Add this next line */
$this->uid = $_SESSION['uid'];
}
}
The first time I ran index.php just the <?php echo $_SESSION['uid']; ?> part of header worked. Refreshed and <?php echo $session->uid; ?> also worked so it echoed twice. This tells me your class isn't assigning the ID to a class variable, hopefully this is the desired out come as it worked on my end, or you can tweek it as needed.
UPDATE 2:
Function File (edit to match your paths but you need to return a string)
<?php
//Templating
function template($path = "", $pageTitle = NULL) {
if ($pageTitle != NULL) {
$_POST['page_title'] = $pageTitle;
}
return "$path";
}
?>
Then in the Index.php file add this way instead:
<?php
require_once('initialize.php');
include(template('header.php', 'TITLE'));
//include('header.php');
?>
<div id="main">
//SOME CONTENT
</div>
</body>
</html>
_session.php file:
<?php
/**
* Class for Sessions
*/
class Session
{
public $logged_in = FALSE;
public $uid;
function __construct() {
session_start();
$this->check_login();
}
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
}
else {
unset($this->uid);
$this->logged_in = FALSE;
$_SESSION['uid'] = session_id();
$this->uid = $_SESSION['uid'];
}
}
public function logged_in() {
return $this->logged_in;
}
public function login($user) {
if ($user) {
$this->uid = $_SESSION['uid'] = $user;
$this->logged_in = TRUE;
}
}
public function logout() {
unset($_SESSION['uid']);
session_unset();
session_destroy();
redirect(WEB_ROOT);
}
}
$session = new Session();
?>
And header.php
<html>
<head>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="style.css">
<title>MY SITE</title>
</head>
<body>
<div id="header">
<div id="logo">
<?php echo $_POST['page_title'];?>
</div>
<?php echo $session->uid; ?> //WORKS NOW
<?php echo $_SESSION['uid']; ?> //WORKS NOW
</div>
The question is pretty vague. My guess would be, that since your index.php file in located in root/index.php, then your include paths:
require_once('root/includes/initialize.php');
include('root/public/templates/header.php');
are incorrect. You don't start with a /, so paths are relative, and considering the location of your index.php, you are including root/root/includes/initialize.php. If that's the case, you should easily spot that by the lack of <title>MY SITE</title> and TITLE on your page. Haven't you?
If that's the problem, I suggest you define some kind of HOME constant, for example
define ('HOME', dirname(__FILE__));
// or define ('HOME', __DIR__); depending on your PHP version
so that you can then include everything relative to that constant
require_once(HOME . '/includes/initialize.php');
Other than that I don't see any errors in your code.
Here is the class:
functions.php
class buildPage {
public function Set($var,$val){
$this->set->$var = $val;
}
function Body(){
ob_start();
include('pages/'.$this->set->pageFile);
$page = ob_get_contents();
ob_end_clean();
return $page;
}
function Out(){
echo $this->Body();
}
}
So here is the main (index) page of the script.
index.php
include_once('include/functions.php');
$page = new buildPage();
$page->Set('pageTitle','Old Title');
$page->Set('pageFile','about.php');
$page->Out();
Now as you can see, it includes about.php file through class, actually inside the class.
And now, I want to access the same buildPage() class to change the page title.
about.php
<?php
$this->Set('pageTitle','New Title');
echo '<h1>About Us</h1>';
?>
But unfortunately, nothing happens.
Please be kind to take few minutes to give me some help!
OK. I've managed to fix the problem myself.
Changed function Body() and Out() as follows :
function Body(){
$pageFile = $this->Get('pageFile');
if(empty($pageFile)){
$pageFile = 'home.php';
}
$page_path = 'pages/'.$pageFile;
ob_start();
include($page_path);
if(!empty($page_set_arr) && is_array($page_set_arr)){
foreach($page_set_arr AS $k=>$v){
$this->Set($k,$v);
}
}
$page = ob_get_clean();
return $page;
}
function Out(){
$body = $this->Body();
echo $this->Header();
echo $body;
echo $this->Footer();
}
And then changed the file about.php as follows :
<?php
$page_set_arr = array(
'pageTitle' => 'About Us'
);
?>
<h1>About Us</h1>