简体   繁体   English

在Meteor中如何将整个对象传递给模板助手?

[英]In Meteor how to pass entire object to template helper?

I currently have a template helper I am using to set the color of a table row, based on some logic. 我目前有一个模板帮助器,用于根据某些逻辑设置表行的颜色。 The helper requires several fields to make its determination. 帮助程序需要几个字段来确定。

<template name="files">
   .
   .
    <thead>...</thead>
    <tbody>
        {{#each files}}
          <tr class="status" style="background-color:{{getStatusColor deleted_on changed_on created_on}}">
            <td>{{_id}}</td>               
            <td>{{created_on}}</td>
            <td>{{changed_on}}</td>
            <td>{{deleted_on}}</td>
          </tr>
        {{/each}}
      </tbody>

And the (abbreviated) JS: 和(缩写)JS:

Template.files.helpers({
  /* returns background color for row based on file properties */
  getStatusColor: function(deleted_on, changed_on, created_on) {
     if(deleted_on)
       return foo...
     if(changed_on)
       return bar...
  }
});

This works great but it seems kind of cheesy that I need to pass each individual attribute. 这很好用,但是我似乎需要每个属性传递一些俗气。 Is there a cleaner way to pass the entire object, and reference the attributes from within the helper? 有没有一种更干净的方法来传递整个对象,并从帮助器内部引用属性? Something along the lines of: 类似于以下内容:

<template name="files">
   .
   .
    <thead>...</thead>
    <tbody>
        {{#each files}}
          <tr class="status" style="background-color:{{getStatusColor this}}">
            <td>{{_id}}</td>               
            <td>{{created_on}}</td>
            <td>{{changed_on}}</td>
            <td>{{deleted_on}}</td>
          </tr>
        {{/each}}
      </tbody>

And referencing the attributes instead in the helper like this: 然后像这样在助手中引用属性:

Template.files.helpers({
  /* returns background color for row based on file properties */
  getStatusColor: function(obj) {
     if(obj.deleted_on)
       return foo...
     etc.
  }
});

I understand this would make the helper need to know more about the data object in question, but am curious if this is possible. 我知道这会使助手需要更多地了解所讨论的数据对象,但是很好奇是否可行。

PS I'm quite new to Meteor, be gentle. PS:我对Meteor还是很陌生,请保持温柔。

You just answered your own question. 您只是回答了自己的问题。 If you pass in this inside the each loop, it will pass in the whole object. 如果在each循环中传递this ,它将传递整个对象。

In template: 在模板中:

{{#each files}}
  <tr class="status" style="background-color:{{getStatusColor this}}">
    <td>{{_id}}</td>               
    <td>{{created_on}}</td>
    <td>{{changed_on}}</td>
    <td>{{deleted_on}}</td>
  </tr>
{{/each}}

On a client.js file: 在client.js文件上:

Template.files.helpers({
  /* returns background color for row based on file properties */
  getStatusColor: function(file) {
     if(file.deleted_on)
       return foo...
     etc.
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM