Search code examples
meteoriron-routerspacebars

Why isn't the URL being generated for this route?


So, I'm working on a Meteor project and I can't get this route to generate properly, or at all for that matter.

<template name="browseAll">
    <h3>List of classes with books available!</h3>
    <ul>
        {{#each aggCount}}
            <li><a href="{{ pathFor 'browse-class' }}">{{ _id }}</a> ({{ count }})</li>
        {{/each}}
    </ul>
</template>

The data that is being iterated over is a result of aggregation using MongoInternals, and that is as follows:

(server/methods.js excerpt):

classCount: function() {

    // Attempt aggregation of the books table to count by class, maybe.
    var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
    var col = db.collection("books");
    var aggregateSync = Meteor._wrapAsync(col.aggregate.bind(col));
    var pipeline = [
        {$group: {_id: "$class", count: {$sum: 1}}},
        {$sort: {_id: 1}}
    ];
    var theAnswer = aggregateSync(pipeline);
    return theAnswer;

}

It seems that the data is coming through okay, and sample data from aggregation (coming into the template) looks like this:

[ { _id: 'ADNR1234', count: 2 }, { _id: 'ARTH1234', count: 1 } ]

That's the template code I've got, and this is the route that it's supposed to be working with:

this.route('browse-class', {
    path: '/browse/:_class',
    data: function() {
        var booksCursor = Books.find({"class": this.params._class},{sort:{"createdAt": 1}});
        return {
            theClass: this.params._class,
            numBooks: booksCursor.count(),
            books: booksCursor
        };
    }
});

I don't understand it. The data is being SHOWN, and what I want to do is generate a URL for browse-class (route) that takes the value of {{ _id }} in the helper as a parameter, so as to generate something like this:

application.org/browse/CLSS


Solution

  • Be aware that {{pathFor}} must be called with a data context properly set :

    {{#with class}}
      {{pathFor "browse-class"}}
    {{/with}}
    

    Optionnaly it is possible to pass the data context as a parameter :

    {{pathFor "browse-class" class}}
    

    The data context provided to pathFor is used when generating the route path, if you defined a route path like this :

    path: "/browse/:_id"
    

    Then it will use the _id from the class to properly generate a URL.

    For the text of the link, I doubt you want to display the _id, your class documents probably include a "label" so you could use this :

    <a href="{{ pathFor 'browse-class' }}">{{ label }}</a>