I am working with HTML <template>
elements. Code-wise, it seems inconvenient to keep the correct set of templates inside each HTML file.
Is it possible to put templates in a separate file? I want something like CSS, where I can include CSS files in the <head>
section of my HTML file:
<link rel="stylesheet" type="text/css" href="mystyle.css">
My app uses several <template>
collections. Can they be in a separate file, or does each <template>
definition need to be directly part of the original HTML file?
2020 Update
Now that HTML Imports have been deprecated, you could use fetch()
to download HTML code:
void async function () {
//get the imported document in templates:
var templates = document.createElement( 'template' )
templates.innerHTML = await ( await fetch( 'templates.html' ) ).text()
//fetch template2 1 and 2:
var template1 = templates.content.querySelector( '#t1' )
var template2 = templates.content.querySelector( '#t2' )
console.log( template2 )
} ()
Original answer
Imagine we want to import a bunch of <template>
s in a separate file called templates.html.
In the (main) homepage index.html, we can import the file via HTML Imports:
<link rel="import" href="templates.html" id="templates">
In the imported file templates.html, add one or as many templates as you need:
<template id="t1">
<div>content for template 1</div>
</template>
<template id="t2">
content for template 2
</template>
The imported document is available from the import
property of the <link>
element. You can use querySelector
on it.
<script>
//get the imported document in doc:
var link = document.querySelector( 'link#templates' )
var doc = link.import
//fetch template2 1 and 2:
var template1 = doc.querySelector( '#t1' )
var template2 = doc.querySelector( '#t2' )
</script>
Note: you can place the above script in the main document, or in the imported one because the <script>
s inside an imported file are executed as soon as the are parsed (at download time).