调用模板中mustache变量的方法

时间:2020-12-08 14:31:36

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.

我有一个mustache模板,我想调用mustache变量(这里是{{{name}}})上的一些函数。具体地说,我想在name变量上调用toLowerCase()方法。

<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

我试着查了查医生的胡子,但是我找不到怎么做。我试着做

  1. <tr data-index="{{age}}-{{name.toLowerCase()}}"></tr>
  2. < tr材料指数= " { {年龄} } - { { name.toLowerCase()} } " > < / tr >
  3. <tr data-index="{{age}}-{{name}}.toLowerCase()"></tr>
  4. < tr材料指数= " { {年龄} } - { {名称} } .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);
      });
  })

1 个解决方案

#1


7  

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>

#1


7  

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>