Last active
August 29, 2015 14:04
-
-
Save lukehedger/91cdf1e783d3575d1965 to your computer and use it in GitHub Desktop.
HTML Imports/Templates example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- Link to import file --> | |
<link rel="import" href="template.html" name="template1"> | |
</head> | |
<body> | |
<!-- a container div with an id to match the name attribute of the import link --> | |
<div class="container" id="template1"> | |
<!-- the contents of template.html will be inserted here at runtime --> | |
</div> | |
<!-- bit of JavaScript to insert the template --> | |
<script> | |
var imports = document.querySelectorAll('link[rel="import"]'); | |
for (var i = imports.length - 1; i >= 0; i--) { | |
var template = imports[i].import.querySelector('template'); | |
var clone = document.importNode(template.content, true); | |
var container = '#'+imports[i].getAttribute('name'); | |
document.querySelector(container).appendChild(clone); | |
}; | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
Markup goes here | |
</div> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick example of using HTML Imports and HTML Templates together.
You can only use natively in Chrome 36+ but I've found them useful for quickly prototyping pages where I'll use a JavaScript templating library down the line.
There's also a Polymer polyfill if you want to go a step further.
Resource: HTML5 Rocks article on HTML Imports