Search code examples
meteoriron-router

Meteor data-context with iron-router


I am new to Meteor and I'm trying to set the data context in a page that displays one passage. I need to access the data in passage_item.js Template.passageItem.rendered but no context is set at that point. I think I need something like {{#with passage}} but "passage" does not exist in one_passage.html.

Here are some code snippets. Thanks.

router.js

Router.map(function() {
    this.route('passagesList', {path: '/'});
    this.route('onePassage', { 
    path: '/passages/:_id',
    data: function() { return Passages.findOne(this.params._id); }
    });
});

one_passage.html

<template name="onePassage">
    {{> passageItem}}
</template>

passage-item.html

<template name="passageItem">
  <div class="passage">
    <div class="one-passage">
      <h4><a href= "{{pathFor 'onePassage'}}">{{title}}</a></h4>
     <div class="passage-content">
    {{content}}
     </div>
   </div>
 </div>

passage_item.js

Template.passageItem.helpers({
});

Template.passageItem.rendered = function() {
    Meteor.defer(function() {
    $('.passage-content').lettering('words');
   //I want to be able to access the data object here. I have a list of words that are highlighted
    });
};

Solution

  • Collection

    Assuming you created your Passages collection like this and you've got autopublish turned on (which it is by default):

    Passages = new Meteor.Collection('passages');
    

    Router Map

    And you mapped your router like this:

    Router.map(function() {
        this.route('onePassage', { 
            path: '/passages/:_id',
            template: 'passageItem' // <-- to be explicit
            data: function() {
                return Passages.findOne(this.params._id);
            }
        });
    });
    

    Template

    And your template looks like the template below:

    <template name="passageItem">
        <div class="passage">
            <div class="one-passage">
                <h4><a href= "{{pathFor 'onePassage'}}">{{title}}</a></h4>
                <div class="passage-content">
                    {{content}}
                </div>
            </div>
        </div>
    </template>
    

    The scope of 'this' in the template will be set to document returned by the Passages.findOne selector.

    If the template doesn't render that means you're either searching for passage that doesn't exist, or your passage is missing title or content fields.

    Rendered Function

    Now for the last part of your question. The scope of 'this' in a rendered function is set to the template instance. So if you need to access the template data try this:

    Template.passageItem.rendered = function() {
        console.log(this.data); // you should see your passage object in the console
    };