How to get the value when using Lambda in Hogan.js

蹲街弑〆低调 提交于 2019-12-12 11:24:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!