Handlebars Example #1

by Berat Emre NebioÄźlu

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<!--This is our template. -->
<!--Data will be inserted in its according place, replacing the brackets.-->
<script id="address-template" type="text/x-handlebars-template">
  <p>I graduated from{{university}}. I studied at {{department}}. And it is my last year as student in {{university}} in {{year}}.</p>
</script>

<!--Your new content will be displayed in here-->
<div class="content-placeholder"></div>

JavaScript

$(function () {
  // Grab the template script
  var theTemplateScript = $("#address-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // Define our data object
  var context={
    "university": "Harward",
    "department": "Economy",
    "year": "2008"
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);
});