问题
I have the following function which handles AJAX success 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 how 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 this is how it should work as it's described in mustache manual (http://mustache.github.com/mustache.5.html) but I'd like to get the value instead.
this
would point to my product object so I could get cost using this.Cost
but this is for a simple case and I have many object types with many properties that need formatting therefore I need a generic solution to keep things DRY.
I could also calculate this on the server side but I prefer to do this on the client side since I am not only using this data with hogan but also for other calculations on the client side.
Is there more straightfoward, generic and client side way to get the value of Cost instead of the unrendered literal block?
回答1:
Yep.
Mustache implementations that scrictly adhere to the spec are very limiting. Your option would be, in your lambda code, to render the "{{Cost}}" string (you should get this string and a rendering function as your lambda parameters), and parse the rendered string into a float, your cost.
Not clean, for sure. But it would work. Don't forget to open an issue in the repository of the Mustache implementation you are using.
回答2:
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 stated in the question, we can use this object.
Javascript code is
res.render("template", {
formatMoney:{
return function(key){
var cost = this[key];
return cost.format('usd');
};
}
});
and the template is
{#Items}}
<tr>
<td>{{ProductId}}</td>
<td>{{#formatMoney}}Cost{{/formatMoney}}</td>
</tr>
{{/Items}}
来源:https://stackoverflow.com/questions/14460350/how-to-get-the-value-when-using-lambda-in-hogan-js