• Stars
    star
    366
  • Rank 116,547 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated over 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Meteor Router

Meteor Router builds on page.js to provide reactive, filterable routing for Meteor applications.

NOTE

Note that the router package is deprecated. Work has now shifted to Iron Router. Please consider using IR instead of Router on new projects!

Installation

Meteor Router can be installed with Meteorite. From inside a Meteorite-managed app:

$ mrt add router

Note that Router version 0.4.3 works with Meteor 0.5.8 and later, and 0.4.2 works with Meteor 0.5.7 and earlier.

API

Basics

To get the current page:

Meteor.Router.page();

This is a reactive variable which will trigger invalidations as the app changes pages. Usually, you'll just want to render the template that corresponds to the current page using the following helper that finds the template by name:

{{> renderPage}}

It's common to render the inside page isolated from the layout:

{{#isolate}} {{> renderPage}} {{/isolate}}

To define a route, simply specify the URL it matches and the name of the template it should render. If you want to get fancy, you can specify a reactive function that returns a template name. It will get repeatedly executed as its reactive dependencies change.

Be careful not to specify your routes inside the Meteor.startup function, or the routing won't work for the first load.

Meteor.Router.add({
  '/news': 'news',

  '/about': function() {
    if (Session.get('aboutUs')) {
      return 'aboutUs';
    } else {
      return 'aboutThem';
    }
  },

  '*': 'not_found'
});

To navigate to such a URL from in the app, either create a link which links to the URL (the router will intercept clicks and trigger relevant state changes), or call directly:

Meteor.Router.to('/news');

Note that this doesn't reload the app, it instead uses HTML5 pushState to change the URL whilst remaining loaded.

Route functions

When the route function is called, this corresponds to a page.js Context object, allowing you to do the following:

Meteor.Router.add({
  'posts/:id': function(id) {
    console.log('we are at ' + this.canonicalPath);
    console.log("our parameters: " + this.params);

    // access parameters in order a function args too
    Session.set('currentPostId', id);
    return 'showPost';
  }
});

Named Routes

If you specify your route with simply a template name, then you'll set up a named route. So instead of calling Meteor.Router.to('/news'), you can call Meteor.Router.to('news') (news is the name of the route). Additionally, that named route sets up the following:

  • Meteor.Router.newsPath() -- which is /news in this case
  • Meteor.Router.newsUrl() -- which is http://yourhost.com/news
  • {{newsPath}} and {{newsUrl}} -- handlebars helpers

If you are using a routing function, you'll need to manually supply a route name, like so:

Meteor.Router.add({
  '/about': { as: 'about', to: function() {
    if (Session.get('aboutUs')) {
      return 'aboutUs';
    } else {
      return 'aboutThem';
    }
  }}
});

Meteor.Router.aboutPath(); // == '/about'

Additionally, you can provide a and property, which is a function that executes everytime the route executes (useful if your template is always the same, but you want to have some side effects):

Meteor.Router.add({
  '/posts/:_id': { to: 'showPost', and: function(id) {
    Session.set('currentPostId', id);
  }}
});

Meteor.Router.showPostPath(post) // == /posts/7

If your URL has named matches inside it, you can either pass in an object with those properties (e.g. post = {_id: 7} above), or you can pass the arguments in in order (e.g. showPostPath(7));

beforeRouting

Use Meteor.Router.beforeRouting = function() {} to set a callback to run before any routing function. Useful to reset session variables.

Filtering

The current system of filtering in this package is the equivalent of an after_filter in Rails. To add a filter which will render the correct template for a page which requires login:

Meteor.Router.filters({
  'checkLoggedIn': function(page) {
    if (Meteor.loggingIn()) {
      return 'loading';
    } else if (Meteor.user()) {
      return page;
    } else {
      return 'signin';
    }
  }
});

To turn the filter on, use one of:

// applies to all pages
Meteor.Router.filter('checkLoggedIn');

// applies to specific pages
Meteor.Router.filter('checkLoggedIn', {only: 'profile'});
Meteor.Router.filter('checkLoggedIn', {except: 'home'});

// accepts an array of pages
Meteor.Router.filter('checkLoggedIn', {only: ['profile', 'notifications'] });
Meteor.Router.filter('checkLoggedIn', {except: ['home', 'browse'] });

Note that filters build on reactivity. So the URL will not change but the user will see different pages as the state of the Meteor.user() property changes.

Server-side routing

The router also allows a very simple server side routing function with a similar API:

Meteor.Router.add('/posts/:id.xml', function(id) {
  return constructXMLForId(Posts.findOne(id));
});

Optionally you can also restrict the route by HTTP method:

Meteor.Router.add('/posts/:id.xml', 'GET', function(id) {
  return constructXMLForId(Posts.findOne(id));
});
Meteor.Router.add('/posts/:id.xml', 'DELETE', function(id) {
  Posts.remove(id);
  return [204, 'No Content'];
});

The arguments to the routing function are the parameters you've specified in your URL, and the this within the function is an object with three properties:

  • this.params -- the list of parameters, page.js style
  • this.request -- a Connect request
  • this.response -- a Connect response (use this to e.g. set headers on your response).

Your routing function can return one of the following:

  • a string, the body of the response
  • a number, the http status code
  • an array, in one of the following forms:
    • [body]
    • [statusCode, body]
    • [statusCode, headers, body], where headers is an object mapping header names to values.

Alternatively, rather than a routing function, you can just provide a fixed response:

Meteor.Router.add('/404', [404, "There's nothing here!"]);

The server side router adds the bodyParser middleware, enabling automatic parsing of JSON, Mutipart and URL encoded forms. You can tweak the Multipart parsing, i.e. changing the uploaded files destination directory:

Meteor.Router.configure({
  bodyParser: {
    uploadDir: 'uploads',
    hash: 'sha1'
  }
});

The configure() call MUST be put before any add() call, otherwise it will throw an error. For more information on options available, go to https://github.com/felixge/node-formidable

NOTE: Spark (meteor's template engine) does not currently run server side, so you are limited in what you can return here. Most likely you will want to return fairly simple things like JSON or XML documents, the construction of which is up to you.

Examples

Check out examples/simple-routed-app for an extremely simple example of a filtered routed app. (To run, use meteorite: cd examples/simple-routed-app; mrt run).

Additionally, you might want to read my blog post on page transitions in Meteor.

Internet explorer 8+ support

If you want the router to work in older version of Internet Explorer that don't support pushState, you can use the HTML5-History-API polyfill:

  mrt add HTML5-History-API

Older Versions of Meteor

(Versions prior to v0.8.0) use {{renderPage}} instead of {{>renderPage}}

Contributing

To run the tests, ensure that the router is checked out to a folder called router, and then simply run:

$ mrt test-packages router

More Repositories

1

create-graphql-server

Generate your GraphQL server one type at a time
JavaScript
322
star
2

meteor-paginated-subscription

JavaScript
64
star
3

meteor-cron

JavaScript
49
star
4

meteor-presence

JavaScript
44
star
5

meteor-transitioner

JavaScript
42
star
6

iron-transitioner

JavaScript
36
star
7

transition-helper

JavaScript
31
star
8

multi-app-accounts

JavaScript
28
star
9

meteor-models

JavaScript
25
star
10

meteor-accounts-anonymous

JavaScript
17
star
11

meteor-gravatar

JavaScript
13
star
12

ruby-ddp-client

Ruby
10
star
13

tasklist-demo

CSS
9
star
14

meteor-page-js

A straightforward wrapper around the excellent page.js.
JavaScript
7
star
15

meteor-HTML5-History-API

JavaScript
7
star
16

premailer-rails

A plugin to hook premailer into ActionMailer
Ruby
7
star
17

meteor-recorder

JavaScript
6
star
18

meteor-errors

JavaScript
5
star
19

edifice

Ruby
5
star
20

meteor-deps-extensions

JavaScript
4
star
21

tasklist-demo-server

JavaScript
4
star
22

meteor_nowrite

JavaScript
3
star
23

storybook-skeleton

JavaScript
3
star
24

react-leaderboard

JavaScript
3
star
25

spectral-clustering

Code for the paper Spectral Clustering with Inconsistent Advice
MATLAB
3
star
26

prototyping-with-meteor

JavaScript
3
star
27

yacwi

Yet Another Calendar Web Interface
Java
3
star
28

meteor-crypto-md5

JavaScript
3
star
29

acceptance-test-driver

JavaScript
3
star
30

meteor-svg

Experiments with svg and meteor
JavaScript
2
star
31

edifice-forms

Unobtrusive JS Form Extensions for rails 3.1
Ruby
2
star
32

css_timings

A little test framework to run CSS timing tests.
Ruby
2
star
33

meteor-page-js-ie-support

JavaScript
2
star
34

react-form

JavaScript
2
star
35

sketch

CoffeeScript
2
star
36

mongo-find-by-ids

Find a list of mongo documents from a list of ids
JavaScript
2
star
37

meteor-experiments

A series of small test apps to do performance experiments on
JavaScript
2
star
38

meteor-static

Simple python script to make a static bundle from a Meteor project
Python
1
star
39

tmeasday.github.com

Personal OS Website for Tom Coleman
HTML
1
star
40

league-mailer

Ruby
1
star
41

cursor-utils

JavaScript
1
star
42

helpers_vs_partials

A project testing the performance of helpers vs partials
Ruby
1
star
43

meteor-double-publication-remove-bug

JavaScript
1
star
44

uihooks-removed-element

JavaScript
1
star
45

test-smart-package

A smart package with a smart.json
JavaScript
1
star
46

meteor-location

JavaScript
1
star
47

react-todos

JavaScript
1
star
48

test-app-feb-13

JavaScript
1
star
49

mitreskiclub.com

1
star
50

simple-meteor-chromatic-app

JavaScript
1
star
51

storybook-708

JavaScript
1
star
52

video_tools

Tools for converting videos on OS X
Ruby
1
star
53

url_hash

Create url-embeddable hashes from integers
Ruby
1
star
54

astrograph

JavaScript
1
star
55

edifice-widgets

Widgets + Traits done the edifice way
Ruby
1
star
56

meteor-storybook-experiment

1
star
57

test

1
star
58

timeoutapp

JavaScript
1
star
59

cordova-demo

JavaScript
1
star
60

noodletools_mock

Ruby
1
star
61

sass_rails_slowness

A demonstration of the difference in compilation time between command line sass and rails sass
Ruby
1
star
62

shareabouts

JavaScript
1
star
63

iron-scroll

JavaScript
1
star
64

meteor-talk

JavaScript
1
star
65

meteor.com-mongo-backup

Python
1
star
66

meteor-trello-example

JavaScript
1
star
67

amble-clean

A clean rails 2.3 project with bits of amble
Ruby
1
star
68

percolate

the public facing website of percolatestudio.com
Ruby
1
star
69

bikespot

JavaScript
1
star