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

2

14

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

Marcin answered 10/11, 2014 at 18:38 Comment(1)
This sounds like a bug with Iron-Router itself. I would put something on their issues board on GitHub.Anglesite
G
14

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.

Grissel answered 10/11, 2014 at 18:50 Comment(1)
Perfect and detailed answer, thanks. I need the path in the context of navigation / highlighting certain items. I already had the setup exactly like you show it in the example, but did not know about the document (this) argument for the path function.Marcin
C
8

Try the following alternative:

Iron.Location.get().path;

Works fine for me, when I need a path with parameters. Does not return the current route, though.

See Meteor Iron Router does not get Current Path from Route

Chancre answered 31/7, 2015 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.