How to get value when using Lambda in Hogan.js

I have the following function that processes an AJAX callback in jQuery:

function success(data) { var templateData = { items: data, formatMoney: function () { return function (value) { return Globalization.format(value, 'N'); }; } }; // fill reports table var filledTable = tableTemplate.render(templateData); $tableContainer.html(filledTable); } 

Here's what my template looks like:

 {#Items}} <tr> <td>{{ProductId}}</td> <td>{{#formatMoney}}{{Cost}}{{/formatMoney}}</td> </tr> {{/Items}} 

The problem is that instead of the value of Cost I get {{Cost}}. I know that this should work as described in the mustache manual (http://mustache.github.com/mustache.5.html), but I would like to get the value instead.

this will point to my product object, so I could get the value using this.Cost , but this is for a simple case, and I have many types of objects with many properties that require formatting, so I need a general solution for storing DRY things .

I could also calculate this on the server side, but I prefer to do it on the client side, since I not only use this data with hogan, but also for other client-side calculations.

Is there a more direct, general, and client-side way to get the value of Cost instead of an unloaded literal?

+4
source share
2 answers

Yes.

Strong implementations that adhere strictly to the specification are very limited. Your option would be in your lambda code to display the string "{{Cost}}" (you should get this string and the rendering function as your lambda parameters) and analyze the displayed string in float, your costs.

Not bad, of course. But it will work. Remember to open the problem in the Mustache implementation repository that you are using.

+1
source

I think we have two options.

1) Use lambdas in hogan.js

 res.render("template", { lambdas:{ formatMoney: function( cost ){ return cost.format('usd'); } }); 

and the template should be

 {#Items}} <tr> <td>{{ProductId}}</td> <td>{{#lambdas.formatMoney}}{{Cost}}{{/lambdas.formatMoney}}</td> </tr> {{/Items}} 

2) As indicated in the question, we can use this object.

Javascript Code

 res.render("template", { formatMoney:{ return function(key){ var cost = this[key]; return cost.format('usd'); }; } }); 

and pattern

 {#Items}} <tr> <td>{{ProductId}}</td> <td>{{#formatMoney}}Cost{{/formatMoney}}</td> </tr> {{/Items}} 
0
source

All Articles