Table of Contents
Use PHP
Use Gulp
Use Grunt
Use Handlebars
Use Pug
Use Nunjucks
Use Ajax
Use iframes
Use Jekyll
Use Sergey
Use Apache SSI
Use CodeKit
Use Dreamweaver
Holy Crap
Home Web Front-end CSS Tutorial The Simplest Ways to Handle HTML Includes

The Simplest Ways to Handle HTML Includes

Apr 21, 2025 am 11:09 AM

The Simplest Ways to Handle HTML Includes

It’s extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that addresses it. I’m talking about straight up includes, like taking a chunk of HTML and plopping it right into another. For example the use case for much of the entire internet, an included header and footer for all pages:

...

   <include src="./header.html"></include>

   Content

   <include src="./footer.html"></include>

...
Copy after login

That’s not real, by the way. I just wish it was.

People have been looking to other languages to solve this problem for them forever. It’s HTML preprocessing, in a sense. Long before we were preprocessing our CSS, we were using tools to manipulate our HTML. And we still are, because the idea of includes is useful on pretty much every website in the world.

Use PHP

Can you use PHP instead?

...

   <?php include "./header.html" ?>

   Content

   <?php include "./footer.html" ?>

...
Copy after login

This will perform the include at the server level, making the request for it happen at the file system level on the server, so it should be far quicker than a client-side solution.

Use Gulp

What’s even faster than a server-side include? If the include is preprocessed before it’s even on the server. Gulp has a variety of processors that can do this. One is gulp-file-include.

That would look like this:

...

   @@include('./header.html')

   Content

   @@include('./footer.html')

...
Copy after login

And you’d process it like:

var fileinclude = require('gulp-file-include'),
  gulp = require('gulp');
 
gulp.task('fileinclude', function() {
  gulp.src(['index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./'));
});
Copy after login

Looks like this particular plugin has fancy features where you can pass in variables to the includes, making it possible to make little data-driven components.

Use Grunt

This is what the grunt-bake plugin does. You’d configure Grunt to process your HTML:

grunt.initConfig({
    bake: {
        your_target: {
            files: {
                "dist/index.html": "app/index.html",
            }
        }
    }
});
Copy after login

Then your HTML can use this special syntax for includes:

...

   <!--(bake header.html)-->

   Content

   <!--(bake footer.html)-->

...
Copy after login

Use Handlebars

Handlebars has partials.

You register them:

Handlebars.registerPartial('myPartial', '{{name}}')
Copy after login

Then use them:

{{> myPartial }}
Copy after login

There is also fancy features of this that allow for evaluation and passing data. You’ll still need a processor to run it, probably something like gulp-handlebars.

Speaking of templating languages which make use of curly braces… Mustache has them, too.

Use Pug

Pug is an HTML preprocessor that has a whole new syntax for HTML that is a bit more terse. It’s got includes though.

...
body
   include ./header.html"

   p Content

   include ./footer.html"

   ...
Copy after login

Then you run it with something like gulp-pug.

Use Nunjucks

I love me some Nunjucks! Nunjucks has includes. You’d do it like this:

...

   {% include "./header.html" %}

   Content

   {% include "./footer.html" %}

...
Copy after login

If you put that in a file called index.njk, you could process it with a simple Node script into index.html like this:

const nunjucks = require("nunjucks");
const fs = require("fs");

fs.writeFile("index.html", nunjucks.render("index.njk"), function(err, data) {
  if (err) console.log(err);
  console.log("Compiled the Nunjucks, captain.");
});
Copy after login

Or process it with something like gulp-nunjucks.

11ty has Nunjucks built-in, along with many of the other mentioned so far. Might be good for you if you’re actually building a little site.

Use Ajax

Say you had…

  
  <header></header>
  
  Content.
  
  <footer></footer>

Copy after login

You could fetch the contents for the header and footer from respective files and dump the contents in.

fetch("./header.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("header").innerHTML = data;
  });

fetch("./footer.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("footer").innerHTML = data;
  });
Copy after login

Speaking of JavaScript… If you’re building your site using a JavaScript framework of just about any kind, building through components is kind of the main deal there and breaking parts you want to include in other files should be no problem. Some kind of import Header from "./header.js"; and 

 is the territory you’d be in in React land.

Use iframes

You could do this:

  
  <iframe src="./header.html"></iframe>
  
  Content.
  
  <iframe src="./footer.html"></iframe>
  
Copy after login

But the content in those iframes does not share the same DOM, so it’s a bit weird, not to mention slow and awkward to style (since iframes don’t know the heights of their contents).

Scott Jehl documented a cool idea though: You can have the iframe inject the content of itself onto the parent page then remove itself.

  
  <iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
  
  Content.
  
  <iframe src="footer.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
  
Copy after login

Kolya Korruptis wrote in with this adaptation which will include more than the first child of the body in case your HTML file has that:

<iframe src="included.html" onload="this.insertAdjacentHTML('afterend', (this.contentDocument.body||this.contentDocument).innerHTML);this.remove()"></iframe>
Copy after login

Use Jekyll

Jekyllis a Ruby-based static site generator withincludes. You keep your includes in the/_includes/folder, then:

  {% include header.html %}
  
  Content.

  {% include footer.html %}
Copy after login

Jekyll is a big one, so I’m calling it out here, but there area ton of static site generatorsand I’d wager any of them can do includes.

Use Sergey

OK, I’ll call out one moreSSGbecause it’s new and super focused.Sergeyhas a web components style format:

  <sergey-import src="header"></sergey-import>

  Content.

  <sergey-import src="footer"></sergey-import>
Copy after login

You’d name the filesheader.htmlandfooter.htmland put them in/includes/and then it’ll make a build with the includes processed when you run the npm script it has you do.

Use Apache SSI

Apache, a super duper common web server, cando includes. You do it like this:

		
  <!--#include file="./header.html" -->
  
  Content
  
  <!--#include file="./footer.html" -->
  
Copy after login

But you need the right Apache configuration to allow stuff. I tried my best to get a working demo going but didn’t have much luck.

I tried using.htaccesswithin a folder on an Apache server and flipping on what I thought was the right stuff:

Options  Includes

AddType text/html .html
AddOutputFilter INCLUDES .html
Copy after login

I’m sure there is some way to get it working though, and if you do, it’s kinda neat that it needs zero other dependencies.

Use CodeKit

Mac only, but CodeKit hasa special language called Kitit processes where 90% of the point of it is HTML includes. It uses special HTML comments:

...

   <!-- @import "./header.html" -->

   Content

   <!-- @import "./footer.html" -->

...
Copy after login

Use Dreamweaver

Lol jk. But itreally is a thing.DWTs, baby.

Holy Crap

That’s a lot of ways, isn’t it?

Like I said at the top, it’s very surprising to me that HTML itself hasn’t addressed this directly. Not that I think it would be a great idea for performance to havestatements that trigger network requests all over our code, but it seems in-line with the platform. Using ES6 imports directly without bundling isn’t a great idea always either, but we have them.@importing CSS within CSS isn’t a great idea always, but we have it. If the platform had a native syntax, perhaps other tooling would key off that, much like JavaScript bundlers support the ES6 import format.

The above is the detailed content of The Simplest Ways to Handle HTML Includes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles