Skip to content

Instantly share code, notes, and snippets.

@timhugh
Last active December 5, 2016 21:53
Show Gist options
  • Save timhugh/5dd7573685ed54cf7a43d320df7f2db3 to your computer and use it in GitHub Desktop.
Save timhugh/5dd7573685ed54cf7a43d320df7f2db3 to your computer and use it in GitHub Desktop.
Using Handlebars to insert values into html templates
<!DOCTYPE html>
<html>
<head>
<style>
.output {
border: solid 1px #000;
font-family: monospace;
}
</style>
</head>
<body>
<form id="inputsForm">
<!-- Hard-coded values just to demonstrate when the page loads -->
<input type="text" placeholder="Title" id="titleInput" value="Some Product"><br>
<input type="text" placeholder="Description" id="descriptionInput" value="Boy howdy, this product is great!">
</form>
<!-- Actual filled-in template gets rendered here -->
<div class="output" id="output1"></div>
<!-- The markup inside this script tag is the template the values are inserted into.
Additional templates can be specified the same way (just need unique IDs) -->
<script id="templateScript1" type="text/x-handlebars-template">
<h1>{{title}}</h1>
<p>{{description}}</p>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Compile the template once the page has loaded.
var template1 = Handlebars.compile(templateScript1.text);
// Additional templates could be added here
// Attach a listener to the form that is triggered every time you press a key in the form
inputsForm.oninput = function() {
// Fetch the form values that have been entered
// -- Note: the names on the left correspond with the names inside the template above
var inputs = {
title: titleInput.value,
description: descriptionInput.value
};
// Render the template with the new input
output1.innerText = template1(inputs);
// Additional templates could be rendered here
};
// This just triggers the first rendering when the page loads with the hardcoded values
inputsForm.oninput();
});
</script>
</body>
</html>
@timhugh
Copy link
Author

timhugh commented May 17, 2016

You can see this in action here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment