Common Header / Footer with static HTML - html

Is there a decent way with static HTML/XHTML to create common header/footer files to be displayed on each page of a site? I know you can obviously do this with PHP or server side directives, but is there any way of doing this with absolutely no dependencies on the server stitching everything together for you?
Edit: All very good answers and was what I expected. HTML is static, period. No real way to change that without something running server side or client side. I've found that Server Side Includes seem to be my best option as they are very simple and don't require scripting.

There are three ways to do what you want
Server Script
This includes something like php, asp, jsp.... But you said no to that
Server Side Includes
Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.
Client Side Include
This solutions has you calling back to the server after page has already been loaded on the client.

JQuery load() function can use for including common header and footer. Code should be like
<script>
$("#header").load("header.html");
$("#footer").load("footer.html");
</script>
You can find demo here

Since HTML does not have an "include" directive, I can think only of three workarounds
Frames
Javascript
CSS
A little comment on each of the methods.
Frames can be either standard frames or iFrames. Either way, you will have to specify a fixed height for them, so this might not be the solution you are looking for.
Javascript is a pretty broad subject and there probably exist many ways how one might use it to achieve the desired effect. Off the top of my head however I can think of two ways:
Full-blown AJAX request, which requests the header/footer and then places them in the right place of the page;
<script type="text/javascript" src="header.js"> which has something like this in it: document.write('My header goes here');
Doing it via CSS would be really an abuse. CSS has the content property which allows you to insert some HTML content, although it's not really intended to be used like this. Also I'm not sure about browser support for this construct.

The simplest way to do that is using plain HTML.
You can use one of these ways:
<embed type="text/html" src="header.html">
or:
<object name="foo" type="text/html" data="header.html"></object>

You can do it with javascript, and I don't think it needs to be that fancy.
If you have a header.js file and a footer.js.
Then the contents of header.js could be something like
document.write("<div class='header'>header content</div> etc...")
Remember to escape any nested quote characters in the string you are writing.
You could then call that from your static templates with
<script type="text/javascript" src="header.js"></script>
and similarly for the footer.js.
Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.

you can do this easily using jquery. no need of php for such a simple task.
just include this once in your webpage.
$(function(){
$("[data-load]").each(function(){
$(this).load($(this).data("load"), function(){
});
});
})
now use data-load on any element to call its contents from external html file
you just have to add line to your html code where you want the content to be placed.
example
<nav data-load="sidepanel.html"></nav>
<nav data-load="footer.html"></nav>

The best solution is using a static site generator which has templating/includes support. I use Hammer for Mac, it is great. There's also Guard, a ruby gem that monitors file changes, compile sass, concatenate any files and probably does includes.

The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.

HTML frames, but it is not an ideal solution. You would essentially be accessing 3 separate HTML pages at once.
Your other option is to use AJAX I think.

You could use a task runner such as gulp or grunt.
There is an NPM gulp package that does file including on the fly and compiles the result into an output HTML file. You can even pass values through to your partials.
https://www.npmjs.com/package/gulp-file-include
<!DOCTYPE html>
<html>
<body>
##include('./header.html')
##include('./main.html')
</body>
</html>
an example of a gulp task:
var fileinclude = require('gulp-file-include'),
gulp = require('gulp');
gulp.task('html', function() {
return gulp.src(['./src/html/views/*.html'])
.pipe(fileInclude({
prefix: '##',
basepath: 'src/html'
}))
.pipe(gulp.dest('./build'));
});

You can try loading them via the client-side, like this:
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
</head>
<body>
<div id="headerID"> <!-- your header --> </div>
<div id="pageID"> <!-- your header --> </div>
<div id="footerID"> <!-- your header --> </div>
<script>
$("#headerID").load("header.html");
$("#pageID").load("page.html");
$("#footerID").load("footer.html");
</script>
</body>
</html>
NOTE: the content will load from top to bottom and replace the content of the container you load it into.

No. Static HTML files don't change. You could potentially do this with some fancy Javascript AJAXy solution but that would be bad.

Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed or m4 and sending the result over to your server, no, you'd need at least SSI.

The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.

Related

Am I able to link another HTML file in another html?

I currently have a pageMaster file which is an HTML file. I am trying to keep it clean. I am linking my javascript files to this pageMaster for example <script type="text/javascript" src="/resources/js/mainpage.js"></script>. I would like to link an HTML page this pageMaster to avoid having a clutter. Is this possible?
This is what i'm attempting <script="text/javascript" src="/resources/state-icons.html"></script> but it is not receiving back the icons I am expecting
Since html isn't a script, you can't load it as an script (using <script type="text/javascript"> does't make a lot of sense, does it?).
You have to use a preprocessing language, like php, which will build the output on the server. Using php, you could have something like:
<p>Some html
<?=file_get_contents(__DIR__.'/resources/state-icons.html')?>
...more html...</p>
Or:
<?php
include(__DIR__.'/header.php');
?>
...html...
If you can't or don't want to use a server-side language, you can do this with javascript. You can download the contents of the other page and insert them wherever you want (I will use jQuery just because it's easy to write, you don't actually need it):
HTML:
<span class="some-placeholder-for-state-icons"></span>
JS:
$(function() {
$.get('/resources/state-icons.html',function(html) {
$(".some-placeholder-for-state-icons").html(html);
});
});
Of course, this way will be slower and produce more requests per page view. Which one is better depends on what you want to achieve.
You can't do something like this with html. This is possible only for javascript file or stylesheets (css)

HTML repetitive blocks

I wish to do the following things:
Insert external html blocks into new html pages
Use the same html header from one html file for a number of pages, without recreating the header again for all the pages
Please help!
You can use HTML Imports which is part of Web Components:
<head>
<link rel="import" href="/path/to/your/file.html">
</head>
If your page does not have to be pure HTML, you should consider using PHP or a similar server-side language.
There are plenty of options, depends on you:
1) use iframes (a lot problems with responsibility) http://www.w3schools.com/tags/tag_iframe.asp
2) ajax call in javascript, load external resource and then print it in placeholder tag (example is with jquery) http://www.w3schools.com/jquery/jquery_ajax_load.asp
3) use some server language/preprocessor (php, ruby, nodejs), depend if you can (need to by installed on server)
4) also there are static page generator, you add marks in your html, and they will compile html with marks to full static html http://hyde.github.io/ for example.
What you are talking about appears to be a process called templating. There are many ways to do this, including writing Javascript to insert pre-written HTML templates into the DOM (the webpage). You might also consider using a pre-written templating library such as http://handlebarsjs.com/ or another library which contains templating functions like http://underscorejs.org/. A simple MVC guide like:
http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html
May be helpful too, to get you started.
In a more practical sense, here's one possible solution:
To begin I would recommend putting the 'blocks' you want to insert in a separate folder. In the website I run, for example, I place them in the \templates folder (or subfolders) but you can more or less call it what you want as long as it makes sense to you. For our purposes let's say we've created block.html and put it in our \templates subfolder...
Now, within each template you will have whatever you want to load in; something like this:
<h2>Title of section</h2>
<p>My text.</p>
Or whatever you'd like. Then, you'll probably want to add an element to your main page which calls some Javascript, which loads your HTML template in when a particular condition occurs. For example, if you wanted to load in our block.html file you might write something like this:
<div id="calling-block" onclick="menuClicked('locationToInsert', 'block')"></div>
Which would call a Javascript function called 'menuClicked()' when we click the div with the id 'calling-block'.
Within the function we would write something like this:
<script>
function menuClicked(insertEl, UrlString, onTemplateLoaded) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(insertEl).innerHTML = xhttp.responseText;
if (onTemplateLoaded) onTemplateLoaded();
};
};
console.log(UrlString);
xhttp.open("GET", UrlString, true);
xhttp.send();
};
</script>
This is a very simple way of doing things and I'm sure people will tell you there are problems with it, so I would definitely recommend doing your own reading as well, but I hope this covers the very basics.
You need tu use a server side functionality like php, aspx ...

Call one html file from another

I want to call one html page fron another in a div.
I tried using
<include file="NavigationTree.html" />
and
<? include("/starfix/pages/NavigationTree.html"); ?>
But it doesn't work.
Am I doing something wrong or do i need to do it some other way?
You may want to consider using Server Side Includes (SSI).
You would place your HTML snippet into a separate file, such as NavigationTree.html, and then you would simply reference it in your web pages by using:
<!--#include virtual="NavigationTree.html" -->
SSI is supported by all the popular web servers, including Apache, IIS and lighttpd.
Note that if you are using a shared host, you may have to use the .shtml, .stm, or .shtm extension for SSI to work. If you have root access to your web server, it can be easily configured to enable SSI for any extension, including html.
This is not possible in pure HTML.
The former is a notation I have never seen before, it is not HTML, maybe it works in some specific server-side templating language.
The latter is PHP. It should work but you need to bear in mind include() works with absolute paths inside the server's file system.
You should specify a relative path:
<? include("./NavigationTree.html"); // will work if it's in the same directory ?>
or an absolute one that will probably look something like this:
<? include("/path/to/your/www/dir/starfix/pages/NavigationTree.html"); ?>
(ask your admin for the absolute path to your web root)
You can maybe also do a HTTP include:
but that's unwise because it tends to be slow, and generates a second request on each page request.
You can also use SSI as outlined by #Daniel.
You could also use jQuery for this,
e.g.
<div id="yourDiv" />
<script>
$("#yourDiv").load("NameOfYourPageToReadFrom.ext #NameOfDivToReadFrom");
</script>
This puts the contents of the 'NameOfDivToReadFrom' DIV in the called file ''NameOfYourPageToReadFrom' into the loaded DIV ('yourDiv') in your current file.
Remember to add the definition to the header part of your html.
e.g.
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
You can use an iframe for that, e.g.:
<iframe width="500" height="300" frameborder="no" scrolling="no" marginheight="0" marginwidth="0"
src="http://www.example.com/page.html"></iframe>

How To Make Reuseable HTML Navigation Menus?

I'm sure this topic comes up all the time,
But I can't seem to fine a concise answer.
I've got a vertical menu bar that I want to reuse in webpages (>20).
The Menu Bar is coded in HTML and uses uses: UL, LI, A, <Div> tags, and CSS. We need this:
Reusable
Maintainable
Scalable
So we don't have to modify all pages every time we add a page.
We'd rather avoid a coding approach if possible. We could live with just one master file that we edit as needed. Since we're using CSS and <div>s, I don't think frames scale for us. What can we do?
Server side includes are the way to go if you don't want to use a programming language.
They take this form:
<!--#include virtual="menu.html" -->
and will be inserted in the page wherever you put that tag in your HTML. It requires server side parsing, so your web server must have server side includes enabled. You can try it out, and if it doesn't work, contact your server host to see if you can get them enabled. If it's Apache, there's a method of enabling them via .htaccess files as well.
In order to do this, you'll have to use some server side technology. For instance you could...
include them in php
put them in the master page in .net
put this in a partial or a layout page in rails
Some reading:
http://us.php.net/manual/en/function.include.php
http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
Another solution would be to create all this using Javascript, but please don't do it like that :)
html:
<script type="text/javascript" src="hack.js"></script>
<div id="mymenu">
</div>
hack.js:
function createMenu(){
$("#mymenu").html("all the html of your menu");
}
Without any server side script or Javascript you can use object or iframe tags.
http://www.w3schools.com/tags/tag_object.asp
http://www.w3schools.com/tags/tag_iframe.asp
The only thing to care is to indicate target="parent" in links.
Hope it helps
Using a w3 script..
index.html
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="header.html"></div>
<div w3-include-html="nav.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
header.html
<h1>Title</h1>
nav.html
<h2>Your nav</h2>
See also: http://www.w3schools.com/howto/howto_html_include.asp
And don't forget to test this code on your localhost.
I've done this two separate ways - one using server side (PHP) and one using Javascript includes (for demos that need to be able to run without any internet connection or server capabilities).
For PHP includes your pages will have to end with .php rather than .htm or .html, and these are very ideal to replace your header, footer, navigation, etc. Anything that is repeated on multiple pages.
Basically you would create your normal code then copy and paste the code you want to break out - in this example, your navigation - and save it in another file called (for example) inc_navigation.htm (this page can be called .htm).
Then in your actual pages you'd use the following code:
<?php include('inc_navigation.htm') ?>
That would insert your navigation at that point, if you had a change to make you'd make it to the .htm file and it would propagate to any page with that included.
For javascript includes you will have to include the following line at the top of every document where you want to include your navigation:
<script type="text/javascript" src="includes.js"></script>
Then you'll create a document called includes.js.
At the top of this document you'll declare your navigation variable:
var navigation = new Array(); // This is for the navigation.
Then a little ways down in that same document you need to actually outline your navigation code (the line numbers in the square brackets are crucial - keep them in order and start with 0 - you cannot have line breaks in this code so every line of code has to be a new line):
// ==================== Navigation ==================== //
navigation[0] = '<div id="tab_navigation">';
navigation[1] = '<ul id="dropline">';
navigation[2] = '<li><b>Home</b></li>';
navigation[3] = '<li><b>About Us</b></li>';
navigation[4] = '</ul>';
navigation[5] = '</div><!-- Close TAB NAVIGATION -->';
Then a little ways after that you'll actually insert the javascript that will put that code into your page (it doesn't actually put it there but rather makes it accessible in the page without actually altering the code of the .htm page - so if you view source you'll see the reference to the code not the code itself).
function show(i)
{
for (x in i)
{
document.write(i[x]+'\n')
}
}
Finally - in your .htm document, say for your index.htm page, you'll replace your navigation code (that you put in the above block called navigation) with this:
<script type="text/javascript">show(navigation);</script>
Where that name after SHOW and in the parenthesis is the name of your variable (declared earlier).
I have sites showing both methods in use if you'd like to see them just send me a message.
I was facing the same thing. Then, I created a new file for storing the html of the navigation bar.
I created a file navbar.html which had all my navigation bar code.
Then, in your main html file where you want navigation bar, just include this file by using jquery.
$(document).ready(function() {
$('#navigation').load('navbar.html');
});
Then at the place where you want navigation bar, just add this line:
<div id="navigation"></div>
As a modern answer to a six year old question: Web Components are specifically reusable HTML components, and Polymer is possibly the most popular implementation of it at the moment. Currently virtually no browser has native support for Web Components, so at the very least a Javascript polyfill is required.
If you would use PHP, all you have to do is use the include command, no coding beyond this one command.
Also, check out server side includes
So far one of the best solutions I have found is to model the menus after the Son of Suckerfish XHTML/CSS solution that is pretty well documented on the internet now combined with some logic on the server to render the unordered list. By using unordered lists you have a couple different options on how to output the results, but as long as the menu has some basic hierarchy you can generate it. Then for the actual page all you need to do is include a reference to the menu generating function.
I was searching for a way to write a reusable navigation menu that toggled(show/hide) when clicking a button. I want to share a solution that worked for me in case anyone else is looking to do the same. This solution uses jQuery, html, and css.
Add this line of code to your head tag in your main index.html file:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Add div for your nav in body tag:
<div id="mySidenav" class="sidenav"></div>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#mySidenav").load("nav.html").toggle().width("400pt");
});
});
</script>
Create a html file that will be where your navigation menu resides. My file is called nav.html and inside the file the contents look like this:
have you found your one true musubi?`
item2
item3

How can I use templates to generate static web pages?

I want to add one HTML file into another.
For example: I have header.html and footer.html
Now I am trying to create aboutus.html where I want to add these two HTML files
there is no dynamic code in these file except JavaScript.
How can I do this without using any scripting language except JavaScript and CSS?
Server Side Includes (SSI) exist for this particular functionality. However, you need to have the server configured for such includes. Apache supports it. Not sure about other web servers.
or Server Side Includes (SSI), all embedding is done there on the server side...
In the case of web sites with no dynamic content but have common elements, I generate the final pages on my development machine using Perl's Template Toolkit and upload the resulting static HTML files to the server. Works beautifully.
For example:
header.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<title>[% title %]</title>
<link rel="stylesheet" href="/site.css" type="text/css">
<meta name="description" content="[% description %]">
<meta name="keywords" content="[% keywords.join(',') %]">
</head>
<body>
<div id="banner">
<p>Banner</p>
</div>
footer.html
<address>
Last update:
[%- USE date -%]
[%- date.format(date.now, '%Y-%m-%d %H:%M:%S') -%]
</address>
</body>
</html>
aboutus.html
[%- INCLUDE header.tt.html
title = 'About Us'
description = 'What we do, how we do it etc.'
keywords = 'rock, paper, scissors'
-%]
<h1>About us</h1>
<p>We are nice people.</p>
You can now use tpage or ttree to build your pages.
The only way to do this on the client side without javascript is to use frames or iframes. If you want to use javascript, you can use AJAX. Most javascript frameworks provide corresponding convenience methods (e.g. jQuery's load function).
Obviously there are many server side solutions, including the popular SSI extension for apache (see other posts).
I'm not entirely sure what it is you want but an entirely client side method of doing it would be to embed them with the <object> tag.
<html>
<head>
<title>About Us</title>
</head>
<body>
<object data="header.html"><!--Something to display if the object tag fails to work. Possibly an iFrame--></object>
<!--Content goes here...-->
<object data="footer.html"></object>
</body>
</html>
I do not think that this would work if either header.html or footer.html have javascript that accesses the parent document. Getting it to work the other way might be possible though.
Check out ppk's website (quirksmode.org), and go to the javascript archives,
(http://quirksmode.org/js/contents.html). He uses an ajax function he wrote called sendRequest (found at http://quirksmode.org/quirksmode.js). Since IE9+ plays nice with standards, I've simplified it some:
function sendRequest(url,callback,postData) {
var req = new XMLHttpRequest();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
Then use the sendRequest function by wrapping the setFooter, setHeader functions and any other content functions around it.
why not use php or any other side scripting language?
doing this with javascript will not all users allow to watch your page.
Whilst this can be done with JS in a number of ways (AJAX, iframe insertion) it would be a very bad idea not to do this within the mark-up directly or (much) better on the server side.
A page reliant on JS for it's composition will not be fully rendered on a significant proportion of user's browsers, and equally importantly will not be correctly interpreted by google et al, if they like it at all.
You can do it, but please, please, don't.
Obviously header.html and footer.html are not html files -- with full fledged headers etc. If you have just html snippets and you want to include them so you can create different pages - like aboutus.html, terms.html, you have a couple of options:
Use a framework like Rails - which allows you to use layouts and partials. [** heavy **]
Write a simple tool that will generate all the files by concat-ing the appropriate files.
I assume you are doing this to avoid duplicating header and footer content.
Another way would be using ajax to include the remote html files.
Framesets would be the way to do this without any script or serverside influences.
<frameset rows="100,*,100">
<frame name="header" src="header.html" />
<frame name="content" src="content.html" />
<frame name="footer" src="footer.html" />
</frameset>
HTML5 framesets:http://www.w3schools.com/tags/html5_frameset.asp
This is a very dated solution, most web hosts will support server side includes or you could use php to include your files
http://php.net/manual/en/function.include.php
Cheers