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> ...
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" ?> ...
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') ...
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('./')); });
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", } } } });
Then your HTML can use this special syntax for includes:
... <!--(bake header.html)--> Content <!--(bake footer.html)--> ...
Use Handlebars
Handlebars has partials.
You register them:
Handlebars.registerPartial('myPartial', '{{name}}')
Then use them:
{{> myPartial }}
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" ...
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" %} ...
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."); });
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>
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; });
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
Use iframes
You could do this:
<iframe src="./header.html"></iframe> Content. <iframe src="./footer.html"></iframe>
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>
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>
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 %}
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>
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" -->
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
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" --> ...
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 have
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It'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.

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

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's like this.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

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.

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

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

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...
