Code duplicate on route

Hi community,

I currently have a piece of code that replicates multiple road ( 3 total - posts). Do you know if it is possible to create a specific function on Meteor ( in a helper ? ) Which I could not duplicate my code ?

`
// Home page
Router.route(’/’, {
name: ‘home’,
itemName: ‘Accueil’,
data: function(){

        // Si l'utilisateur n'est pas connecté
        if (!Meteor.user()) {

            // On affiche les articles non draftés
            var posts = Posts.find({
                draft: false
            });

        } else {

            // Sinon, les drafts sont affichés
            var posts = Posts.find();

        }

        return {
            posts: posts
        };

    },
    onAfterAction: function() {

        SEO.set({
            title: appSEO.seoSuffix,
            meta: {
                'description': 'une description'
            }
        });

    }
});


// Blog
Router.route('/blog', {
    name: 'blog',
    parent: 'home',
    itemName: 'Le blog',
    data: function(){

        // Si l'utilisateur n'est pas connecté
        if (!Meteor.user()) {

            // On affiche les articles non draftés
            var posts = Posts.find({
                draft: false
            });

        } else {

            // Sinon, les drafts sont affichés
            var posts = Posts.find();

        }

        return {
            posts: posts
        };

    },
    onAfterAction: function() {

        SEO.set({
            title: 'Le blog - ' + appSEO.seoSuffix,
            meta: {
                'description': 'une description'
            }
        });

    }
});`

Thank you !

Hi @leg3ndz

I haven’t tested this, but it looks like Iron Router provides Route Controllers for this:

###Route

Router.route('/post/:_id', {
  name: 'post.show',
  controller: 'CustomController'
});

Controller

CustomController = RouteController.extend({
  data: function () { return Posts.findOne({_id: this.params._id}) }
  // you can do anything you want to do for every route here
});

For more info, check the “Route Controllers” part from the docs.
http://iron-meteor.github.io/iron-router/

I think I should also mention this:
If you’re just starting out with iron router you might want to consider switching to flow router.
At the moment its the recommended router for meteor :slight_smile:

Also just in case you haven’t seen it yet:
Here’s the official Meteor Guide. It’s a ver handy resource full of best practices to have around.

works perfectly, thank you !

I’ll switch on flow router soon :slight_smile:

1 Like

You’re welcome. :slight_smile:

Yup, I think it’s a good idea. Seems like iron router is a thing of the past. Still works though :smiley: