I have 2 HTML files, suppose a.html
and b.html
. In a.html
I want to include b.html
.
In JSF I can do it like that:
<ui:include src="b.xhtml" />
It means that inside a.xhtml
file, I can include b.xhtml
.
How can we do it in *.html
file?
My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:
a.html:
b.js:
The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.
In order to get the properly escaped JavaScript file without much work, you can use the following sed command:
Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting
b.html
tob.js
: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.
Shameless plug of a library that I wrote the solve this.
https://github.com/LexmarkWeb/csi.js
The above will take the contents of
/path/to/include.html
and replace thediv
with it.There is no direct HTML solution for the task for now. Even HTML Imports (which is permanently in draft) will not do the thing, because Import != Include and some JS magic will be required anyway.
I recently wrote a VanillaJS script that is just for inclusion HTML into HTML, without any complications.
Just place in your
a.html
It is
open-source
and may give an idea (I hope)Checkout HTML5 imports via Html5rocks tutorial and at polymer-project
For example:
Using ES6 backticks ``: template literals!
This way we can include html without encoding quotes, include variables from the DOM, and so on.
It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:
https://caniuse.com/#feat=template-literals
Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files:
And then to include something in the html:
Which would include the file views/header.html and views/footer.html