javascript - Rendering local templates using Handlebars.js -
i've started using handlebars.js in attempt move away rendering dynamic data ugly way using string concat , injection. trying separate template script main html file , render template file via function call.
here i've got:
script.js ---------- $(function() { var mydata = { requests: [ {id: "1", firstname: "roger", lastname: "jones", age: 24}, {id: "2", firstname: "phillip", lastname: "green", age: 44} ]}; $.ajax({ url: 'templates/requests.html', datatype: 'html', cache: false, success: function(data, status, response) { var template = handlebars.compile(response.responsetext); var context = mydata; $('#injecttemplate_requests').html(template(context)); } }); });
index.html ------------- <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>handlebars</title> </head> <body> <div id="injecttemplate_requests"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script> <script src="script.js"></script> </body> </html>
requests.html (template file inside 'templates' directory) -------------- <table> <thead> <th>name</th> <th>status</th> <th>type</th> </thead> <tbody> {{#requests}} <tr> <td>{{firstname}} {{lastname}}</td> <td>{{age}}</td> </tr> {{/requests}} </tbody> </table>
file structure -------------- index.html | script.js | | |---templates | | |---requests.html
i seem getting error on console: failed load resource: requested url not found on server.
however, when add template index.html
(and remove ajax call script file), template renders fine.
can shed light why happening , how can fix this?
thanks in advance.
i managed fix issue changing this:
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
to this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
thanks suggestions though.
Comments
Post a Comment