Search code examples
ractivejs

How to feed data into a dynamic Ractive component?


I am creating a page that displays Ractive components specified from a JSON blueprint, and need some help passing the right data into the components.

I understand in the simplest case how to pass data into a component:

(e.g., <dog theData={{theData}} />)

But in this case, I am using a Ractive.extend function to provide the component to a loop, and have tried many things to get the right data to each component to no avail.

This fiddle should explain it: https://jsfiddle.net/4kax8dLo/7/

In the “getComponent” function, I need to use “this” to locate the appropriate data under “homePageSections” and feed this data into the component.

If successful, the page should say “the navText is yee haa.”

(If these seems like an overcomplicated way to put stuff on a page, let me know and I can detail the use case. There might be a simpler, more elegant way to achieve the goal.)

Grateful for any guidance or advice!


Solution

  • Are you sure you need components at all? From your example it seems you would do good with just partials (http://docs.ractivejs.org/latest/partials).

    If that's the case, I've modified your example a little bit to make it working with the partial approach. https://jsfiddle.net/cxnhtxLy/

    Defining the partials:

    partials: { 
      dog: '{{#with theData}}<h3>the dog is a <span style="color: {{color}};">{{dogType}}</span> and this works fine</h3>{{/with}}',
      topHomeNav: '<div>the navText is: {{data.navText}} </div>',
      heroUnit:'<div><h2>THE HERO TITLE IS:</h2><br />{{data.heroTitle}}</div>',
      filterResults: '<div>filter results: </div>',
      pageFooter:'<div>footertext is: {{data.footertext}}</div>'
    }
    

    Your loop for printing them:

    {{#each homePageData.views[currentView]}}
    {{#with homePageData.homePageSections[this]}}
        {{> this.partial}}
    {{/with}}
    {{/each}}
    

    That being said, you could probably refactor your code to look quite alot cleaner if you're satisfied partials is all you need for the task.

    UPDATE: This is the fiddle working with components. https://jsfiddle.net/grkgb0sr/ See comments below for more backstory.