I am building a website with php and it has 20 pages. In the homepage
I would like to have a slider and some other plugins which I include them
in the head. In the footer I link also some JS files.
When we use php we have header.php and footer.php
Some of the plugins are not needed on some pages but the header.php
and footer.php is included on those pages. Is there a way to remove
those plugins on those specific pages? or I have to include everything
even if they are not needed? Also I would like to add some other plugins
in some of the pages that are not needed in the Home Page. Should I create multiple header.php and footer.php and include them when necessary?
What is the solution to this problem?
Thanks.
Example:
Home Page those are needed:
Header.php
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
<link rel="stylesheet" href="plugin03.css">
<link rel="stylesheet" href="plugin04.css">
Footer.php
<script src="plugin01.js"></script>
<script src="plugin02.js"></script>
<script src="plugin03.js"></script>
<script src="plugin04.js"></script>
Random Page:
I need only
header.php
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
footer.php
<script src="plugin01.js"></script>
<script src="plugin02.js"></script>
What you can do is create a helper function to assist with loading required assets and then have a common header.php / footer.php like this:
helpers.php
<?php
function loadStyles($assets = array()) {
foreach ($assets as $asset) {
echo '<link rel="stylesheet" href="'. $asset .'.css">'."\r\n";
}
}
function loadScripts($assets = array()) {
foreach ($assets as $asset) {
echo '<script src="'. $asset .'.js"></script>'."\r\n";
}
}
?>
Then, update your header.php like this:
<?php
// Load required stylehseets for this page
if (isset($styleAssets)) {
loadStyles($styleAssets);
}
// Rest of your common header stuff here
?>
Then do something similar with footer.php like this:
<?php
// Load required scripts for this page
if (isset($scriptAssets)) {
loadScripts($scriptAssets);
}
// Rest of your common footer stuff here
?>
Then you put it all together like this. For example, this is your "home.php" page:
<?php
// Load helpers
require 'helpers.php'
// Define required styles for this page
$styleAssets = array(
'plugin01',
'plugin02',
'plugin03',
'plugin04'
);
// Load header
require 'header.php'
// Rest of the "home" page code goes here
// Define required scripts for this page
$scriptAssets = array(
'plugin01',
'plugin02',
'plugin03',
'plugin04'
);
// Load footer
require 'footer.php'
?>
Now, for another random.php page, you simply re-use the script like this:
<?php
// Load helpers
require 'helpers.php'
// Define required styles for this page
$styleAssets = array(
'plugin01',
'plugin02'
);
// Load header
require 'header.php'
// Rest of the "random" page code goes here
// Define required scripts for this page
$scriptAssets = array(
'plugin01',
'plugin02'
);
// Load footer
require 'footer.php'
?>
You'll have to define for each page its required plugins (resources).
In the header and footer files, simply loop through that array and call the resources.
It's a bit more work but it's a better organised method and in case you'll have in the future a new page with other plugins, instead of writing patched, you'll easily update it using this mechanism.
PageX.php
//$this_page = 'pageX';
$plugins = array(
'css' => array(
'pluginName1' => 'plugin-name-1.css',
'pluginName2' => 'plugin-name-2.css',
),
'js' => array(
'pluginName1' => 'plugin-name-1.js'
)
);
require_once 'header.php;
//....
//...
require_once 'footer.php';
Header.php
foreach($plugins['css'] as $name => $resource_url){
echo '<link rel="stylesheet" href="'.$resource_url.'">';
}
Footer.php
foreach($plugins['js'] as $name => $resource_url){
echo '<script src="'.$resource_url.'"></script>';
}
In your Header.php you can check for the current page.
if( basename($_SERVER['PHP_SELF']) == 'homepage.php')
{ ?>
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
<link rel="stylesheet" href="plugin03.css">
<link rel="stylesheet" href="plugin04.css">
<?php
}
Related
I am trying toinclude css file in the following code.
Config :
$config['base_url'] = 'http://localhost/ASOFT/Projects/CI_search';
$config['site_url'] = 'http://localhost/ASOFT/Projects/CI_search/index.php';
$config['js'] = 'assets/js';
View:
<link rel="stylesheet" href="<?php echo $base?>/<?php echo $css?>/style.css">
<link rel="stylesheet" href="<?php echo $base?>/<?php echo $css?>/bootstrap.min.css">
<script src="<?php echo $base?>/<?php echo $js?>/jquery.min.js"></script>
<script src="<?php echo $base?>/<?php echo $js?>/jquery.js"></script>
<script src="<?php echo $base?>/<?php echo $js?>/bootstrap.min.js"></script>
I put the css file in CI_search/css and js file in CI_search/assets/js
I got the error undefined variable css and undefined variable js.Please provide solution for this problem.
UPDATE
Controller:
public function index() {
$this->data = array(
'site' => $this->config->item('site_url'),
'base' => $this->config->item('base_url'),
'css' => $this->config->item('css'),
'js' => $this->config->item('js'),
'image'=>$this->config->item('image')
);
$data = $this->data;
$data['error'] = '';
$this->load->view('index',$data);
}
As far as i can see, you din't declared $config['css'] in your config file, so it's normal to get undefined variable error for css. But you shouldn't have problem with js.
When declaring your base_url use trailing slash at the end (eg. "http://localhost/fancysite/")
Also you can use CI's url helper to use functions like base_url() or site_url() and many more. (as #Likee suggested).
config.php
// this should be the first variable in CI's config.php
$config['base_url'] = "http://localhost/ASOFT/Projects/CI_search/";
// many more lines with other configuration variables
// ..................................................
// ..................................................
// ..................................................
// your own configuration variables at the end of file
$config['css'] = 'css/';
$config['js'] = 'assets/css/';
$config['image'] = 'images/';
controller
public function index() {
// loading url helper to use base_url() function in the view,
// if you load this helper in autoload.php you don't need to load it here again
$this->load->helper('url');
// if you didn't declare data as class property
// you can simply use
// $data = array(
// 'css' => $this->config->item('css'),
// 'js' => $this->config->item('js'),
// 'image'=>$this->config->item('image')
// );
$this->data = array(
'css' => $this->config->item('css'),
'js' => $this->config->item('js'),
'image'=>$this->config->item('image')
);
// you really don't need the line below
// $data = $this->data;
$this->data['error'] = '';
$this->load->view('index',$this->data);
}
view
<link rel="stylesheet" href="<?php echo base_url($css . 'style.css'); ?>">
<link rel="stylesheet" href="<?php echo base_url($css . 'bootstrap.min.css'); ?>">
<script src="<?php echo base_url($js . 'jquery.min.js'); ?>"></script>
<!-- do you really need to include jquery.js while you included jquery.min.js above? but here we go :) -->
<script src="<?php echo base_url($js . 'jquery.js'); ?>"></script>
<script src="<?php echo base_url($js . 'bootstrap.min.js'); ?>"></script>
Probably you will need to use url helper a lot. So you can autoload it in autoload.php file in config folder. it must be somewhere around line 90
$autoload['helper'] = array('url');
There are many ways to include css and js file in codeigniter.
This how I do it.
FIRST: Create a folder outside the application folder and named it any named you liked but I prefer to named it as resources. Create a sub folders like js, css, images and others. Place all your files in here for future references.
SECOND: Open the the contants.php saved in application/config and paste this code.
define('CSS', 'http://localhost/yourfolder/resources/css');
define('JS', 'http://localhost/yourfolder/resources/js');
define('IMAGES', 'http://localhost/yourfolder/resources/images');
NOTE: Update this code depends on your needs.
THIRD: On your view file, you can access this files by,
<link rel="stylesheet" href="<?php echo(CSS.'bootstrap.min.css'); ?>">
<script type="text/javascript" src='<?php echo(CSS.'bootstrap.min.css'); ?>'></script>
Refer to this link. How can I include the CSS file in CodeIgniter?
I hope this helped.
Bind your variables to view like this:
$this->load->view('viewName', $config);
And array $config should be available in your controller method.
Instead setting $config['base_url'] you can use function base_url().
well if at all possible determine what your path structure will be and then just use it in the view with base_url() .
<link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">
<script src="<?php echo base_url();?>assets/js/blahblah.js"></script>
you can even have a few simple templates, and then call the appropriate template.
if that is impossible - then push this logic and output to a model or similar so that it can be called by different controllers. otherwise you are going to have to update folder names and file paths in your controllers.
I have modules for category:
+modules/
+category/
+assets/
+css/
+js/
+images/
+components/
+controllers/
+models/
+views/
-CategoryModule.php
What is the best way to includes the css and jss to all views?
Publish and register in CategoryModule init method - this will make available your css and js in category module.
Something like this:
public function init() {
$path = $this->assetManager->publish(Yii::getPathOfAlias('application.modules.category.assets'));
$this->clientScript->registerCssFile($path . '/css/some-css.css', 'screen, projection');
$this->clientScript->registerScriptFile($path . '/js/some-js.js');
}
create module layout file under views/layout and call it in module config file as
$this->layoutPath = Yii::getPathOfAlias('application.modules.moduleName.views.layouts');
$this->layout = '/layouts/layoutname';
register all the js and css file as #PeterM mentioned
Create a folder "layouts" in your views folder. Create main.php in that layouts folder.
In your , add following code:
<link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl; ?>/css/style.css" type="text/css" media="screen"/>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/cycle.js"></script>
This is your default layout. So add,
<?php echo $content; ?>
This is another method to include css and js in all views.
Easy using this static method
<?php Yii::app()->clientScript->registerCssFile(Yii::getPathOfAlias('application.modules.curriculo.assets') . '/bootstrap/datepicker/css/datepicker.css'); ?>
<?php Yii::app()->clientScript->registerScriptFile(Yii::getPathOfAlias('application.modules.curriculo.assets') . '/bootstrap/datepicker/js/bootstrap-datepicker.js'); ?>
This should help you:
http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/
All three sections (beginContent, container and endContent) are explained in detail.
I am using zend. When i use below code,
<?= $this->headLink()
->appendStylesheet(BASE_URL . 'css/css.css');
?>
This outputs like below with out close element.
<link href="/ecomos3/css/css.css" media="screen" rel="stylesheet" type="text/css" >
so this one fails in w3 validation and getting "end tag for "link" omitted, but OMITTAG NO was specified"
i want the link tag should be
<link href="/ecomos3/css/css.css" media="screen" rel="stylesheet" type="text/css" />
How can i do it in zend ? Kindly advice on this.
You need to specify the docType using the doctype helper
You can do it in your bootstrap if you wish:-
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
}
}
Or add this line to your config.ini file:-
resources.view.doctype = "XHTML1_STRICT"
I am trying to find the cleanest way to merge multiple html files into one html file. This way I can easily change parts of the html or show them only on certain pages. The file list is as followed:
page.tpl (header, footer, head info)
sidebar.tpl (contains sidebar and sidebar blocks)
nav.tpl(contains navigation links in nested UL)
The page.tpl file looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Brandon" />
<meta name="robots" content="noindex,nofollow" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<?php print $stylesheets; ?>
<?php print $scripts; ?>
</head>
<body>
<section id="wrapper">
<header>Header Title</header>
<nav><?print $nav; ?></nav>
<section><?php print $content; ?></section>
<aside> <?php print $sidebar; ?><aside>
<footer>© 2011 Brandon License: GPLv2</footer>
</section>
</body>
</html>
The main function I have to include everything is:
function theme($tpl, $vars = array()) {
extract($vars);
ob_start();
require($tpl);
$template = ob_get_contents();
ob_end_clean();
return $template;
}
$tpl is set to the page.tpl file.
I tried $vars['nav'] = file_get_contents('nav.tpl'); above the theme function just to give it some data to work with. If I remove the $tpl variable and the require() function, I see the UL nav list but when I add back the page.tpl file back in I get this error:
Warning: extract() expects parameter 1 to be array, null given
This works(shows UL nav list):
$vars['nav'] = file_get_contents('nav.tpl');
function theme($vars = array()) {
extract($vars);
ob_start();
$template = ob_get_contents();
ob_end_clean();
return $template;
}
This doesn't:
$vars['nav'] = file_get_contents('nav.html');
theme('page.html', $vars) //page.html is set to correct directory.
function theme($tpl, $vars = array()) {
extract($vars);
ob_start();
require($tpl);
$template = ob_get_contents();
ob_end_clean();
return $template;
}
Any help on getting this to work correctly would be appreciated.
UPDATE: This is my current index.php file:
<?php
define('ROOT_DIR', getcwd());
require_once(ROOT_DIR . '/core/includes/boot.inc');
boot_start(BOOT_FULL);
// Based off of Drupal's drupal_bootstrap(). Set's ini_set's, database
//and starts sessions. This works just fine and I haven't coded any
//theme/template code into it. The only thing boot_start() does for theme is
//load the .inc file that has the theme() function. The .inc gets included
// otherwise I would have gotten a "call to unknown function" error.
$vars['nav'] = file_get_contents(ROOT_DIR . '/core/templates/nav.tpl');
theme('./core/templates/page.tpl', $vars);
I don't quite understand why I am getting the error from extract(). When I add $vars['nav'] without including 'include($tpl)', extract works just fine. It isn't until I try to include the page.tpl file.
The page.tpl file should be loaded on every page request that outputs anything. So I think I only need theme($vars) instead of theme($tpl, $vars = array())
Is there a way I can include page.tpl without passing it to theme(), while passing $vars so that $vars['nav'] overrides the <?php print $nav; ?> tag in page.tpl? Thanks.
SOLVED: Man, I can't believe it took me this long to fix this. Since theme() returned and not echo'ed the data, I had to assign $theme = theme('page.tpl', $vars); then echo $theme; Besides a few PHP notices, it works.
I personally just like to make a file for the individual parts. and then include them.
<?php include('relative/link.php'); ?>
if you want to edit the content in a section I would use variables.
header.php
echo $foo;
index.php
$foo='bar';
include('header.php');
when we include a file it grabs the contents and injects it in the current file and then will process it.
This is more of a style question. I have a template file header.php in which I define a PrintHeader() function.
Callers of this function can specify, via global variables, the title of the page and any Javascript scripts to include when printing the header (because surely not every page will have the same title or want to include the same scripts). I chose to use global variables rather than function arguments because the latter would require the interface to change when adding new arguments.
Is this considered "good" style, and is there a "better" way to do what I'm trying to do?
header.php (simplified)
<?php
function PrintHeader()
{
global $pageTitle, $scripts; // Set by the caller of this function
echo <<<HEADER
<html>
<head>
<title>$pageTitle</title>
HEADER;
if( !empty($scripts) )
{
foreach($scripts as $script)
{
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
?>
index.php (simplified)
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
PrintHeader();
// Print the rest of the page
?>
is there a "better" way to do what I'm trying to do?
sure.
I see no point in defining and calling a function at all. as well as in using heredoc.
header.php (dramatically simplified):
<html>
<head>
<title><?=$pageTitle?></title>
<? if( !empty($scripts) ): ?>
<? foreach($scripts as $script): ?>
<script type="text/javascript" src="<?=$script?>.js"></script>
<? endforeach ?>
<? endif ?>
</head>
index.php:
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
?>
but still it's not the best way, as it seems you're not using a template where it most valuable - to output page contents itself.
So, I'd make it in three parts:
links.php (simplified):
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA = getdata("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
notice native HTML syntax, which is highlighted, readable and centralized in one place instead of being split between numerous functions and files
The point is in having separate template for the every PHP page as well as main site template for them all. With such setup you'll get a lot of advantages such as custom error pages, multiple representations of the same data (say, HTML, JSON or XML) by switching only templates without changing the code and many more
The use of global variables is certainly not advisable, and I question the necessity of using heredoc as you have - not that there is anything inherently wrong with heredoc, just that you seem to have rather arbitrarily utilized it in this sample template.
It is not elegant to use a return-value of a function as the output of each template - this defeats one of the purposes of templates which is re-usability.
Take a look at smarty, if not to directly use it (after all, why re-invent the wheel), at least to get an idea of how a rendering class is used to shuttle in the variables that a template needs without resorting to messy globals.
Here's a very quick overview of a way to do templating:
You have a template class that you can assign data to and then render a template.
Template.php:
class Template
{
protected $data = array();
public function assign($key, $value)
{
$this->data[$key] = $value;
}
public function render($file)
{
extract($this->data);
require $file;
}
}
You then have your template, header.php:
<html>
<head>
<title><?php echo $pageTitle; ?></title>
....
In index.php, you then use the template class to assign data and render your template.
$tpl = new Template;
$tpl->assign('pageTitle', 'My page title!');
$tpl->render('header.php');
This is just a simple example to demonstrate the idea, and could give you a good starting point.
While "better" may be in the eye of the beholder, I would suggest having some sort of functions that set the page bits rather than exposing raw variables. For instance, instead of doing $pageTitle = 'Welcome'; you could have set_page_title('Welcome');.
For JavaScript you could have a function that adds to the current script set -- rather than possibly replacing it all -- such as add_javascript($code);. This will allow a developer to set all of these without having to keep track of what the variable name was, and also without needing to global it as well if they want to set it from within a function.
This is an alternative using output buffering.
p/example_page/index.php is one of your pages:
<?php
ob_start() ?>
<h1>Example</h1>
<p>This is the page content</p>
<?php $main = ob_get_clean();
ob_start() ?>
<script defer src="js/example_page/example.js"></script>
<?php $script = ob_get_clean();
$title = 'Example page';
include 'templates/base.php';
templates/base.php is your reusable layout:
<!doctype html>
<html>
<head>
<script defer src="js/main.js"></script>
<?php echo $script ?>
<title><?php echo $title ?> - Example website</title>
</head>
<body>
<header>
<nav aria-label="Main menu"></nav>
</header>
<main><?php
echo $main;
?></main>
<footer>Example footer</footer>
</body>
</html>
Global variables are generally considered bad, and should be avoided if possible.
Rather than listing every variable in the interface, as you said things could change, pass a single array to the PrintHeader() functions:
<?php
function PrintHeader($opts=array()) {
if(!isset($opts['title'])) $opts['title'] = 'Default Title';
echo <<<HEADER
<html>
<head>
<title>$opts['title']</title>
HEADER;
if(!empty($opts['scripts'])) {
foreach($opts['scripts'] as $script) {
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
$opts = array('title'=>'Welcome',
'scripts'=>array('script1', 'script2'));
require('header.php');
PrintHeader($opts);
?>
This way, you can add new capabilities in the function without breaking old code.