【问题标题】:passing an object to a function with mustache.js使用 mustache.js 将对象传递给函数
【发布时间】:2016-04-25 12:29:44
【问题描述】:

有没有办法通过 mustache.js 模板将对象传递给函数?

类似:

var template = $('#template').html();
var json = {folder : 'abc', size : '123', date : '1'};
var output = Mustache.render(template, json);


<script type="template/text" id="template">
    <td><span class="{{folder}}" onclick="doSomething(json)"></span>
</script>

我没有找到任何方法来做到这一点,所以我想这是不可能的,如果是这样,哪个模板引擎可以做到这一点?

【问题讨论】:

    标签: mustache template-engine


    【解决方案1】:

    你可以这样做...

    * 车把助手 *

    json: function(obj) {
      return JSON.stringify(obj)
    }
    

    服务器

    var crypto = {}
    res.locals = {
      crypto: crypto
    }
    

    客户

    <script>
        var crypto = {{{json crypto}}}
    </script>
    

    【讨论】:

      【解决方案2】:

      您可以在呈现 html 后绑定事件处理程序。比如:

      <script type="template/text" id="template">
          <td><span class="{{folder}} folder" onclick="doSomething(json)"></span>
      </script>
      
      var template = $('#template').html();
      var json = {folder : 'abc', size : '123', date : '1'};
      var output = Mustache.render(template, json);
      
      $(".folder").on('click', function(){
        //make use of json object here
      });
      

      【讨论】:

        【解决方案3】:
        <script type="template/text" id="template">
            <td><span onclick="myFunction({{json}})">{{variable}}</span></td>
        </script>
        
        
        var data={
            variable:'some stuff',
            json: function() {
               return JSON.stringify(data)
            }
        };
        
        
        var template = $('#template').html();
        
        var output = Mustache.render(template, data);
        
        var myFunction=function(data){
            console.log(data);
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-30
          • 2011-12-07
          • 2016-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-22
          相关资源
          最近更新 更多