Search code examples
javascriptmeteoriron-router

Iron-Router: One route for showing list and single article


At the moment I'm using two routes for displaying a list or the content of articles. So I got a route articles and a route article as there are two templates.

But isn't it possible to put everything in just one route?

I think the first route doesn't make sense, so there should only be '/article/:id' and if there is no id given, the list should be shown.

Route

Router.configure({
    layoutTemplate: 'layout',
});
Router.route('/articles', {
    name: 'articles',
    yieldTemplates: {
        'articleList':      { to: 'content' } 
    }
});
Router.route('/article/:_id', {
    name: 'article',
    yieldTemplates: {
        'contentPage':      { to: 'content' } 
    },
    onBeforeAction: function () { Session.set('articleID', this.params._id); this.next(); }
});

Template

<template name="layout">
    {{ > header}}
    {{ > yield 'content'}}
    {{ > footer}}
</template>

<template name="articles">
    <ul class="list">
        {{#each list}}
            <li><a href="/article/{{_id}}">{{title}}</a></li>
        {{/each}}
    </ul>
</template>

<template name="article">
    <h1 id="element" data-id="{{article._id}}">{{article.title}}</h1>
    <p>{{article.content}}</p>
</template>

Solution

  • It's possible, but I think you are confusing some terminology regarding what is a route. The following code:

    Router.route('/article', {
        ...
    })
    
    Router.route('/article/:_id', {
        ...
    })
    

    defines two routes, that both share the same base path: '/article'.

    Here is a meteorpad showing this in action.