Andrew Kim
Andrew Kim

Reputation: 3335

abstracting handlebars templates into external files w/o AJAX

Is there any way to load handlebars templates more simply? Seems like an easy thing to be able to do. If I have the following code for index.html:

<body>
  <h1>From the index.html</h1>
  <div id="hbs"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
  <script id="test" type="text/x-handlebars-template">
      <h2>This is from HBS</h2>
      <p>
        hbs generated this p tag!
      </p>
    </script>
    <script src="js/script.js"></script>
</body>

Here's the code for the script to compile the template in js/script.js:

var template = Handlebars.compile(document.querySelector("#test").innerHTML)
document.querySelector("#hbs").innerHTML = template({})

This works fine,but when I open the index.html I can see the header and p tag generated through the template. There has to be an easy way to abstract this template into a separate file!

Upvotes: 3

Views: 1926

Answers (1)

Christophe
Christophe

Reputation: 2200

You can put your template in a hbs file :

template.hbs:

<script type="text/x-handlebars-template">
      <h2>This is from HBS</h2>
      <p>
        hbs generated this p tag!
      </p>
</script>

And then use ajax to get your file instead of a querySelector to get your html

$document.ready(function(){
   $.get( '/url/template.hbs', function( source ) {
      var template = Handlebars.compile(source);
      document.querySelector("#hbs").innerHTML = template({});
   }
});

Upvotes: 3

Related Questions