Search code examples
javascriptmeteorhandlebars.jsmeteor-blazespacebars

How to access an object within another object in meteor.js


I'm currently trying to access objects within other objects using Meteor. The Object looks like:

({
title: "Bubble Explosion",
createdAt: new Date(),
label: {
        status: "live",
        class: "success"
        } 
})

My problem is that I dont know how to access the status and class of the label object. All other attributes just work fine..

<tbody>
   {{#each imports}}
      {{> tableRow}}
   {{/each}}
</tbody>

<template name="tableRow">
...

  <td>
     <span class="label label-{{label}} text-xs-left">{{label.status}}
     </span>                 
  </td>
...
</template>

Any suggestions?


Solution

  • You have to specify a helper for your template to retrieve data, like that: {Doc here}

    mytemplate.html

    <template name="table">
        <tbody>
          {{#each getImports}}
               {{> tableRow}}
          {{/each}}
        </tbody>
    </template>
    
    <template name="tableRow">
      <td>
         <span class="label label-{{label.class}} text-xs-left">{{label.status}}
         </span>                 
      </td>
      <td>
         {{title}}                
      </td>
    </template>
    

    mytemplate.js

    Template.table.helpers({
      getImports() {
        return [
          {
            title: "Bubble Explosion",
            createdAt: new Date(),
            label: {
                  status: "live",
                  class: "success"
            } 
          },
          {
            title: "Bubble Explosion #2",
            createdAt: new Date(),
            label: {
                  status: "live",
                  class: "success"
            } 
          },
        ]
      }
    })
    

    To work with MongoDB data you can update you mytemplate.js file

    Template.table.onCreated(function() {
      let instance = this;
      /* Subscribe to data */
      instance.subscribe('imports')      
    })
    Template.table.helpers({
      getImports() {
         return Imports.find({}).fetch()
      }
    })