Search code examples
meteoriron-router

Rendering Template in Meteor and Iron Router depending on value in document


I am trying to render a template depending on a value of a field in a document.

I tried using a switch case in a helper but the return value comes out incorrect.

units_list.html

<template name="unitsList">
{{#each units}}
  {{> unitItem}}
{{/each}}
</template>

units_list.js

Template.unitsList.helpers({
  units: function() {
    return Units.find({}, {sort: {name: 1}});
  }
});

unit_item.html

<template name="unitItem">
  <a href="{{unitType}}">{{name}}</a>
</template>

unit_item.js

Template.unitItem.helpers({
  unitType: function() {
    var unitType = this.unitType;
    switch(unitType){
      case 'first': return "{{pathFor 'unitPageFirst'}}";
      case 'second': return "{{pathFor 'unitPageSecond'}}";
    }
  }
});

I'm either going about this the wrong way or missing something elementary...

I've cut out a lot of code to focus on the problem.

Any ideas on how to get this working, or any suggestions on how to do it better?


Solution

  • You can't return uncompiled Spacebars strings from JS at execution time.

    You can either use Router.path to get the path for your routes within your template helper :

    Template.unitItem.helpers({
      unitType: function() {
        var unitType = this.unitType;
        switch(unitType){
          case 'first':
            return Router.path('unitPageFirst', this);
          case 'second':
            return Router.path('unitPageSecond', this);
        }
      }
    });
    

    Or you can use plain Spacebars by declaring template helpers to check against the unitType.

    HTML

    <template name="unitItem">
      {{#if unitTypeIs 'unitTypeFirst'}}
        <a href="{{pathor 'unitTypeFirst'}}">{{name}}</a>
      {{/if}}
      {{#if unitTypeIs 'unitTypeSecond'}}
        <a href="{{pathor 'unitTypeSecond'}}">{{name}}</a>
      {{/if}}
    </template>
    

    JS

    Template.unitItem.helpers({
      unitTypeIs: function(unitType){
        return this.unitType == unitType;
      }
    });