How to load partials / views / templates dynamically in Ember.js

后端 未结 4 1510
耶瑟儿~
耶瑟儿~ 2021-02-04 14:14

So I have the following setup.

On the main page, a list of generators is being displayed based on a list coming from a model using fixture data.

Now when one of

相关标签:
4条回答
  • 2021-02-04 15:04

    You can create a dynamic partial helper that uses the passed in name to render with the {{partial}} helper.

    Ember.Handlebars.helper('dynPartial', function(name, options) {
      return Ember.Handlebars.helpers.partial.apply(this, arguments);
    });
    

    Then use this dynamic partial, {{dynPartial}} instead.

    {{#each item in controller}}
      {{dynPartial item.templateName}}
    {{/each}}
    

    For a generator with templateName of generator-1. This would render with the partial _generator-1. Note that the name of the template's id/data-template-name must begin with an underscore.

    0 讨论(0)
  • 2021-02-04 15:09

    You should be able to simply place your dynamic partial variable within the partial helper.

    {{#each item in controller}}
        {{partial item.templateName}}
    {{/each}}
    

    As @darshan-sawardekar pointed out if you have a generator with templateName of generator-1it would render the partial _generator-1.

    0 讨论(0)
  • 2021-02-04 15:09

    While @Darshan's answer is simpler than the below and will work in many cases, I just ran into an issue where transitioning to a same route with a different model causes the partial to not re-render if the second model's partial name is the same as the first's (bug in ember?). Setting up a view that watches the model fixes this.

    App.FooDynamicLayout = Ember.View.extend
      rerenderOnModelChange: (->
        @rerender()
      ).observes('model')
    

    And call it with:

    view App.FooDynamicLayout templateName=dynamicTemplateName model=model
    
    0 讨论(0)
  • 2021-02-04 15:12

    @KamrenZ already mentioned this but I figured I'd cite chapter and verse for those looking into this. More recent versions of Ember gracefully accept bound property names and use them in the partial helper:

    http://ember-doc.com/classes/Ember.Handlebars.helpers.html#method_partial

    BOUND TEMPLATE NAMES The parameter supplied to partial can also be a path to a property containing a template name, e.g.:

    {{partial someTemplateName}}
    

    The above example will look up the value of someTemplateName on the template context (e.g. a controller) and use that value as the name of the template to render. If the resolved value is falsy, nothing will be rendered. If someTemplateName changes, the partial will be re-rendered using the new template name.

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