6
votes

I want to create a component which needs to generate dynamics links. I tried passing the link data as an array, but this does not work.

var user1 = get("store").find("user", 1);
var data = {link: ["users.show", user1], title: "User1"};

{{#link-to data.link}}{{data.title}}{{/link-to}}

This should be equal to

{{#link-to "users.show" 1}}{{data.title}}{{/link-to}}

How to generate fully dynamic links from a variable?

3
I think link-to won't work for that, you might need create a custom helper, or use a function in a controller that 'Transitions' to the given route. Take a look here github.com/emberjs/ember.js/blob/master/packages/ember-routing/… you can use the 'recognizer' to recognize the given path, you'll get a handler, and then transition to that route.fanta

3 Answers

8
votes

You can specify an array as params argument into a link-to helper. Similar to nickiaconis' answer answer, but with just the default {{link-to}} helper:

{{#link-to params=data.link}}{{data.title}}{{/link-to}}

...will render something like:

<a href="/users/show/1">User1</a>

(tested with Ember 2.3.0)

3
votes

Ember 1.13.x

The LinkComponent, which is what the link-to helper creates for you, is exposed as -link-to. I've created an example of its use here: http://emberjs.jsbin.com/rinukefuqe/2/edit?html,js,output

{{#-link-to params=(unbound link) hasBlock="true"}}
  {{title}}
{{/-link-to}}

The params attribute is what the link-to helper normally bundles your positional parameters onto, although you must use the unbound helper here because the LinkComponent expects params to be an array rather than a value binding object. Additionally, the determination of use as block or inline component is not built into components yet, so you must pass hasBlock="true" unless you include the link text as the first parameter in your array.


Ember ≤ 1.12.x

Although it is not done already, you can manually expose the LinkView component, which is the equivalent of the new LinkComponent.

App.XLinkToComponent = Ember.LinkView.extend();

Then use it like:

{{#x-link-to params=link}}
  {{title}}
{{/x-link-to}}

Using unbound and hasBlock="true" are not necessary as the internal logic of LinkView differs from LinkComponent.

0
votes

I think that isn't possible to pass an array, but you can pass each argument directlly, like the following:

route

  var user1 = this.store.find('user', 1);
  var data = { data: { link: "users.show", model: user1, title: "User1" } };
  return data;

template

  {{#link-to data.link data.model.id}}{{data.title}}{{/link-to}}

I hope it helps