Rendering pattern in Meteor and Iron Router depending on the value in the document

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

I tried to use the toggle case in the helper, but the return value came out wrong.

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 am either cheating on this or missing something rudimentary ...

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

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

+3


source to share


2 answers


You cannot return unrelated Spacebars strings from JS at runtime.

You can use Router.path

to get the path to your routes in your templating 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 simple spaces by declaring template helpers to test for 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;
  }
});

      

+1


source


Take a look at the rendering templates in the Iron-router manual, specifically the this.render ('xyz');



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

0


source







All Articles