Skip to content

Instantly share code, notes, and snippets.

@Bktero
Created July 1, 2019 12:17
Show Gist options
  • Save Bktero/24d38d4e417f4752684ed15b9e49e9d2 to your computer and use it in GitHub Desktop.
Save Bktero/24d38d4e417f4752684ed15b9e49e9d2 to your computer and use it in GitHub Desktop.
[HTML/CSS/JS] HandleBarJS example
* {
font-family: 'Roboto', sans-serif;
font-weight: normal;
}
button.open {
display: inline-block;
width: 4rem;
height: 2rem;
border-radius: 0.3rem;
border-width: 0;
transition-duration: 0.2s;
background-color: darkgray;
}
button.open:hover {
background-color: darkred;
}
button.open:active {
background-color: darkorange;
}
button.open:focus {
outline: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>HandleBarJS Example</title>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="main.css" rel="stylesheet">
</head>
<body>
<script id="my-template" type="text/x-handlebars-template">
<h2>{{ title }}</h2>
This document was written by <em>{{ document.author }}</em>
(version {{ formatVersion document.version.major document.version.minor }}).
<h2>References</h2>
<ol>
{{#each references }}
<li>{{ this }}</li>
{{/each}}
</ol>
{{#times 3 }}
<button class="open" onclick="popup({{ this }})"></button>
{{/times}}
</script>
<div id="template-placeholder">
<!-- Will be filled with the rendering of the template -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.js"></script>
<script src="main.js"></script>
<script>
function popup(value) {
console.log(value);
}
</script>
</body>
</html>
// Create and register helper functions
function formatVersion(major, minor) {
return major + '.' + minor;
}
Handlebars.registerHelper("formatVersion", formatVersion);
function times(n, options) {
// Code from https://stackoverflow.com/questions/11924452/iterating-over-basic-for-loop-using-handlebars-js
// See "Block Expressions" from the documentation https://handlebarsjs.com/
var accum = '';
for(var i = 0; i < n; ++i)
accum += options.fn(i);
return accum;
}
Handlebars.registerHelper("times", times);
// Utility function that can be used "as a value" in the context
function getReferences() {
return [ "the first reference", "another reference", "and a third reference" ];
}
// Creat and compile template
const source = document.getElementById('my-template').innerHTML;
const template = Handlebars.compile(source);
// Render it
const context = {
title: "My First Template",
document: {
version: {
major: 42,
minor: 1
},
author: "jack"
},
references: getReferences(),
};
const html = template(context);
// Display result
const placeholder = document.getElementById('template-placeholder');
placeholder.innerHTML = html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment