search
HomeWeb Front-endCSS TutorialThe Simplest Ways to Handle HTML Includes

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 

 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>
  

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 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
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
Powering Search With Astro Actions and Fuse.jsPowering Search With Astro Actions and Fuse.jsApr 22, 2025 am 11:41 AM

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

Undefined: The Third Boolean ValueUndefined: The Third Boolean ValueApr 22, 2025 am 11:38 AM

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

In Defense of the Ternary StatementIn Defense of the Ternary StatementApr 22, 2025 am 11:25 AM

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Using the Web Speech API for Multilingual TranslationsUsing the Web Speech API for Multilingual TranslationsApr 22, 2025 am 11:23 AM

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

Jetpack Gutenberg BlocksJetpack Gutenberg BlocksApr 22, 2025 am 11:20 AM

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

All About mailto: LinksAll About mailto: LinksApr 22, 2025 am 11:04 AM

You can make a garden variety anchor link () open up a new email. Let's take a little journey into this feature. It's pretty easy to use, but as with anything

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor