sircamp
sircamp

Reputation: 107

How do I get and print an .hbs or .handlebars template?

Does anyone know how I can print an .hbs/.handlebars template in an HTML page? I've looked everywhere but I cannot figure out how to put the .hbs files in a directory and then print them in my index.html. Sorry for the question, but I am a new user of handlebars. Thanks in advance!

Upvotes: 3

Views: 10179

Answers (2)

Vignesh
Vignesh

Reputation: 11

Save your hbs file as a fragment file. Say myTemplate.jspf

Include this in your HTML/JSP file as below

<script type="text/x-handlebars-template"> 
   <%@ include file="myTemplate.jspf" %>
</script>

Upvotes: 1

Mike Grassotti
Mike Grassotti

Reputation: 19050

Let's say you have a handlebars template post.handlebars:

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

Use handlebars precompiler to compile your templates:

$ handlebars post.handlebars -f templates.js

Include the compiled templates and handlebars runtime in your html doc

<script src="/libs/handlebars.runtime.js"></script>
<script src="templates.js"></script>

Now the compiled template will be accessible as a property of Handlebars.templates. Next pass data to the template, generate some html and append it to the DOM.

<script type="text/javascript">
   var template = Handlebars.templates.post;
   var context = {title: "My New Post", body: "This is my first post!"};
   var html    = template(context);
  
 $(document).append(html);
</script>

See http://handlebarsjs.com/precompilation.html for details on precompile. Also there is a great handlebars tutorial here: http://javascriptissexy.com/handlebars-js-tutorial-learn-everything-about-handlebars-js-javascript-templating/

Upvotes: 7

Related Questions