Dynamically choosing a view at runtime with Ember + Handlebars

后端 未结 4 836
眼角桃花
眼角桃花 2021-02-04 20:10

I am using Ember, Ember Data, and Handlebars to display a timeline with a number of different types of models. My current implementation, though functioning properly, seems lik

4条回答
  •  遇见更好的自我
    2021-02-04 20:36

    This is what I used for a similar scenario.

    Model 'page' hasMany 'activity'.

    // App.PageModel
    export default DS.Model.extend({
        index     : DS.attr('number'),
        activity  : DS.hasMany('activity',  { async: true })
    });
    

    Model 'activity' has property 'type' that references which template to use for the content in another property 'configuration'.

    // App.ActivityModel
    export default DS.Model.extend({
        activityId    : DS.attr('string'),
        type          : DS.attr('string'),
        page          : DS.belongsTo('page', { async: true }),
        configuration : DS.attr()
    });
    

    Note the lack of attribute type for configuration. This offers the means of storing a collection of randomly structured objects. For consistently structured objects, I suggest using Ember-Data.Model-Fragments.

    Main template:

    {{! page.hbs }}
    {{#with activity}}
        {{#each}}
            {{partial type}}
        {{/each}}
    {{/with}}
    

    For type: 'static', it uses the {{{3 mustache option}}} to render a html string.

    {{! static.hbs }}
    {{{configuration.content}}}
    

    The other options are far more complex, yet still simplified using a 'with'. ie: for type: 'multiplechoice',

    {{! multiplechoice.hbs }}
    {{#with configuration}}
        {{#each options}}
        
        {{/each}}
        {{ ...etc... }}
    {{/with}}
    

    With the partials, remember to consider nomenclature and/or folder structure depending on your environment, ie '_partialname.hbs' or 'viewname/partialname.hbs'

提交回复
热议问题