EmberJS - How to dynamically generate link with linkTo?

我与影子孤独终老i 提交于 2020-01-21 11:12:06

问题


Is there a way to dynamically generate a link using the link-to helper by passing a variable with the route path?

For example, instead of hard coding the path like this:

{{#linkTo "route.subroute" model}}{{model.title}}{{/linkTo}}

I want to be able to pass the link-to helper a variable which holds the path like this:

{{#linkTo destination model}}{{model.title}}{{/linkTo}}

The use case for this is to allow me to consolidate templates which only differ by this path. For instance, if there are two collections each with a different destination. When rendered with the each helper the templates are the same except for the path in the link-to.

If I could save this variable in the view’s controller and pass it, I could use only one template for both the lists.

I have thought about manually constructing the path like this:

<a {{bindAttr href="destination"}}>{{model.title}}</a>

But this does not have the integration with the router to determine the active state which I need.


回答1:


Is there a way to dynamically generate a link using the linkTo helper by passing a variable with the route path?

Not at the moment.

The use case for this is to allow me to consolidate templates which only differ by this path. For instance, if there are two collections each with a different destination.

Agreed this is a valid use case, I would expect linkTo helper to support it in future. Meantime since you've only got two collections you could accomplish this with conditionals in the template

{{#if isRouteOne}}
  {{#linkTo "routeOne.subrouteOne" model}}{{model.title}}{{/linkTo}}
{{else}}
  {{#linkTo "routeTwo.subrouteTwo" model}}{{model.title}}{{/linkTo}}
{{/if}}



回答2:


Instead of {{linkTo}},you can use {{action}} and handle the event of transition by route name specify in destination property of model.




回答3:


There is another very similar SO Question in which I answer this question. The solution is possible using the inline version of the link-to helper.

In this situation, we would have:

{{link-to model.title destination model}}

Which would be compiled to:

<a href="#/route/subroute/3856">
  Click me
</a>


来源:https://stackoverflow.com/questions/16021148/emberjs-how-to-dynamically-generate-link-with-linkto

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!