Html include local html file

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:

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.

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.

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

Handlebars.registerPartial('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.

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

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.

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.

  Content.  

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.

Читайте также:  Include php всю папку

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:

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

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

OK, I’ll call out one more SSG because it’s new and super focused. Sergey has a web components style format:

You’d name the files header.html and footer.html and 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.

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

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

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 statements 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. @import ing 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.

Источник

How to include another HTML file in an HTML file?

In this tutorial, we shall learn to include another HTML file in an HTML file.

Various methods are available to include another HTML file in an HTML file. Let us quickly go through the techniques that have support on the web.

Читайте также:  Java loading image icon

Using JQuery load to include an HTML file

In this section, we shall check how to use JQuery’s load method to include an HTML file.

Users can follow the syntax below to use this method.

Syntax

The wrapper appends the new HTML file that jQuery loads.

Parameters

  • wrapper − ID of the DOM element that includes the new HTML content.
  • htmlfile − The new HTML file name.

Example

The program requires two HTML files. One is the main HTML file to load the new HTML file. Next is the new HTML file. Place both files in the exact location.

Define a wrapper DOM element in the main HTML file to append the new HTML file. Using the jQuery load technique load the new HTML file and set it inside the wrapper DOM.

Inner HTML file

 
html> body> h3>This is an HTML page from same directoryh3> body> html>

Main HTML file

html> head> script src="https://code.jquery.com/jquery-1.11.3.min.js">script> script> $(function() < $("#includeHtml").load("result.html"); >); script> head> body> h2>Program to include another HTML file in this HTML using i>JQuery loadi>h2> div id="includeHtml">div> body> html>

Output

Using w3-include-html attribute to include an HTML file

In this section, let us check how to use the w3-include-html attribute to include an HTML file.

Users can follow the syntax below to use this method.

Syntax

Includes a wrapper DOM with the attribute w3-include-html having the new HTML file name as the value.

//Read the attribute fileName = domEl.getAttribute("w3-include-html"); //Make XMLHttpRequest with the attribute value xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() < //If the request is successful, load the new HTML. Else throw 404 error and try again if (this.readyState == 4) < if (this.status == 200) if (this.status == 404) /* Remove the attribute and invoke the function again*/ domEl.removeAttribute("w3-include-html"); addHTML(); > xmlHttp.open("GET", fileName, true); xmlHttp.send();

The syntax reads the w3-include-html attribute value and loads the new HTML with a XMLHttpRequest.

Example

In this example, create a new HTML and a default HTML file. The default HTML file contains a div element with attribute w3-include-html which contains the new HTML file name.

The program reads the w3-include-html attribute value, makes an XMLHttpRequest with the file name, and loads the file.

A New HTML file renders inside the w3-include-html wrapper DOM after a successful file load. Else user gets an error message, and the program loads the file again.

Inner HTML file

html> body> header>b>HTML 2 HEADERb>header> div style="height: 100px;">div> footer>b>HTML 2 FOOTERb>footer> body> html>

Main HTML file

html> body> h2>Program to include another HTML file in this HTML using i>w3-include-htmli>h2> div w3-include-html="result.html">div> script> function addHTML() < var el, i, domEl, fileName, xmlHttp; /*Iterate all DOM*/ el = document.getElementsByTagName("*"); for (i = 0; i < el.length; i++) < domEl = el[i]; /*find the element having w3-include-html attribute*/ fileName = domEl.getAttribute("w3-include-html"); if (fileName) < /*http request with attribute value as file name*/ xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() < if (this.readyState == 4) < if (this.status == 200) < domEl.innerHTML = this.responseText; >if (this.status == 404) < domEl.innerHTML = "Page not found."; >/* Remove the attribute and invoke the function again*/ domEl.removeAttribute("w3-include-html"); addHTML(); > > xmlHttp.open("GET", fileName, true); xmlHttp.send(); /*function ends*/ return; > > > addHTML(); script> body> html>

Output

Using the htmlinclude library to include an HTML file

In this section, we shall check how to use the htmlinclude library to include an HTML file.

Users can follow the syntax below to use this method.

Syntax

The syntax adds the javascript library file URL.

The include tag src contains the new HTML file name.

//Getting include attribute value let includes = document.getElementsByTagName('include'); for(var i=0; i); > function load_file(filename, callback) < fetch(filename).then(response =>response.text()).then(text => callback(text)); >

The syntax loads the source of the tag «include» using the fetch method.

Example

In this example, the htmlinclude library is available in the header. Creating an include tag with the new file name as the src attribute value.

Coming to the script, loading the include tag src value with the fetch method. If you get any error using fetch, try to get help from nodejs or any other program IDE.

Inner HTML file

html> body> b>htmlinclude library included this HTML fileb> body> html>

Main HTML file

html> head> script src="https://unpkg.com/htmlincludejs">script> head> body> h2>Program to include another HTML file in this HTML using i>htmlinclude libraryi>h2> include src="./result.html">include> script> let includes = document.getElementsByTagName('include'); for (var i = 0; i < includes.length; i++) < let include = includes[i]; load_file(includes[i].attributes.src.value, function(text) < include.insertAdjacentHTML('afterend', text); include.remove(); >); > function load_file(filename, callback) < fetch(filename).then(response =>response.text()).then(text => callback(text)); > script> body> html>

Output

Using an iframe to include an HTML file

In this section, let us check how to use an iframe to include an HTML file.

Users can follow the syntax below to use this method.

Syntax

The iframe tag includes the new HTML file name in the src.

Example

In this example, create a sample HTML file to include and main HTML file. The approach adds an iframe with the new HTML file name as the source value in the new HTML body.

The iframe loads the new HTML content inside the main HTML file.

Inner HTML file

html> body> div style="background-color: skyblue;">iframe included this HTML filediv> body> html>

Main HTML file

html> head> h2>Program to include another HTML file in this HTML using i>iframei>h2> style> iframe[iframetag] < border: none; >style> head> body> div id="iframeDiv"> iframe src="result.html" iframetag>iframe> div> body> html>

Output

This tutorial introduced four methods to include a new HTML file in an HTML file. The iframe method is simple to implement. Users can choose the jQuery load method if they need a jQuery method.

Источник

Оцените статью