So, I'm making a site about WWI as a school assignment, and I want this to appear in every document:
<!DOCTYPE html>
<html>
<head>
<title>1914</title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<header>
<img src="images/banner.png" alt="World War I" style="border: none"/>
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
<footer style="font-weight: bold; letter-spacing: .1em">
Citations •
About
</footer>
</div>
</body>
</html>
I think it's kind of stupid to copy-paste all this into each document, and painstakingly go in and change each page separately if I just want to change one word or tag. Is there a way I can put this in template.htm (or something similar) and have php or javascript code take this and insert everything from the requested file inside of the <article> tag? I don't know a lot of php, so this is probably a piece of cake for you gurus, but I would appreciate the help.
Using php includes:
Save this as top.php
<html>
<head>
<title><?php echo $title; ?></title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<header>
<img src="images/banner.png" alt="World War I" style="border: none"/>
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
Save this as bottom.php
<aside>
</aside>
</section>
<footer style="font-weight: bold; letter-spacing: .1em">
Citations •
About
</footer>
</div>
</body>
</html>
Then your individual pages would be like this:
<?php $title = '1914'; include("top.php");?>
//This would be where you would make the changes that need to be made on each page.
<article>
<br style="clear: both" />
</article>
<?php include("bottom.php");?>
You could consider one of these popular template engines :
Smarty (becoming outdated)
Latte (used mostly by the Nette community)
Twig (used mostly by the Symfony community)
Mustache (official implementations of this templating engine exist in more than two dozen proramming/scripting languages)
I tend to favor Mustache, mostly because it has an official JS version, an official Ruby version, an official Java version, etc. It allows you to use the same templates frontend and backend, which is very useful for widgets that are first rendered in background and rerendered in foreground at updates.
Put the content in a file abc.php
and then add this to each page you want the desired content in :
<?php
include("abc.php");
?>
So if your code is :
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
And you want the part inside <nav> to be repeated in each page, you can put the content between <nav> and </nav> (including the tags) inside abc.php and include abc.php in your file like this :
<?php
include("abc.php");
?>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
Create the template file as a single file, exactly you have it already, but printing PHP variables in the places where you want content.
eg:
....
<article>
<?php print $mainContent; ?>
</article>
....
Then write a PHP function as follows:
<?php
function insertContentIntoTemplate($mainContent) {
require_once('/path/to/template.php');
}
?>
Now you can load your page content into the template simply by calling the function and passing the content into it for each page.
So, for example, 1914.php could look like this:
<?php
require_once('/path/to/insertFunction.php');
//the text could be loaded from a DB, or from another file, or just as a plain string like this:
$text = "The year was 1914, and the war was just starting.";
insertContentIntoTemplate($text);
?>
Congratulations. You now have a working (albeit very simple) template system. Add more variables / placeholders to your template as required.
Related
I have got header.html, nav.html and footer.html. I need to load them on a index.php.
is it right? Because this works but I don't know if this is the best way to do.
index.php
<html>
<body>
<header><?php require('../layout/header.html')?></header>
<nav><?php require('../layout/nav.html')?></nav>
<div id="content">Hello World</div>
<footer><?php require('../layout/footer.html')?></footer>
</body>
</html>
header.php
<html>
<body>
<img src="../images/header.png">
</body>
</html>
You cannot have multiple <html> tags in the resulting HTML, i.e., the following code is not valid:
<html>
<html>
<header></header>
</html>
</html>
When you split your HTML into different files in order to reuse code, you have to consider that they will be, probably, injected in a pre-existent HTML code. Therefore, I would suggest the following code:
main.html
<html>
<body>
<!-- Header -->
<?php require('../layout/header.html')?>
<!-- Nav -->
<?php require('../layout/nav.html')?>
<!-- Content -->
<div id="content">Hello World</div>
<!-- Footer -->
<?php require('../layout/footer.html')?>
</body>
</html>
layout/header.html
<header>
<!-- Your header HTML -->
</header>
layout/nav.html
<nav>
<!-- Your Nav HTML -->
</nav>
layout/footer.hml
<footer>
<!-- Your footer HTML -->
</footer>
I am working on an established website which has many problems in it. I am trying to incorporate a new navbar that will be coded in a 'header.php' file. I want to call it in the index.php and other pages using <?php include('header.php') ?> but there are differences in the pages and it needs the header.php to be dynamic. I want the header.php to have some slight changes when called by a specific page. How can I dynamically change the header.php file depending on what page called it?
This is my code:
HEADER.PHP
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/angel-header.css">
<!-- RENAME THIS CSS FILE APPROPRIATELY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body class="m-price_update price_starway vb lang-en webp">
<header class="angelmod-site-header">
<div class="angelmod-wrapper">
<a href="#">
<img src="img/logo_sb.png" alt="Small Builders">
</a>
<nav class="angelmod-site-nav">
<ul class="angelmod-nav-list">
<li>Home
</li>
<li>Products
</li>
<li>Signup
</li>
<li>Login
</li>
</ul>
</nav>
<div class="angel-mod-navbtn">
<div class="angel-mod-navbtn-bars"></div>
<div class="angel-mod-navbtn-bars"></div>
<div class="angel-mod-navbtn-bars"></div>
</div>
</div>
<script src="js/angel-header.js"></script>
<!-- RENAME THIS JS FILE APPROPRIATELY -->
</header>
I have a products.php file that needs to change the body tag to: <body class="m-price_update price_starway vb lang-en webp"> right now the header.php only have <body>.
Please don't ask why the body differs from page to page, it's the previous dev's work and I am tasked to not change those.
Any variables defined in the file doing the including will be available in the included file. Just define a variable in the including file that identifies what needs to be done in the included file.
// products.php
$include_option = 'products';
include('header.php');
Then in the included file, refer to that variable at the appropriate place to conditionally do whatever needs to be done:
// header.php
...
<?php if ($include_option == 'products') { ?>
<body class="m-price_update price_starway vb lang-en webp">
<?php } else { ?>
<body class="something else">
<?php } ?>
...
I am new to PHP frameworks and yii and I am trying to understand how views/layouts work. This is how I currently understand how to layout a page template:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="page_wrp">
<?php include 'includes/top_right_nav.php' ?>
<div id="content_wrp">
<div id="content">
</div>
</div><!--#content_wrp-->
<?php include 'includes/main_nav.php' ?>
</div><!--#page_wrp-->
</body>
I understand that basic yii way is more like this:
<?php /* #var $this Controller */ ?>
<!DOCTYPE>
<html>
<head>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div class="container" id="page">
<div id="header">
<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div id="mainmenu">
<!--
DON'T WANT TO USE ZII.WIDGETS FOR MENU
WANT TO KNOW BEST WAY TO INCLUDE MY ONW NAVIAGTION MENU-
->
<?php $this->widget('zii.widgets.CMenu',array('...')); ?>
</div><!-- mainmenu -->
<?php echo $content; ?>
<div id="footer"></div><!-- footer -->
What I don't understand is what is the best practice/analogous way to include my own navigation bar in the context of yii/MVC. Can I still use includes as above or do I have to use zii.widgets? If it's ok to use includes where do I put the files?
Any help would be much appreciated.
You don't have to use Yii widgets however it's recommended to use them, they are quite flexible.
Make a view file for your menu markup in the layouts folder, something like _myMenu.php
_menu.php
<ul>
<li>menu item 1</li>
<li>menu item 2</li>
</ul>
then in your layout use renderPartial() to render your _menu.php partial view inside your layout.
main.php
<div id="mainmenu">
<?php $this->renderPartial("//layouts/_menu"); ?>
</div>
This is a really simple solution, if you want to make the menu more dynamic you can add a method to your controller to handle this.
I cannot seem to get this to work. I have a small JS file that switches banners depending on the time of day, but it seems that doing an external reference in my PHP file does not work. It works fine in an HTML page.
This is the code in the JavaScript file.
function getStylesheet() {
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 19) {
document.write("<img src='images/banner_day.jpg'>");
} else {
document.write("<img src='images/banner_night.jpg'>");
}
}
getStylesheet();
And here is the reference code I used to call the JavaScript file. Its in a PHP file.
<script src="http://beta.website.com/wp-content/themes/theme/scripts/banner.js"></script>
Everything on the PHP page shows up in the browser, except for the banner that I tried to call with the script.
Here is the entire PHP file code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="main">
<div class="container">
<div id="header">
<div id="logo">
<img src="http://beta.dfdfdf.com/wp-content/themes/asdafd/images/logo.png" />
</div>
<div id="shadow2"></div>
<div id="shadow1"></div>
<ul id="menu">
<li>df</li>
<li>df</li>
<li>fd df df</li>
<li>The asfdssd asdfds</li>
<li>sf</li>
<li>df</li>
<li>dfd</li>
</ul>
<div id="slogan"><big>"fasfdsads2005."</big></div>
<div id="loginDiv">Login Panel Here</div>
</div>
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script></div>
<div class="sidebar">
Sidebar Content<br />
<br /><br />
blah
blah
blah
</div>
<div class="content">
Main Content
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<div id="footer">
<div class="container">
<div class="footer_column long">
<h3>Cadsfadsfafdfsd.com All Rights Reserved</h3>
<p>dsafasdfdffadffadsdafsdfsadafsdfsadfas</p>
</div>
<div class="footer_column2">
<h3>More Links</h3>
<ul>
<li><a href="http://aadfsdfsdfa.
com">asfsdfa</a></li>
<li><a href="http://ItsNotch.
com">ItsNotch</a></li>
<li><a href="http://adfasfsfaf.
com">adsfasf</a></li>
<li><a href="http://twitter.
com/safs">Twitter</a></li>
<li><a href="https://www.facebook.com/group.php?gid=10215yy20340498">Facebook Fan Page
</a></li>
</ul>
</div>
<div class="footer_column2">
<h3>RSS</h3>
<ul>
<li>RSS Feed</li>
<li>What is RSS?</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Try changing your Javascript to this:
window.onload = function () {
// Uncomment this line to make sure the script is loading/running, then delete it
// alert('Hello, your Javascript is running');
// Declare variables
var currentTime, bannerDiv, newImg;
// Get currentTime
currentTime = new Date().getHours();
// Get 'banner' div
bannerDiv = document.getElementById('banner');
// Get create a new <img>
newImg = document.createElement('img');
// Assign a src="" attribute depending on the time
newImg.src = (currentTime > 7 && currentTime < 19) ? 'images/banner_day.jpg' : 'images/banner_night.jpg';
// add the new image to the document
bannerDiv.appendChild(newImg);
};
And put it in the <head> of the document, so change
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<!-- ....... -->
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</div>
<!-- ....... -->
...to:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</head>
<body>
<!-- ....... -->
<div id="banner"></div>
<!-- ....... -->
If it still doesn't work, one of two things is happening:
Your javascript file is not actually at http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js so the script cannot be loaded/run. Uncomment the first line to confirm that the script is running.
Your banner images cannot be found at images/banner_night.jpg - make sure your relative paths are correct.
Have you made sure that you've actually got the <script></script> in your head? I certainly can't see it there (unless it is in <?php wp_head();>?).
Having attempted to navigate to http://beta.website.com/wp-content/themes/theme/scripts/banner.js it returns a 404, you'll need to fix this issue first.
Remember that javascript is client side, and all you want to do with php is spit out the tags somewhere for the browser to deal with.
It might be path problem.
What is you images (full) path?
What is you page (full) path?
As it is now it looks for images directory beneath your current page. Is this correct?
At the moment, I have a base HTML template file. When ever I want to make a new page, I copy the template and place some require_once statements in between specific tags. I was wondering if there's a better way that would make it unnecessary to copy the template each time. Here's a typical example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title>Order a Ticket for the ball</title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text">introduction</div>
<div id="header_cell2">the process</div>
<div id="header_cell3">start</div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($config["directories"]["views"]."/index.form.view.php"));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($config["directories"]["views"]."/index.data.view.php"));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($config["directories"]["views"]."/index.side.view.php"));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
EDIT: I have taken note of your suggestions to use GET. The new idea is to have each request url formed as index.php?page=page_name. This request would then be dealt with by a main controller which then sets the variables of the template based on the value of $_GET['page']. For this, the template will now be:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title><?php h($title) ?></title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text"><?php h($header_1) ?></div>
<div id="header_cell2"><?php h($header_2) ?></div>
<div id="header_cell3"><?php h($header_3) ?></div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($view_1));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($view_2));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($view_3));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
Note: h() is a function that first of all removes all undesired entity tags before echoing a string.
On a related note, at the top of each page I have some controller files which are included with require_once. I was wondering if it would be possible to implement a function that simply includes files based on a specific input string (name of the functionality/page) i.e "index" in this way:
function include_controller($page){
switch($page){
case "index":
require_once(realpath($config["directories"]["controllers"]."/index_.php"));
break;
case "checkout":
require_once(realpath($config["directories"]["controllers"]."/checkout_.php"));
break;
default:
break;
}
}
Instead of hard coding the includes into each file, you could have a controller file in which you pass the page to be displayed through a $_GET variable. The controller then handles the logic and includes the appropriate page or pages. This is the way a lot of MVC frameworks do it.
Edit: To answer your second question, instead of using a switch, you could just check to make sure the file exists. If it does, include that file, otherwise output an error ("Page doesn't exists" or something similar).
function include_controller($page){
if (file_exists($config["directories"]["controllers"]."/$page_.php")) {
// page exists, include it
require_once($config["directories"]["controllers"]."/$page_.php"));
} else {
// page not found
}
}
Obviously you should probably make the function a little more robust and probably limit the files that will be included to a certain directory or something. Also make sure you properly filter the $page variable so users aren't able to access any file.
Keep this one file as your template file. Then for all the functionality in your site always hit this file. Lets sat this file is index.php. So all functionality requests go to index.php. But with different parameters so for functionality A.
index.php?function=a
For functionality b
index.php?function=b
you can add more parameters also.
Now on the basis of a,b and the set of parameters see what files you want to include as require once.
Like the others already said, it would be better to use some kind of MVC framework. Or at least use a template engine (e.g. Smarty). Your example is ok though, for the 90ies :)
You can get by with one template if you choose a different way of specifying what page is being requested, such as using a GET variable. You can load the pages in a database and specify each of the included pieces, then have one php 'template engine' that loads the requested page from the database and outputs the template with the right includes.
If your server supports it, you can references to things you want to include on all pages in .htaccess:
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"
(Found this on codingforums.com)