Chris
Chris

Reputation: 3698

How to get header HTML code included in all .html files

I have a simple website, in which I've written the code that's about the header.
This is included in the index.html. Now that I want to add another .html file, how can I have the header related code, included into all the HTML files?

A simple copy paste will surely do the job, but is it a correct solution?

Developing in Ubuntu, using Sublime Text with H5BP and Compass.

Upvotes: 0

Views: 3668

Answers (2)

StackSlave
StackSlave

Reputation: 10617

I would use PHP:

// header.php
<?php
date_default_timezone_set('America/Los_Angeles');
function https(){
  $sv = $_SERVER;
  if(!isset($sv['HTTPS'])){
    header("LOCATION:https://{$sv['SERVER_NAME']}{$sv['PHP_SELF']}"); die();
  }
}
function http(){
  $sv = $_SERVER;
  if(isset($sv['HTTPS'])){
    unset($_SERVER['HTTPS']);
    header("LOCATION:http://{$sv['SERVER_NAME']}{$sv['PHP_SELF']}"); die();
  }
}
$doc = "<!DOCTYPE html>
  <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
    <head>
      <meta http-equiv='content-type' content='text/html;charset=utf-8' />
      <meta name='keywords' content='put your site keywords here' />";
$main = " </head>
<body class='njs'>
  <div id='head'>
    <div id='menu'>
      <nav class='tabs'>
        <a href='index.php' id='hm'>Home</a>
        <a href='page2.php' id='p2'>Page 2</a>
        <a href='page3.php' id='p3'>Page 3</a>
        <a href='page4.php' id='p4'>Page 4</a>
        <a href='page5.php' id='p5'>Page 5</a>
        <a href='page6.php' id='p6'>Page 6</a>
        <a href='page7.php' id='p7'>Page 7</a>
      </nav>
    </div>
    <div id='content'>";
 ?>

Now, put header.php in a restricted folder, in the same location as index.html for added security, then change index.html to index.php. Now index.php:

// index.php
<?php
include_once 'restricted/header.php'; http(); // could be https() for SSL
echo "$doc
    <title>Whatever - Home</title>
    <meta name='description' content='Whatever - Home' />
    <style type='text/css'>
      @import 'common.css'; @import 'index.css';
    </style>
$main";
?>
  <!-- put your content here -->
  <!-- don't forget to close the `id='content'` div -->
  </div>
</body>
</html>

Upvotes: 1

user3000116
user3000116

Reputation: 75

You could also ajax to load in the header into the separate pages, if you didn't want to deal with php. Just have the header html in a separate file and do an ajax call on dom load and then apply the response to the container of the header in the page you are using.

Upvotes: 0

Related Questions