Handlebars - data not being displayed at all - javascript

Hello everyone,
I've been playing around with the handlebars trying to make it work in my project, but I keep getting no results when I'm testing the page.
I'm using the JSON data that I have received from another page. Those data should be displayed after compiling the template. But nothing really happens, I just get no results at all.
get_items_data.js
var source = $("#mytemplate").html();
var template = Handlebars.compile(source);
var Items = Array();
getting_items_data = true;
$.get('GetItemsData',function(responseJson) {
if(responseJson!=null){
$.each(responseJson, function(key,value) {
Items.push({ "id": value['item_id'], "blabla": "bla" });
});
}
});
$('body').append(template(Items));
test.jsp
<script id="mytemplate" type="text/x-handlebars-template">
<table>
<thead>
<th>Items</th>
</thead>
<tbody>
{{#each this}}
<tr>
<td>{{id}}</td>
<td>{{blabla}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
JSON data format:
[{"ItemID":74,"SectionID":4},{"ItemID":78,"SectionID":4}]
Any ideas what may be wrong here?

It looks your template function is called before you have the data returned, so the Items array is empty when the elements are appended to the DOM. Unlike AngularJS, Handlebars is static templating so it won't update the DOM if you update the array later.
Try move that render logic into the callback of get:
$.get('GetItemsData',function(responseJson) {
if(responseJson!=null){
$.each(responseJson, function(key,value) {
Items.push({ "id": value['item_id'], "blabla": "bla" });
});
$('body').append(template(Items));
}
});

$(document).ready(function() {
LoadItems();
});
Will never execute inside a script of type text/x-handlebars-template.
Also there could be a problem with your variables attempting to get values from the dom before it's loaded.
Here is a dumbed down version that works: http://jsfiddle.net/whDqv/
function LoadItems()
{
var source = $("#mytemplate").html();
var template = Handlebars.compile(source);
var Items = Array();
getting_items_data = true;
Items.push({ "id": 1, "blabla": "bla" });
var template = Handlebars.compile(source);
$('body').append(template(Items));
}
$(document).ready(function() {
LoadItems();
});

Related

json data getting from url is not parsed in handlebars.js

I want to parse JSON data that I am getting from url in handlebars.
What I tried is I got the JSON data from the url.
I defined it into data object.
I want to know how can I parse the data using handlebars.js
I am new to handlebars.js
Is there any other way in which we can get without defining each property?
Because my JSON data is huge.
for eg.
reportData = {
inquiryId= data.data[0].inquiryId;
}
HTML code:
<script id="address-template" type="text/x-handlebars-template">
{{#with data}}
<p> My id is {{{inquiryId}}}</p>
{{/with}}
</script>
<div class="content-placeholder"></div>
JS code:
var reportData= {};
$(document).ready(function () {
$.ajax({
type:'GET',
url: reportURL,
success : function (data){
var inquiryId= data.data[0].inquiryId;
var theTemplateScript = $("#address-template").html();
console.log(theTemplateScript);
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
// Define our data object
reportData=data;
console.log(reportData);
// Pass our data to the template
var theCompiledHtml = theTemplate(reportData);
// Add the compiled html to the page
$('.content-placeholder').html(theCompiledHtml);
}
})
});
JSON:
{
"success":true,
"errors":{
},
"authenticated":true,
"program":1,
"data":[
{
"id":1,
"date":1505756267000,
"name":"AKKAYA, JORGE",
"productName":"Credit Profile",
"inquiryId":726608
}
]
}
My output is:
My id is
Can anyone help me out?
Thanks in advance.
In your Json, data contains array and in your html you are treating it like single object. So please use the below handlebar format to iterate over it.
{{#with abc}}
{{#each this}}
<p> My id is {{{inquiryId}}}</p>
{{/each}}
{{/with}}

Handlebars code inside of Ember Model field. How to evaluate?

Let's say I have some model with html field. This field contains some handlebars code. For example
<div class="foo">
{{model.title}}
</div>
The problem is when I'm trying to iterate over models and render html field, it doesn't evaluate handlebars code inside it.
{{#each models as |model|}}
{{{model.html}}}
{{/each}}
Here's an idea, create a Handlebars helper, that will compile handlebars.
With this sample, I believe you can build something that will suit your needs:
<script type="text/javascript" src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars.min-latest.js"></script>
<script>
var data = [{
"title": "Hey",
"subtitle": "I'm an inner handlebar template.",
"html": '<h1>{{title}}</h1><h2>{{subtitle}}</h2>'
}, {
"title": "Nice!",
"html": '<h1>{{title}}</h1>'
}];
/** Handlebar helper that will compile the content passed, with the data at index **/
Handlebars.registerHelper("compile", function(content, index) {
var template = Handlebars.compile(content);
return template(data[index]);
});
var content = '{{#each .}}\
{{{compile html #index}}}\
{{/each}}';
var template = Handlebars.compile(content);
document.body.innerHTML = template(data);
</script>
I never used ember, but I believe you can make it work easily ;)

How to create html list from a json file (handlebars)

I have an empty todo list:
<ul class="list">
</ul>
I want to create a li inside that list for each json title I have in the following json data:
[{"id":2,"title":"Mandar cartas a impresión","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:55.552Z","updated_at":"2015-12-07T13:09:55.552Z","project_id":1},{"id":3,"title":"CIF Intracomunitario","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:05.736Z","updated_at":"2015-12-07T13:10:05.736Z","project_id":1},{"id":4,"title":"Uniformes Chef a Porter","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:16.170Z","updated_at":"2015-12-07T13:10:16.170Z","project_id":1},{"id":5,"title":"Personal","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:31.569Z","updated_at":"2015-12-07T13:10:31.569Z","project_id":1},{"id":1,"title":"Mandar contrato pleni","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:36.747Z","updated_at":"2015-12-07T13:13:12.068Z","project_id":1},{"id":17,"title":"Comprar TPV","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:40.753Z","updated_at":"2015-12-08T00:18:40.753Z","project_id":1},{"id":18,"title":"Vajillas Zara Home","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:54.580Z","updated_at":"2015-12-08T00:18:54.580Z","project_id":1},{"id":19,"title":"Tpv","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:33:17.393Z","updated_at":"2015-12-08T00:33:17.393Z","project_id":1},{"id":21,"title":"Wifi - Contratar","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:24.639Z","updated_at":"2015-12-08T15:33:24.639Z","project_id":1},{"id":22,"title":"Cuenta Definitiva Santander","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:50.255Z","updated_at":"2015-12-08T15:33:50.255Z","project_id":1},{"id":23,"title":"Pagarés Kider","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:34:08.162Z","updated_at":"2015-12-08T15:34:08.162Z","project_id":1}]
So, I have the following javascript which uses handlebars for templating:
<script>
jQuery.getJSON("http://myurl/tasks.json", function(data){
var source = $("#tasks-template").html();
var template = Handlebars.compile(source);
$.each(data) function() {
var context = data;
var show = template(context);
$(".list").html(show);
});
});
</script>
My handlebars template:
<script id="tasks-template" type="text/x-handlebars-template">
<li>
<div>{{title}}</div>
</li>
</script>
It wont create a li in my html for each title in the json.
What am I missing?
Thanks!
When you iterate for each object of the array received in the JSON, you have to use this instead of data to access to the object.
data is the whole array and this is the current object where you want to retrieve the title property:
$.each(data, function() {
var context = this;
var show = template(context);
$(".list").append(show);
});
And also change the html method for append for don't overwrite the content.
Regards

Call methods on mustache variable in a template

I have a mustache template and I would like to call some function on the mustache variables ({{name}} in this case). Specifically, I want to call toLowerCase() method on the name variable.
<tbody>
<script id="mytemplate" type="text/template">
{{#cat}}
<tr data-index="{{age}}-{{name}}"></tr>
{{/cat}}
</script>
</tbody>
I tried looking in the mustache docs but I couldn't find out how to do this. I tried doing
<tr data-index="{{age}}-{{name.toLowerCase()}}"></tr>
<tr data-index="{{age}}-{{name}}.toLowerCase()"></tr>
But I'm not getting what I expect. I render the template with this code which gets triggered on document ready.
$(function() {
$.getJSON('/cats.json', function(data){
var template = $("#mytemplate").html();
var view = Mustache.to_html(template, data);
$("tbody").html(view);
});
})
you need to pass the function as part of the data, like so:
$(function() {
$.getJSON('/cats.json', function(data){
data.lower = function () {
return function (text, render) {
//wrong line return render(text.toLowerCase());
return render(text).toLowerCase();
}
};
var template = $("#mytemplate").html();
var view = Mustache.to_html(template, data);
$("tbody").html(view);
});
})
and the template:
<tr data-index="{{age}}-{{#lower}}{{name}}{{/lower}}"></tr>

Templating a table with ember.js not working with JSON call

I've got an index page that lists taxes in a table. I'm trying to
implement this with ember.js following some of the code in the
contacts example app.
Here is the gist: https://gist.github.com/1494281
When I don't load the content from JSON, by commenting out line 19 of
taxes.js, the table renders correctly. However if I use the content
that I pulled from taxes.json then the table renders without tr and
td elements.
Script:
App.Tax = Ember.Object.extend({});
App.taxesController = Ember.ArrayController.create({
content: [
{name:"tax1",rate:"10",number_id:"TaxIDNum"},
{name:"tax2",rate:"9",number_id:null}
],
newTax: function() {
this.pushObject(App.Tax.create({}));
},
loadTaxes: function() {
console.log('loadTaxes');
var self = this;
$.getJSON('/taxes.json', function(json) {
console.log('got response', taxes);
var taxes = json.map(function(item) {
return self.createTaxFromJSON(item);
});
self.set('content', taxes);
});
},
createTaxFromJSON: function(json) {
console.log("createTaxFromJSON", json.tax);
return App.Tax.create(json.tax);
}
});
App.taxesController.loadTaxes();
App.selectedTaxController = Ember.Object.create({
content: null
});
App.TaxListView = Ember.View.extend({
classNameBindings: ['isSelected'],
click: function() {
var content = this.get('content');
console.log('click', content);
App.selectedTaxController.set('content', content);
},
isSelected: function() {
var selectedItem = App.selectedTaxController.get('content');
var content = this.get('content');
if (content == selectedItem) {
return true;
}
return false;
}.property('App.selectedTaxController.content')
});
App.TaxView = Ember.View.extend({
contentBinding: 'App.selectedContactController.content'
});
HTML:
<script type="text/x-handlebars">
<table>
{{#each App.taxesController.content}}
{{#view App.TaxListView contentBinding="this" tagName="tr"}}
{{#with content}}
<td>{{name}}</td>
<td>{{rate}}</td>
<td>{{number_id}}</td>
<td>
Edit
Delete
</td>
{{/with}}
{{/view}}
{{/each}}
</table>
</script>
JSON:
[{"tax":{"account_id":1,"created_at":"2011-12-16T22:45:43Z","id":1,"name":"CA Sales Tax","number_id":"","rate":10.0,"updated_at":"2011-12-16T22:45:43Z"}},{"tax":{"account_id":1,"created_at":"2011-12-17T01:03:01Z","id":2,"name":"Second Tax","number_id":"EIN29387","rate":0.3,"updated_at":"2011-12-17T01:03:01Z"}}]
When you look at the resulting HTML, you'll notice that ember added tags inside your table. these are the markers for bindings to work
according to the HTML specification, inside a tag there MUST only be , , , tags, everything else is undefined behaviour
to make it work, you'll have to remove the {{#view}} and it should at least render something useful.

Categories

Resources