Search code examples
meteormeteor-blazespacebars

Displaying dynamic content in Meteor using Dynamic Templates


I've read through the (somewhat sparse) documentation on Dynamic Templates but am still having trouble displaying dynamic content on a user dashboard based on a particular field.

My Meteor.users collection includes a status field and I want to return different content based on this status.

So, for example , if the user has a status of ‘current’, they would see the 'currentUser' template.

I’ve been using a dynamic template helper (but have also considered using template helper arguments which may still be the way to go) but it isn’t showing a different template for users with different statuses.

{{> Template.dynamic template=userStatus}}

And the helper returns a string to align with the required template as required

 userStatus: function () {
     if (Meteor.users.find({_id:Meteor.userId(), status: 'active'})){
         return 'isCurrent'
     }
     else if (Meteor.users.find({_id:Meteor.userId(), status: ‘isIdle'})) {
         return 'isIdle'

     } else {
         return ‘genericContent'

     }
}

There may be much better ways to go about this but it seems a pretty common use case.

The few examples I've seen use Sessions or a click event but I’d rather use the cursor if possible. Does this mean what I’m missing is the re-computation to make it properly reactive? Or something else incredibly obvious that I’ve overlooked.


Solution

  • Ended up using this approach discussed on the Meteor forums which seems a bit cleaner.

      {{> Template.dynamic template=getTemplateName}}
    

    And the helper then becomes:

      getTemplateName: function() {
            return "statusTemplate" + Meteor.user().status;
        },
    

    Which means you can then use template names based on the status:

    <template name="statusTemplateActive">
     Content for active users
    </template>
    

    (though keep in mind that Template helpers don't like hyphens and the data context needs to be set correctly)