Skip to content

Instantly share code, notes, and snippets.

@davidDuymelinck
Last active August 29, 2015 14:14
Show Gist options
  • Save davidDuymelinck/284f6576ec265b9f2000 to your computer and use it in GitHub Desktop.
Save davidDuymelinck/284f6576ec265b9f2000 to your computer and use it in GitHub Desktop.
web component static website demo
<html>
<head>
<link rel="import" href="indexMain.html">
</head>
<body>
<section class="main"></section>
<script src="site.js"></script>
<script>
site.addTemplate('.main', 'indexMain.html');
</script>
</body>
</html>
<template id="indexMain">
<h1>Main index</h1>
</template>
var site = {};
site.utils = {};
site.utils.addError = function(msg){
var body = document.querySelector('body'),
el = document.createElement('p');
el.setAttribute('style', 'color: red; font-weight: bold;');
el.textContent = msg;
body.insertBefore(el, body.firstChild);
};
site.templates = [];
site.getTemplates = function(){
var templatesRaw = document.querySelectorAll('link[rel="import"]'),
templates = [];
for(var link in templatesRaw){
if(parseInt(link) === parseInt(link)){
templates[templates.length] = templatesRaw[link];
}
}
if(templates.length === 0){
site.utils.addError("There are no imports");
}
site.templates = templates;
};
site.utils.autoGetTemplates = function(){
if(site.templates.length === 0){ site.getTemplates(); }
};
site.addTemplate = function(documentTag, templateFile){
site.utils.autoGetTemplates();
var templateTag = templateFile.replace('.html', ''),
containerTag = document.querySelector(documentTag),
templateExists = false,
templateLink = null;
if(containerTag === null){
site.utils.addError(documentTag+" does not exist!");
return;
}
for(var index in site.templates){
var template = site.templates[index],
re = new RegExp(templateFile+'$');
if(re.test(template.href)){
templateExists = true;
templateLink = template;
}
}
if(!templateExists){
site.utils.addError(templateFile+' does not exist!');
return;
}
var contentAll = template.import,
contentTemplate = contentAll.querySelector('#'+templateTag),
clone = document.importNode(contentTemplate.content, true);
containerTag.appendChild(clone);
}
site.addHeader = function(title){
site.utils.autoGetTemplates();
for(var index in site.templates){
var template = site.templates[index];
if(/header.html$/.test(template.href)){
var contentAll = template.import,
contentTemplate = contentAll.querySelector('.header'),
clone = document.importNode(contentTemplate.content, true);
clone.querySelector('h1').textContent = title;
document.querySelector('header').appendChild(clone);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment