Aessandro
Aessandro

Reputation: 5761

Handlebars.js separating script tags from html document

What is the best way of separating the script tag like the following from inside an html document?

<ul class="shoesNav">
 <script id="shoe-template" type="x-handlebars-template">
  {{#each this}}
       <li class="shoes">
            <a href="/{{name}}">{{name}} -- Price: {{price}} </a>
       </li>
   {{/each}}
 </script>

</ul>

Would it be possible to have something like this or similar?

<ul class="shoesNav">
  {{#each this}}
       <li class="shoes">
            <a href="/{{name}}">{{name}} -- Price: {{price}} </a>
       </li>
   {{/each}}
</ul>

The idea would be to have all the templates in a separate file.

Upvotes: 0

Views: 2141

Answers (2)

Cedric Leo
Cedric Leo

Reputation: 31

in your main html file say: main.html


<div id="myTarget"></div>

<script type="text/javascript">
$(document).ready(function(){
    
    var context = { name : "XYZ", city : "Cape town" };
        var templateScript = $('#handlebars-demo').html();
        var theTemplate = Handlebars.compile(templateScript);
        var html = theTemplate(context);
        console.log(html);
    
    $('#myTarget').append(html);
});
</script>

<script src="myscripts.js"></script>

in an external js file say: myscripts.js

<script id="handlebars-demo" type="text/x-handlebars-template" >
    <p> Hi, my name is @{{name}} and i live in @{{city}} </p>
</script>

Upvotes: 0

ckross01
ckross01

Reputation: 1671

You really should separate these out, have a handlebars template that is separate from your html page and then load the template into the div.

so it would be

<div id="shoes">
</div>    

and then have the separate file template that is loaded into that div.

'<script id="shoe-template" type="x-handlebars-template">
  <ul class="shoesNav"> 
  {{#each this}}
      <li class="shoes">
        <a href="/{{name}}">{{name}} -- Price: {{price}} </a>
      </li>
  {{/each}}
  </ul>

'


Upvotes: 1

Related Questions