How to make linkTo dynamic in ember?
<script type="text/x-handlebars" data-template-name="patient"> <ul class="nav"> {{#each menuItem in menuItems}} <li>{{#linkTo "dashboard.summary" menuItem}}{{menuItem.name}}{{/linkTo}}</li> {{/each}} </ul> {{outlet}} </script> In the above code, how to make linkTo dynamic link instead of the linkTo "dashboard.summary"? For example, "dashboard."+menuItem.name .
You can register a simple Handlebars helper that wraps the linkTo .
var linkTo = Ember.Handlebars.helpers.linkTo; Ember.Handlebars.registerHelper('myLinkTo', function(name, suffixPath) { var suffix = Ember.Handlebars.get(this, suffixPath); arguments = [].slice.call(arguments, 2); arguments.unshift(name + '.' + suffix); return linkTo.apply(this, arguments); }); Then in your template you can write:
{{#each menuItems}} <li>{{#myLinkTo "dashboard" name this}}{{name}}{{/myLinkTo}}</li> {{/each}} The helper will resolve the second argument and add it to the first, which is preceded by a dot.
Edit: this behavior can now be achieved without a special assistant. See c4p answer for a modern solution to this problem. The solution given above was last tested with Ember 1.0.0-rc.1.
In the current Ember (1.10 from this post), helpers now accept both quoted arguments and arguments that will be displayed as attributes in the current context. I believe this was changed in Ember 1.2 ( changelog ).
When quoting, the argument will be used as a string:
{{#link-to 'post'}}Posts{{/link-to}} If not specified, the argument will search in the current context:
{{#link-to routeName}}Go To '{{routeName}}'{{/link-to}} This will be a link to what indicates that the routeName property is currently set. This can be updated dynamically.
Here is a JSBin example showing this in action: http://emberjs.jsbin.com/nelafep/1/edit?html,css,js,output