How to make linkTo dynamic in ember?

前端 未结 2 1824
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 23:53


        
相关标签:
2条回答
  • 2020-12-18 00:20

    In the current Ember (1.10 as of this post), helpers now accept both quoted arguments or arguments that will be looked up as attributes in the current context. I believe this was changed in Ember 1.2 ( change log ).

    If quoted, the argument will be used as a string:

    {{#link-to 'post'}}Posts{{/link-to}}
    

    If not quoted, the argument will be looked up in the current context:

    {{#link-to routeName}}Go To '{{routeName}}'{{/link-to}}
    

    This will be a link-to that points to whatever the routeName property currently is set to. This can be updated dynamically.

    Here is an example JSBin showing this in action: http://emberjs.jsbin.com/nelafep/1/edit?html,css,js,output

    0 讨论(0)
  • 2020-12-18 00:32

    You could register a simple Handlebars helper that wraps the linkTo helper.

    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 could write:

    {{#each menuItems}}
        <li>{{#myLinkTo "dashboard" name this}}{{name}}{{/myLinkTo}}</li>
    {{/each}}
    

    The helper will resolve the second argument and append it to the first, preceded by a dot.

    Edit: this behaviour can now be achieved without a custom helper. See c4p's answer for the contemporary solution to this problem. The solution above was last tested with Ember 1.0.0-rc.1.

    0 讨论(0)
提交回复
热议问题