Hello Handlebars.js!

I just completed a fairly short but very¬†informative course¬†on¬†Handlebars¬†through¬†PluralSight. The course, by Ryan Lewis, is called ‚ÄúJavaScript Templating with Handlebars‚ÄĚ, and I would highly encourage those who are interested in learning a strong templating framework to take it. It covers Handlebars, but also dives into some great best practices that include using tools like Bower and Gulp, Modular Template¬†Patterns, and using Handlebars with Node.

Anyway, here’s a very simple templating example using Handlebars!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
</head>
<body>
  <div id="Main"></div>
  <script>
    // Define the template
    // Templates are really just strings
    var stringTemplate = "<div>Hello {{name}}</div>";

    // Compile the template
    // This returns a templating function
    var compiledTemplate = Handlebars.compile(stringTemplate);

    // Invoke the templating function with the appropriate data
    // This returns a string that contains the rendered template
    var renderedTemplate = compiledTemplate({name: 'Smik'});

    // Retrieve the element which you intend to inject the string into
    // In our case this string contains HTML
    var targetElement = document.getElementById("Main");

    // Inject the string into the target element
    targetElement.innerHTML = renderedTemplate;
  </script>
</body>
</html>