javascriptember.jspartialshtmlbars

Ember, how to reuse same "partial" for "index" and for "show"


This is the simplified version of my situation:

<!-- app/templates/charts/index.hbs -->
{{#each model as |chart|}}
  {{partial "charts/chart"}}
{{/each}}

<!-- app/templates/charts/show.hbs -->
{{partial "charts/chart"}}

<!-- app/templates/charts/-chart.hbs -->  
{{chart.title}}

The partial -chart.hbs works well for the index template but not for the show, because for the show the chart is into the variable model.

How can I fix this so I can reuse the same partial for index and for show?


Solution

  • It's more of a case for Ember Components, as far as I can see it.

    Let me explain a bit, to get you started.

    Components are bits of reusable code with some structure attached. That means a component will have:

    You can move your partial's template into a component (let's name it chart), like this:

    1. Move the code as it is into a new component template.
    2. Use variables/objects inside your template, as you probably do now
    3. Instead of rendering it with {{partial "charts/chart"}} do {{chart componentObject=localObject}}
    4. This will pass an external object (be it a model or whatever) to a component's context, as follows:

    _

    // context code:
    <h1>{{localobject.title}}</h1>
    
    {{chart componentObject=localObject}}
    
    // component code
    <p>{{componentObject.author}}</p>
    

    _

    You mileage may vary. Please feel free to comment and/or improve my answer :-)