简体   繁体   中英

Meteor | Helper function. How to print attribute values of returned element on HTML

I am using Meteor JS for UI development of a project. There is a helper method which takes a input parameter and return an object.

Helper Function:

"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return myObj;
    }

How i am using it on HTML

<span>{{getPhoneName 'id_1234'}}</span> //This line is obviously prints the [[Object]]

    Here i am not getting solution how to print modelNumber. I have tried following :
1.{{getPhoneName 'id_1234'.modelNumber}}
2.{{getPhoneName 'id_1234'}}.modelNumber

Can someone help? If you need more information please let me know.

You have mentioned you have this helper function:

getPhoneName (_id) {
  const myObj = PhoneRegister.findOne({_id});
  //This myObj contains  name, _id, modelNumber
  return myObj;
}

There are 2 ways to go based on your needs


First, if you want to get just the "name" as the helper implies getPhoneName , you can instead return myObj.name; (error handling to ensure myObj exists should also be considered).

You can then just use it:

<p>The name of the phone is {{getPhoneName phoneId}}</p>

But, if you instead what to list a variety of information about the phone in your template, you can leave the helper alone and adjust your template in one of two different ways:

1) Use #let to name your object within your template.

{{#let currentPhone=(getPhoneName phoneId)}}
  <ul>
    <li>ID: {{currentPhone._id}}</li>
    <li>Name: {{currentPhone.name}}</li>
  </ul>
{{/let}}

2) Use #with to use that object as your data context without assigning a name

{{#with getPhoneName phoneId}}
  <ul>
    <li>ID: {{_id}}</li>
    <li>Name: {{name}}</li>
  </ul>
{{/let}}

If you only want one property, you could simply return myObj.property; and display it as you already did with {{getPhoneName 'id_1234'}} .
But if you want to access multiple properties, you can return the object in an array and then use each or each-in Blaze's built-in block like this:

Helper:

"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return [myObj];  // Returning an array in order to use each or each-in
    }

HTML (with each):

{{#each getPhoneName 'id_1234'}}
    <span>{{this.property1}}</span>
    <span>{{this.property2}}</span>
{{/each}

You can also take a look at {{#let}} , in some cases it's useful too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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