PiotrG
PiotrG

Reputation: 871

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?

Upvotes: 3

Views: 108

Answers (2)

saimeunt
saimeunt

Reputation: 22696

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;
  }
});

Upvotes: 1

Ren&#233; Post
Ren&#233; Post

Reputation: 1

Have a look at Rendering Templates in the Iron-router guide, specifically the this.render('xyz'); statement

https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#rendering-templates

Upvotes: 0

Related Questions