Meteor Iron Router get Current Path from Route with Parameters in a Template Helper

Rico Leuthold picture Rico Leuthold · Nov 10, 2014 · Viewed 16.2k times · Source

In a Template Helper I get the current path from Iron.Router (iron:router) as follows:

Router.current().route.path()

This works fine, unless the route path does contain parameters (e.g. /client/:_id/edit). In that case the path() function returns null.

How do I get the current path within a Template Helper, when the route contains parameters?

I'm using Meteor 1.0 with iron:router1.0.1

Answer

saimeunt picture saimeunt · Nov 10, 2014

I suppose the _id in your route comes from a collection, you need to pass route.path the document the route is based on.

Router.route("/client/:_id/edit",{
  name:"edit",
  data:function(){
    return MyCollection.findOne(this.params._id);
  }
});

<template name="edit">
  {{myHelper}}
  {{pathFor route="edit"}}
</template>

Template.edit.helpers({
  myHelper:function(){
    return Router.current().route.path(this);
  }
});

I suggest you use the default pathFor helper for rendering an URL in the app.

https://github.com/EventedMind/iron-router/blob/devel/Guide.md#pathfor

This helper is using the current data context (in this case MyCollection.findOne(this.params._id)) to extract route parameters.

But you can also use the path method from the route, which takes the document you want to generate the path for as first argument.