Handlebars JS Example #1

Using HandlebarsJS over jQuery text() or even html() for changing dynamic data

by Farzad Cyrus

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.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">
  <ul>
  <li>{{firstName}}</li>
  <li>{{lastName}}</li>
  </ul>
</script>

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


<button id="button-change">
Change Address
</button>

JavaScript

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

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

// some dynamic data
    var _data = {firstName: 'Farzad', lastName: 'Cyrus'};
    var _data2 = {firstName: 'Mihir', lastName: 'Solanki'};

  // Define our data object
  var context = _data;
  

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

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);
  
  
  $('#button-change').click(function(){
  	context = _data2;
    $('.content-placeholder').html(theCompiledHtml);
  });
  
  
});