First of all I should say this code is a sample and i remake for you to show what i want my original code too huge and can't post here, but the logic and functions similar to this example.
I made a dynamic title in a function called getTitle() and it show on #side-bar now i want to use this title in h1 tag too, but as you see h1 tag rendered before this function, and i'm not able to move h1 tag after #side-bar. Now i want to know how can i echo a variable that generated from a function, before call this function.
PHP:
<?php
function getTitle(){
global $title;
// some code to generate dynamic title
$title = "example title";
echo $sample = "123";
return $title;
// other code
}
?>
HTML:
echo <h1><?=$title;?></h1>;
<div id="side-bar"><?php getTitle(); ?></div> <!-- call -->
I know if i move $title after calling the function getTitle(); it works fine but i need to echo $title before calling this function. Is it possible? or any idea, or logic to do this?
Also i know i can clone the title from side-bar to h1 with javascript or etc.. but this is a h1 tag and can't fill it after page load in client side.
PHP:
<?php
function getTitle(){
// some code to generate dynamic title
return ['title' => 'Example title', 'sample' => '123'];
}
?>
HTML:
$response=getTitle();
echo <h1><?=$response["sample"];?></h1>;
<div id="side-bar"><?php $response["title"]; ?></div> <!-- call -->
Your approach is wrong. Instructions are not executed after return statement.
PHP function
<?php
function getTitle(){
$title = /*generate dynamic title*/;
return $title;
}
?>
HTML
<?php $generatedTitle = getTitle(); ?>
<h1><?php echo $generatedTitle; ?></h1>
<div id="side-bar"><?php echo $generatedTitle; ?></div>
This is the second time I have used CodeIgniter and there is one thing that does not succeeds. Sending a variable from my homepage to my header. This is my controller:
public function index()
{
$data['data'] = $this->BookModel->get_author();
$this->load->view('templates/header', $data);
$this->load->view('home/index');
$this->load->view('templates/footer', $data);
}
As you see, it's loading my header, my index and my footer.
This is my index file:
<?php
$title = "Books"; ?>
<div class="content">
<table>
...
and this is my Header:
<html>
<head>
<meta charset="utf-8">
<title>Author plaza</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/style.css') ?>">
</head>
<body>
<div class="website">
<div class="header">
<h1 class="kopje"><?php echo $title; ?> </h1>
<img class="boekje" src="<?php echo base_url('assets/img/book.gif')?>">
</div>
The variable $title needs to be printed using echo in the my header as a H1. For what I know is this the right way. But it won't work.
Can someone help me?
The problem is your defining the title below the header so its not available in the header what you need to do i define it in the controller and pass it to the views $data['title']="Your Title"
public function index()
{
$data['data'] = $this->BookModel->get_author();
$data['title]="your Header";
$this->load->view('templates/header', $data);
$this->load->view('home/index',$data);
$this->load->view('templates/footer', $data);
}
in your view files you can access the key "title
Why you are not passing it from controller?
$data['data'] = $this->BookModel->get_author();
$data['title'] ="Books";
$this->load->view('templates/header', $data);
$this->load->view('home/index',$data);
$this->load->view('templates/footer', $data);
In any view:
echo $title;
change $data['data'] to $data['titel'] in index function of your controller
You can Use like this by sending seperate $titel variable
$data['titel'] ="titel";
<h1 class="kopje"><?php echo $titel; ?> </h1>
or
titel is in data variable you can use like this
<h1 class="kopje"><?php echo $data['titel']; ?> </h1>
The variable is being used in the Header whilst it is declared only in index. You are trying to use the variable before it has been assigned.
Ideally this data should be in BookModel and then referenced from there.
Or, set the variable in the Header and then use it in index.
If you want to display custom title for different pages you should use controller to pass title to the view. In your code you are passing get_author() to the variable $data['data'] so that you can use author data from your view using $data because you have passed data key in the $data array. Same as you can do it for title also like $data['title'] = "Book Title" using this statement you can print title on the page. By echoing $title on the view page
public function index()
{
$data['data'] = $this->BookModel->get_author();
$data['title'] = "Book Title"
$data['what_ever_print'] = "Pass value from here and access from view like echo $what_ever_print"
$this->load->view('templates/header', $data);
$this->load->view('home/index', $data);
$this->load->view('templates/footer', $data);
}
In the view you can print like this
<h1 class="kopje"><?php echo $title; ?> </h1>
OR If you want to print on the title tag you can do like below
<title><?php echo $title; ?> </title>
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's some stuff stored in a database table:
<section id="earth">
<h2>Earth</h2>
<div class="MainDiv">
(article)
</div>
</section>
<section id="mars">
<h2>Mars</h2>
<div class="MainDiv">
(article)
</div>
</section>
All I want to do is modify the display so each section has a unique data-target and each div has a matching ID. (I gave the div's a class - MainDiv - to distinguish them from any nested divs they might contain.)
<section id="earth" data-target="a">
<h2>Earth</h2>
<div class="MainDiv" id="a">
<section id="mars" data-target="b">
<h2>Mars</h2>
<div class="MainDiv" id="b">
Ideally, I'd like to keep the data-targets and matching ID's simple - single, lower case letters would be perfect. Is there a PHP function that can do that? If not, do you know a regex script that would work?
No, as much as possible, don't work on regex for this task. This is what HTML parsers are for. There is already a class for PHP that does this, its DOMDocument.
First, just load up the class (this is built-in already), then you load the HTML markup, get all the elements you need (in this case, the section tags). After you got all the section tags, iterate on those found and add those data attributes you want for each of those (including the div tags), then you put it back together as string again. Here's some to get you started. Rough Example:
$i = 1; // initialize counter
// initialize DOMDocument
$dom = new DOMDocument;
#$dom->loadHTML($html); // load the markup
$sections = $dom->getElementsByTagName('section'); // get all section tags
if($sections->length > 0) { // if there are indeed section tags inside
// work on each section
foreach($sections as $section) { // for each section tag
$section->setAttribute('data-target', 'section' . $i); // set id for section tag
// get div inside each section
foreach($section->getElementsByTagName('div') as $div) {
if($div->getAttribute('class') == 'MainDiv') { // if this div has class maindiv
$div->setAttribute('id', 'div' . $i); // set id for div tag
}
}
$i++; // increment counter
}
}
// back to string again, get all contents inside body
$html = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $child) {
$html .= $dom->saveHTML($child); // convert to string and append to the container
}
// output
echo $html;
Sample Output
I would do as #Barmar suggested. Doing a0,a1,a2, ..., This way we can have as many as we want and echo each <section> in PHP via loop. If we went from a,b,c,...,z what would be next? aa? And you will have to program that in. For each element I would use a simple for loop and use the index for each element. For example this:
class Planet
{
public $title;
public $name;
public $article;
function __construct($title, $name, $article) {
$this->name = $name;
$this->title = $title;
$this->article = $article;
}
}
$planets = array(
new Planet("earth", "Earth", "Hello World!"),
new Planet("mars", "Mars", "Hello World Again!")
);
for( $i = 0; $i < count($planets); $i++ ) {
$id = strtolower($planets[$i]->name);
$name = $planets[$i]->name;
$article = $planets[$i]->article;
echo <<<HERE
<section id="$id" data-target="a$i">
<h2>$name</h2>
<div class="MainDiv" id="a$i">
$article
</div>
</section>
HERE;
}
Would give the output:
<section id="earth" data-target="a0">
<h2>Earth</h2>
<div class="MainDiv" id="a0">
Hello World!
</div>
</section>
<section id="mars" data-target="a1">
<h2>Mars</h2>
<div class="MainDiv" id="a1">
Hello World Again!
</div>
</section>
I m new to CodeIgniter so i m facing some problem regarding adding contents from one view to another.
I have three views header, contents and footer and want to put these views in one main container with 960px width.
coz i m new so expecting some simple answer.
My code is this
public function index()
{
$this->load->view('header');
$this->load->view('content');
$this->load->view('footer');
}
Thanks
You need this.
$output = $this->load->view('header', 'your_data', true);
$output .= $this->load->view('content', 'your_other_data', true);
$output .= $this->load->view('footer', 'your_last_data', true);
$this->output->set_output($output);
For more Info
Just call the views inside the main view
public function index()
{
$data['content']['title'] = 'title';
$data['content']['body'] = 'body';
$this->load->view('layout',$data);
}
In views/layout.php
<div id="main_container">
<?php
$this->load->view('header',$content);
$this->load->view('content',$content);
$this->load->view('footer');
?>
</div>
Ex. in views/header.php
<title>.<?php echo $title;?></title>
in views/content.php
<div id="main_body"><?php echo $body;?></div>
function index()
{
$data['title'] ="Details";
$this->load->view("headerview",$data);
$data['batches'] =$this->detailsmodel->getname();
$this->load->view('content',$data);
$this->load->view("footerview");
}
// something similar to this ?
Didn't understand ur question properly brief what u want ? is this the answer u looking for