I've just started using handlebars.js in attempt to move away from rendering dynamic data the ugly way using string concat and injection. I am trying to separate the template script from the main HTML file and render the template file via a function call.
Here is what 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 the '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 to be getting this error on the console: Failed to load resource: The requested URL was not found on this server. However, when I add the template to Index.html (and remove ajax call from the script file), the template renders just fine.
Can anybody shed some light as to why this is happening and how I can fix this?
Thanks in advance.